blob: 318123edcdf1c00ea08649b38021a1f55f64de83 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
jeffhao10037c82012-01-23 15:06:23 -080016
17#include "dex_file_verifier.h"
18
Andreas Gampee6215c02015-08-31 18:54:38 -070019#include <inttypes.h>
Narayan Kamath92572be2013-11-28 14:06:24 +000020#include <zlib.h>
Andreas Gampee6215c02015-08-31 18:54:38 -070021
David Sehr28e74ed2016-11-21 12:52:12 -080022#include <limits>
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Narayan Kamath92572be2013-11-28 14:06:24 +000024
Andreas Gampe46ee31b2016-12-14 10:11:49 -080025#include "android-base/stringprintf.h"
26
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "dex_file-inl.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070028#include "experimental_flags.h"
jeffhao10037c82012-01-23 15:06:23 -080029#include "leb128.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070030#include "safe_map.h"
Ian Rogersa6724902013-09-23 09:23:37 -070031#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "utils.h"
jeffhao10037c82012-01-23 15:06:23 -080033
34namespace art {
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036using android::base::StringAppendV;
37using android::base::StringPrintf;
38
David Sehr28e74ed2016-11-21 12:52:12 -080039static constexpr uint32_t kTypeIdLimit = std::numeric_limits<uint16_t>::max();
40
41static bool IsValidOrNoTypeId(uint16_t low, uint16_t high) {
42 return (high == 0) || ((high == 0xffffU) && (low == 0xffffU));
43}
44
45static bool IsValidTypeId(uint16_t low ATTRIBUTE_UNUSED, uint16_t high) {
46 return (high == 0);
47}
48
jeffhao10037c82012-01-23 15:06:23 -080049static uint32_t MapTypeToBitMask(uint32_t map_type) {
50 switch (map_type) {
51 case DexFile::kDexTypeHeaderItem: return 1 << 0;
52 case DexFile::kDexTypeStringIdItem: return 1 << 1;
53 case DexFile::kDexTypeTypeIdItem: return 1 << 2;
54 case DexFile::kDexTypeProtoIdItem: return 1 << 3;
55 case DexFile::kDexTypeFieldIdItem: return 1 << 4;
56 case DexFile::kDexTypeMethodIdItem: return 1 << 5;
57 case DexFile::kDexTypeClassDefItem: return 1 << 6;
58 case DexFile::kDexTypeMapList: return 1 << 7;
59 case DexFile::kDexTypeTypeList: return 1 << 8;
60 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9;
61 case DexFile::kDexTypeAnnotationSetItem: return 1 << 10;
62 case DexFile::kDexTypeClassDataItem: return 1 << 11;
63 case DexFile::kDexTypeCodeItem: return 1 << 12;
64 case DexFile::kDexTypeStringDataItem: return 1 << 13;
65 case DexFile::kDexTypeDebugInfoItem: return 1 << 14;
66 case DexFile::kDexTypeAnnotationItem: return 1 << 15;
67 case DexFile::kDexTypeEncodedArrayItem: return 1 << 16;
68 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17;
69 }
70 return 0;
71}
72
73static bool IsDataSectionType(uint32_t map_type) {
74 switch (map_type) {
75 case DexFile::kDexTypeHeaderItem:
76 case DexFile::kDexTypeStringIdItem:
77 case DexFile::kDexTypeTypeIdItem:
78 case DexFile::kDexTypeProtoIdItem:
79 case DexFile::kDexTypeFieldIdItem:
80 case DexFile::kDexTypeMethodIdItem:
81 case DexFile::kDexTypeClassDefItem:
82 return false;
83 }
84 return true;
85}
86
Andreas Gampe8a0128a2016-11-28 07:38:35 -080087const char* DexFileVerifier::CheckLoadStringByIdx(dex::StringIndex idx, const char* error_string) {
88 if (UNLIKELY(!CheckIndex(idx.index_, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070089 return nullptr;
90 }
91 return dex_file_->StringDataByIdx(idx);
92}
93
Orion Hodson6c4921b2016-09-21 15:41:06 +010094// Try to find the name of the method with the given index. We do not want to rely on DexFile
95// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
96// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
97// (flagged by the return value), otherwise error_msg will contain an error string.
98static bool FindMethodName(uint32_t method_index,
99 const uint8_t* begin,
100 const DexFile::Header* header,
101 const char** str,
102 std::string* error_msg) {
103 if (method_index >= header->method_ids_size_) {
104 *error_msg = "Method index not available for method flags verification";
105 return false;
106 }
107 uint32_t string_idx =
108 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
109 method_index)->name_idx_.index_;
110 if (string_idx >= header->string_ids_size_) {
111 *error_msg = "String index not available for method flags verification";
112 return false;
113 }
114 uint32_t string_off =
115 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
116 string_data_off_;
117 if (string_off >= header->file_size_) {
118 *error_msg = "String offset out of bounds for method flags verification";
119 return false;
120 }
121 const uint8_t* str_data_ptr = begin + string_off;
122 uint32_t dummy;
123 if (!DecodeUnsignedLeb128Checked(&str_data_ptr, begin + header->file_size_, &dummy)) {
124 *error_msg = "String size out of bounds for method flags verification";
125 return false;
126 }
127 *str = reinterpret_cast<const char*>(str_data_ptr);
128 return true;
129}
130
131// Gets constructor flags based on the |method_name|. Returns true if
132// method_name is either <clinit> or <init> and sets
133// |constructor_flags_by_name| appropriately. Otherwise set
134// |constructor_flags_by_name| to zero and returns whether
135// |method_name| is valid.
136bool GetConstructorFlagsForMethodName(const char* method_name,
137 uint32_t* constructor_flags_by_name) {
138 if (method_name[0] != '<') {
139 *constructor_flags_by_name = 0;
140 return true;
141 }
142 if (strcmp(method_name + 1, "clinit>") == 0) {
143 *constructor_flags_by_name = kAccStatic | kAccConstructor;
144 return true;
145 }
146 if (strcmp(method_name + 1, "init>") == 0) {
147 *constructor_flags_by_name = kAccConstructor;
148 return true;
149 }
150 *constructor_flags_by_name = 0;
151 return false;
152}
153
Andreas Gampea5b09a62016-11-17 15:21:22 -0800154const char* DexFileVerifier::CheckLoadStringByTypeIdx(dex::TypeIndex type_idx,
155 const char* error_string) {
156 if (UNLIKELY(!CheckIndex(type_idx.index_, dex_file_->NumTypeIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700157 return nullptr;
158 }
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800159 return CheckLoadStringByIdx(dex_file_->GetTypeId(type_idx).descriptor_idx_, error_string);
Andreas Gampee09269c2014-06-06 18:45:35 -0700160}
161
162const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -0700163 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700164 return nullptr;
165 }
166 return &dex_file_->GetFieldId(idx);
167}
168
169const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -0700170 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700171 return nullptr;
172 }
173 return &dex_file_->GetMethodId(idx);
174}
175
Orion Hodson6c4921b2016-09-21 15:41:06 +0100176const DexFile::ProtoId* DexFileVerifier::CheckLoadProtoId(uint32_t idx, const char* err_string) {
177 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumProtoIds(), err_string))) {
178 return nullptr;
179 }
180 return &dex_file_->GetProtoId(idx);
181}
182
Andreas Gampee09269c2014-06-06 18:45:35 -0700183// Helper macro to load string and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700184#define LOAD_STRING(var, idx, error) \
185 const char* (var) = CheckLoadStringByIdx(idx, error); \
186 if (UNLIKELY((var) == nullptr)) { \
187 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700188 }
189
190// Helper macro to load string by type idx and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700191#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
192 const char* (var) = CheckLoadStringByTypeIdx(type_idx, error); \
193 if (UNLIKELY((var) == nullptr)) { \
194 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700195 }
196
197// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700198#define LOAD_METHOD(var, idx, error_string, error_stmt) \
199 const DexFile::MethodId* (var) = CheckLoadMethodId(idx, error_string); \
200 if (UNLIKELY((var) == nullptr)) { \
201 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700202 }
203
204// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700205#define LOAD_FIELD(var, idx, fmt, error_stmt) \
206 const DexFile::FieldId* (var) = CheckLoadFieldId(idx, fmt); \
207 if (UNLIKELY((var) == nullptr)) { \
208 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700209 }
210
Aart Bik37d6a3b2016-06-21 18:30:10 -0700211bool DexFileVerifier::Verify(const DexFile* dex_file,
212 const uint8_t* begin,
213 size_t size,
214 const char* location,
215 bool verify_checksum,
216 std::string* error_msg) {
217 std::unique_ptr<DexFileVerifier> verifier(
218 new DexFileVerifier(dex_file, begin, size, location, verify_checksum));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700219 if (!verifier->Verify()) {
220 *error_msg = verifier->FailureReason();
221 return false;
222 }
223 return true;
224}
225
226bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
227 bool is_return_type) {
jeffhao10037c82012-01-23 15:06:23 -0800228 switch (shorty_char) {
229 case 'V':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700230 if (UNLIKELY(!is_return_type)) {
231 ErrorStringPrintf("Invalid use of void");
jeffhao10037c82012-01-23 15:06:23 -0800232 return false;
233 }
Ian Rogersfc787ec2014-10-09 21:56:44 -0700234 FALLTHROUGH_INTENDED;
jeffhao10037c82012-01-23 15:06:23 -0800235 case 'B':
236 case 'C':
237 case 'D':
238 case 'F':
239 case 'I':
240 case 'J':
241 case 'S':
242 case 'Z':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700243 if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
244 ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
245 shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800246 return false;
247 }
248 break;
249 case 'L':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700250 if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
251 ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800252 return false;
253 }
254 break;
255 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700256 ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
jeffhao10037c82012-01-23 15:06:23 -0800257 return false;
258 }
259 return true;
260}
261
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700262bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700263 const char* label) {
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700264 // Check that size is not 0.
265 CHECK_NE(elem_size, 0U);
266
Ian Rogers13735952014-10-08 12:43:28 -0700267 const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
268 const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700269
270 // Check for overflow.
271 uintptr_t max = 0 - 1;
272 size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
273 size_t max_count = available_bytes_till_end_of_mem / elem_size;
274 if (max_count < count) {
275 ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
276 static_cast<size_t>(range_start - file_start),
277 count, elem_size);
278 return false;
279 }
280
Ian Rogers13735952014-10-08 12:43:28 -0700281 const uint8_t* range_end = range_start + count * elem_size;
282 const uint8_t* file_end = file_start + size_;
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700283 if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
284 // Note: these two tests are enough as we make sure above that there's no overflow.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800285 ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
Ian Rogerse3d55812014-06-11 13:00:44 -0700286 static_cast<size_t>(range_start - file_start),
287 static_cast<size_t>(range_end - file_start));
jeffhao10037c82012-01-23 15:06:23 -0800288 return false;
289 }
290 return true;
291}
292
Ian Rogers13735952014-10-08 12:43:28 -0700293bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700294 // Check that the list is available. The first 4B are the count.
295 if (!CheckListSize(*ptr, 1, 4U, label)) {
296 return false;
297 }
298
299 uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
300 if (count > 0) {
301 if (!CheckListSize(*ptr + 4, count, element_size, label)) {
302 return false;
303 }
304 }
305
306 *ptr += 4 + count * element_size;
307 return true;
308}
309
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700310bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
311 if (UNLIKELY(field >= limit)) {
312 ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
jeffhao10037c82012-01-23 15:06:23 -0800313 return false;
314 }
315 return true;
316}
317
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800318bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
319 uint32_t size,
320 size_t alignment,
321 const char* label) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700322 if (size == 0) {
323 if (offset != 0) {
324 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
325 return false;
326 }
327 }
328 if (size_ <= offset) {
329 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
330 return false;
331 }
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800332 if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
333 ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
334 return false;
335 }
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700336 return true;
337}
338
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100339bool DexFileVerifier::CheckSizeLimit(uint32_t size, uint32_t limit, const char* label) {
340 if (size > limit) {
341 ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label);
342 return false;
343 }
344 return true;
345}
346
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700347bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800348 // Check file size from the header.
349 uint32_t expected_size = header_->file_size_;
350 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700351 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800352 return false;
353 }
354
355 // Compute and verify the checksum in the header.
356 uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
357 const uint32_t non_sum = sizeof(header_->magic_) + sizeof(header_->checksum_);
Ian Rogers13735952014-10-08 12:43:28 -0700358 const uint8_t* non_sum_ptr = reinterpret_cast<const uint8_t*>(header_) + non_sum;
jeffhaof6174e82012-01-31 16:14:17 -0800359 adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
jeffhao10037c82012-01-23 15:06:23 -0800360 if (adler_checksum != header_->checksum_) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700361 if (verify_checksum_) {
362 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
363 return false;
364 } else {
365 LOG(WARNING) << StringPrintf(
366 "Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
367 }
jeffhao10037c82012-01-23 15:06:23 -0800368 }
369
370 // Check the contents of the header.
371 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700372 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800373 return false;
374 }
375
376 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700377 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800378 return false;
379 }
380
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700381 // Check that all offsets are inside the file.
382 bool result =
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800383 CheckValidOffsetAndSize(header_->link_off_,
384 header_->link_size_,
385 0 /* unaligned */,
386 "link") &&
387 CheckValidOffsetAndSize(header_->map_off_,
388 header_->map_off_,
389 4,
390 "map") &&
391 CheckValidOffsetAndSize(header_->string_ids_off_,
392 header_->string_ids_size_,
393 4,
394 "string-ids") &&
395 CheckValidOffsetAndSize(header_->type_ids_off_,
396 header_->type_ids_size_,
397 4,
398 "type-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100399 CheckSizeLimit(header_->type_ids_size_, DexFile::kDexNoIndex16, "type-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800400 CheckValidOffsetAndSize(header_->proto_ids_off_,
401 header_->proto_ids_size_,
402 4,
403 "proto-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100404 CheckSizeLimit(header_->proto_ids_size_, DexFile::kDexNoIndex16, "proto-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800405 CheckValidOffsetAndSize(header_->field_ids_off_,
406 header_->field_ids_size_,
407 4,
408 "field-ids") &&
409 CheckValidOffsetAndSize(header_->method_ids_off_,
410 header_->method_ids_size_,
411 4,
412 "method-ids") &&
413 CheckValidOffsetAndSize(header_->class_defs_off_,
414 header_->class_defs_size_,
415 4,
416 "class-defs") &&
417 CheckValidOffsetAndSize(header_->data_off_,
418 header_->data_size_,
419 0, // Unaligned, spec doesn't talk about it, even though size
420 // is supposed to be a multiple of 4.
421 "data");
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700422 return result;
jeffhao10037c82012-01-23 15:06:23 -0800423}
424
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700425bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700426 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
427 header_->map_off_);
428 // Check that map list content is available.
429 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
430 return false;
431 }
432
jeffhao10037c82012-01-23 15:06:23 -0800433 const DexFile::MapItem* item = map->list_;
434
435 uint32_t count = map->size_;
436 uint32_t last_offset = 0;
437 uint32_t data_item_count = 0;
438 uint32_t data_items_left = header_->data_size_;
439 uint32_t used_bits = 0;
440
441 // Sanity check the size of the map list.
442 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
443 return false;
444 }
445
446 // Check the items listed in the map.
447 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700448 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
449 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800450 return false;
451 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700452 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
453 ErrorStringPrintf("Map item after end of file: %x, size %x",
454 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800455 return false;
456 }
457
458 if (IsDataSectionType(item->type_)) {
459 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700460 if (UNLIKELY(icount > data_items_left)) {
461 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800462 return false;
463 }
464 data_items_left -= icount;
465 data_item_count += icount;
466 }
467
468 uint32_t bit = MapTypeToBitMask(item->type_);
469
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700470 if (UNLIKELY(bit == 0)) {
471 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800472 return false;
473 }
474
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700475 if (UNLIKELY((used_bits & bit) != 0)) {
476 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800477 return false;
478 }
479
480 used_bits |= bit;
481 last_offset = item->offset_;
482 item++;
483 }
484
485 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700486 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
487 ErrorStringPrintf("Map is missing header entry");
jeffhao10037c82012-01-23 15:06:23 -0800488 return false;
489 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700490 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
491 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800492 return false;
493 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700494 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
495 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
496 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800497 return false;
498 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700499 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
500 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
501 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800502 return false;
503 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700504 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
505 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
506 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800507 return false;
508 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700509 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
510 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
511 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800512 return false;
513 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700514 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
515 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
516 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800517 return false;
518 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700519 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
520 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
521 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800522 return false;
523 }
jeffhao10037c82012-01-23 15:06:23 -0800524 return true;
525}
526
527uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
528 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700529 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700530 for (uint32_t i = 0; i < size; i++) {
531 result |= ((uint32_t) *(ptr_++)) << (i * 8);
532 }
jeffhao10037c82012-01-23 15:06:23 -0800533 }
jeffhao10037c82012-01-23 15:06:23 -0800534 return result;
535}
536
Andreas Gampebed6daf2016-09-02 18:12:00 -0700537
538#define DECODE_UNSIGNED_CHECKED_FROM_WITH_ERROR_VALUE(ptr, var, error_value) \
539 uint32_t var; \
Andreas Gampe44fd2352016-11-03 08:21:21 -0700540 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700541 return error_value; \
542 }
543
Andreas Gampe44fd2352016-11-03 08:21:21 -0700544#define DECODE_UNSIGNED_CHECKED_FROM(ptr, var) \
545 uint32_t var; \
546 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
547 ErrorStringPrintf("Read out of bounds"); \
548 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700549 }
550
Andreas Gampe44fd2352016-11-03 08:21:21 -0700551#define DECODE_SIGNED_CHECKED_FROM(ptr, var) \
552 int32_t var; \
553 if (!DecodeSignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
554 ErrorStringPrintf("Read out of bounds"); \
555 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700556 }
557
jeffhao10037c82012-01-23 15:06:23 -0800558bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700559 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700560 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800561
562 for (uint32_t i = 0; i < handlers_size; i++) {
563 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800564 size_t offset = ptr_ - handlers_base;
Andreas Gampebed6daf2016-09-02 18:12:00 -0700565 DECODE_SIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800566
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700567 if (UNLIKELY((size < -65536) || (size > 65536))) {
568 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800569 return false;
570 }
571
572 if (size <= 0) {
573 catch_all = true;
574 size = -size;
575 } else {
576 catch_all = false;
577 }
578
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800579 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800580
581 while (size-- > 0) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700582 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -0800583 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
584 return false;
585 }
586
Andreas Gampebed6daf2016-09-02 18:12:00 -0700587 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700588 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
589 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800590 return false;
591 }
592 }
593
594 if (catch_all) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700595 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700596 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
597 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800598 return false;
599 }
600 }
601 }
602
603 return true;
604}
605
Andreas Gampee6215c02015-08-31 18:54:38 -0700606bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
607 uint32_t access_flags,
608 uint32_t class_access_flags,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800609 dex::TypeIndex class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700610 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700611 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800612 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
613 return false;
614 }
615
Andreas Gampee6215c02015-08-31 18:54:38 -0700616 // Check that it's the right class.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800617 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700618 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
619 class_idx_;
620 if (class_type_index != my_class_index) {
621 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800622 my_class_index.index_,
623 class_type_index.index_);
Andreas Gampee6215c02015-08-31 18:54:38 -0700624 return false;
625 }
626
627 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800628 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700629 if (UNLIKELY(is_static != expect_static)) {
630 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800631 return false;
632 }
633
Andreas Gampee6215c02015-08-31 18:54:38 -0700634 // Check field access flags.
635 std::string error_msg;
Andreas Gampec9f0ba12016-02-09 09:21:04 -0800636 if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700637 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800638 return false;
639 }
640
641 return true;
642}
643
Andreas Gampee6215c02015-08-31 18:54:38 -0700644bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
645 uint32_t access_flags,
646 uint32_t class_access_flags,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800647 dex::TypeIndex class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700648 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700649 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700650 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700651 DCHECK(direct_method_indexes != nullptr);
652 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800653 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
654 return false;
655 }
656
Andreas Gampee6215c02015-08-31 18:54:38 -0700657 // Check that it's the right class.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800658 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700659 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
660 class_idx_;
661 if (class_type_index != my_class_index) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700662 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 " vs %" PRIu16,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800663 my_class_index.index_,
664 class_type_index.index_);
jeffhao10037c82012-01-23 15:06:23 -0800665 return false;
666 }
667
Andreas Gampee6215c02015-08-31 18:54:38 -0700668 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700669 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700670 direct_method_indexes->insert(idx);
671 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700672 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
673 return false;
674 }
675
Andreas Gampee6215c02015-08-31 18:54:38 -0700676 std::string error_msg;
Orion Hodson6c4921b2016-09-21 15:41:06 +0100677 const char* method_name;
678 if (!FindMethodName(idx, begin_, header_, &method_name, &error_msg)) {
679 ErrorStringPrintf("%s", error_msg.c_str());
680 return false;
681 }
682
683 uint32_t constructor_flags_by_name = 0;
684 if (!GetConstructorFlagsForMethodName(method_name, &constructor_flags_by_name)) {
685 ErrorStringPrintf("Bad method name: %s", method_name);
686 return false;
687 }
688
689 bool has_code = (code_offset != 0);
Andreas Gampee6215c02015-08-31 18:54:38 -0700690 if (!CheckMethodAccessFlags(idx,
691 access_flags,
692 class_access_flags,
Orion Hodson6c4921b2016-09-21 15:41:06 +0100693 constructor_flags_by_name,
Andreas Gampee6215c02015-08-31 18:54:38 -0700694 has_code,
695 expect_direct,
696 &error_msg)) {
697 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800698 return false;
699 }
700
Orion Hodson6c4921b2016-09-21 15:41:06 +0100701 if (constructor_flags_by_name != 0) {
702 if (!CheckConstructorProperties(idx, constructor_flags_by_name)) {
703 DCHECK(FailureReasonIsSet());
704 return false;
705 }
706 }
707
jeffhao10037c82012-01-23 15:06:23 -0800708 return true;
709}
710
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800711bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800712 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700713 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800714 return false;
715 }
716 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700717 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800718 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800719 return false;
720 }
721 ptr_++;
722 offset++;
723 }
724 }
725 return true;
726}
727
728bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700729 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800730 return false;
731 }
732
733 uint8_t header_byte = *(ptr_++);
734 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
735 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
736
737 switch (value_type) {
738 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700739 if (UNLIKELY(value_arg != 0)) {
740 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800741 return false;
742 }
743 ptr_++;
744 break;
745 case DexFile::kDexAnnotationShort:
746 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700747 if (UNLIKELY(value_arg > 1)) {
748 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800749 return false;
750 }
751 ptr_ += value_arg + 1;
752 break;
753 case DexFile::kDexAnnotationInt:
754 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700755 if (UNLIKELY(value_arg > 3)) {
756 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800757 return false;
758 }
759 ptr_ += value_arg + 1;
760 break;
761 case DexFile::kDexAnnotationLong:
762 case DexFile::kDexAnnotationDouble:
763 ptr_ += value_arg + 1;
764 break;
765 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700766 if (UNLIKELY(value_arg > 3)) {
767 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800768 return false;
769 }
770 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
771 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
772 return false;
773 }
774 break;
775 }
776 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700777 if (UNLIKELY(value_arg > 3)) {
778 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800779 return false;
780 }
781 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
782 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
783 return false;
784 }
785 break;
786 }
787 case DexFile::kDexAnnotationField:
788 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700789 if (UNLIKELY(value_arg > 3)) {
790 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800791 return false;
792 }
793 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
794 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
795 return false;
796 }
797 break;
798 }
799 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700800 if (UNLIKELY(value_arg > 3)) {
801 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800802 return false;
803 }
804 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
805 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
806 return false;
807 }
808 break;
809 }
810 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700811 if (UNLIKELY(value_arg != 0)) {
812 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800813 return false;
814 }
815 if (!CheckEncodedArray()) {
816 return false;
817 }
818 break;
819 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700820 if (UNLIKELY(value_arg != 0)) {
821 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800822 return false;
823 }
824 if (!CheckEncodedAnnotation()) {
825 return false;
826 }
827 break;
828 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700829 if (UNLIKELY(value_arg != 0)) {
830 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800831 return false;
832 }
833 break;
834 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700835 if (UNLIKELY(value_arg > 1)) {
836 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800837 return false;
838 }
839 break;
840 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700841 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800842 return false;
843 }
844
845 return true;
846}
847
848bool DexFileVerifier::CheckEncodedArray() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700849 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800850
851 while (size--) {
852 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700853 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800854 return false;
855 }
856 }
857 return true;
858}
859
860bool DexFileVerifier::CheckEncodedAnnotation() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700861 DECODE_UNSIGNED_CHECKED_FROM(ptr_, anno_idx);
862 if (!CheckIndex(anno_idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -0800863 return false;
864 }
865
Andreas Gampebed6daf2016-09-02 18:12:00 -0700866 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800867 uint32_t last_idx = 0;
868
869 for (uint32_t i = 0; i < size; i++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700870 DECODE_UNSIGNED_CHECKED_FROM(ptr_, idx);
jeffhao10037c82012-01-23 15:06:23 -0800871 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
872 return false;
873 }
874
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700875 if (UNLIKELY(last_idx >= idx && i != 0)) {
876 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
877 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800878 return false;
879 }
880
881 if (!CheckEncodedValue()) {
882 return false;
883 }
884
885 last_idx = idx;
886 }
887 return true;
888}
889
Andreas Gampee6215c02015-08-31 18:54:38 -0700890bool DexFileVerifier::FindClassFlags(uint32_t index,
891 bool is_field,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800892 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700893 uint32_t* class_access_flags) {
894 DCHECK(class_type_index != nullptr);
895 DCHECK(class_access_flags != nullptr);
896
897 // First check if the index is valid.
898 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
899 return false;
900 }
901
902 // Next get the type index.
903 if (is_field) {
904 *class_type_index =
905 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
906 class_idx_;
907 } else {
908 *class_type_index =
909 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
910 class_idx_;
911 }
912
913 // Check if that is valid.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800914 if (class_type_index->index_ >= header_->type_ids_size_) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700915 return false;
916 }
917
918 // Now search for the class def. This is basically a specialized version of the DexFile code, as
919 // we should not trust that this is a valid DexFile just yet.
920 const DexFile::ClassDef* class_def_begin =
921 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
922 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
923 const DexFile::ClassDef* class_def = class_def_begin + i;
924 if (class_def->class_idx_ == *class_type_index) {
925 *class_access_flags = class_def->access_flags_;
926 return true;
927 }
928 }
929
930 // Didn't find the class-def, not defined here...
931 return false;
932}
933
934bool DexFileVerifier::CheckOrderAndGetClassFlags(bool is_field,
935 const char* type_descr,
936 uint32_t curr_index,
937 uint32_t prev_index,
938 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800939 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700940 uint32_t* class_access_flags) {
941 if (curr_index < prev_index) {
942 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
943 type_descr,
944 prev_index,
945 curr_index);
946 return false;
947 }
948
949 if (!*have_class) {
950 *have_class = FindClassFlags(curr_index, is_field, class_type_index, class_access_flags);
951 if (!*have_class) {
952 // Should have really found one.
953 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
954 type_descr,
955 curr_index);
956 return false;
957 }
958 }
959 return true;
960}
961
962template <bool kStatic>
963bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
964 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800965 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700966 uint32_t* class_access_flags) {
967 DCHECK(it != nullptr);
968 // These calls use the raw access flags to check whether the whole dex field is valid.
969 uint32_t prev_index = 0;
970 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
971 uint32_t curr_index = it->GetMemberIndex();
972 if (!CheckOrderAndGetClassFlags(true,
973 kStatic ? "static field" : "instance field",
974 curr_index,
975 prev_index,
976 have_class,
977 class_type_index,
978 class_access_flags)) {
979 return false;
980 }
981 prev_index = curr_index;
982
983 if (!CheckClassDataItemField(curr_index,
984 it->GetRawMemberAccessFlags(),
985 *class_access_flags,
986 *class_type_index,
987 kStatic)) {
988 return false;
989 }
990 }
991
992 return true;
993}
994
995template <bool kDirect>
996bool DexFileVerifier::CheckIntraClassDataItemMethods(
997 ClassDataItemIterator* it,
998 std::unordered_set<uint32_t>* direct_method_indexes,
999 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -08001000 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -07001001 uint32_t* class_access_flags) {
1002 uint32_t prev_index = 0;
1003 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
1004 uint32_t curr_index = it->GetMemberIndex();
1005 if (!CheckOrderAndGetClassFlags(false,
1006 kDirect ? "direct method" : "virtual method",
1007 curr_index,
1008 prev_index,
1009 have_class,
1010 class_type_index,
1011 class_access_flags)) {
1012 return false;
1013 }
1014 prev_index = curr_index;
1015
1016 if (!CheckClassDataItemMethod(curr_index,
1017 it->GetRawMemberAccessFlags(),
1018 *class_access_flags,
1019 *class_type_index,
1020 it->GetMethodCodeItemOffset(),
1021 direct_method_indexes,
1022 kDirect)) {
1023 return false;
1024 }
1025 }
1026
1027 return true;
1028}
1029
jeffhao10037c82012-01-23 15:06:23 -08001030bool DexFileVerifier::CheckIntraClassDataItem() {
1031 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -07001032 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -08001033
Andreas Gampee6215c02015-08-31 18:54:38 -07001034 // This code is complicated by the fact that we don't directly know which class this belongs to.
1035 // So we need to explicitly search with the first item we find (either field or method), and then,
1036 // as the lookup is expensive, cache the result.
1037 bool have_class = false;
Andreas Gampea5b09a62016-11-17 15:21:22 -08001038 dex::TypeIndex class_type_index;
Andreas Gampee6215c02015-08-31 18:54:38 -07001039 uint32_t class_access_flags;
1040
1041 // Check fields.
1042 if (!CheckIntraClassDataItemFields<true>(&it,
1043 &have_class,
1044 &class_type_index,
1045 &class_access_flags)) {
1046 return false;
jeffhao10037c82012-01-23 15:06:23 -08001047 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001048 if (!CheckIntraClassDataItemFields<false>(&it,
1049 &have_class,
1050 &class_type_index,
1051 &class_access_flags)) {
1052 return false;
jeffhao10037c82012-01-23 15:06:23 -08001053 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001054
1055 // Check methods.
1056 if (!CheckIntraClassDataItemMethods<true>(&it,
1057 &direct_method_indexes,
1058 &have_class,
1059 &class_type_index,
1060 &class_access_flags)) {
1061 return false;
jeffhao10037c82012-01-23 15:06:23 -08001062 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001063 if (!CheckIntraClassDataItemMethods<false>(&it,
1064 &direct_method_indexes,
1065 &have_class,
1066 &class_type_index,
1067 &class_access_flags)) {
1068 return false;
jeffhao10037c82012-01-23 15:06:23 -08001069 }
1070
1071 ptr_ = it.EndDataPointer();
1072 return true;
1073}
1074
1075bool DexFileVerifier::CheckIntraCodeItem() {
1076 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001077 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -08001078 return false;
1079 }
1080
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001081 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
1082 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
1083 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -08001084 return false;
1085 }
1086
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001087 if (UNLIKELY((code_item->outs_size_ > 5) &&
1088 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -08001089 /*
1090 * outs_size can be up to 5, even if registers_size is smaller, since the
1091 * short forms of method invocation allow repetitions of a register multiple
1092 * times within a single parameter list. However, longer parameter lists
1093 * need to be represented in-order in the register file.
1094 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001095 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
1096 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -08001097 return false;
1098 }
1099
1100 const uint16_t* insns = code_item->insns_;
1101 uint32_t insns_size = code_item->insns_size_in_code_units_;
1102 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
1103 return false;
1104 }
1105
1106 // Grab the end of the insns if there are no try_items.
1107 uint32_t try_items_size = code_item->tries_size_;
1108 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001109 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001110 return true;
1111 }
1112
1113 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001114 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001115 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001116 return false;
1117 }
1118
1119 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -08001120 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
1121 return false;
1122 }
1123
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001124 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
Andreas Gampebed6daf2016-09-02 18:12:00 -07001125 DECODE_UNSIGNED_CHECKED_FROM(ptr_, handlers_size);
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001126
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001127 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
1128 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -08001129 return false;
1130 }
1131
Ian Rogers700a4022014-05-19 16:49:03 -07001132 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -07001133 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -08001134 return false;
1135 }
1136
1137 uint32_t last_addr = 0;
1138 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001139 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1140 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001141 return false;
1142 }
1143
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001144 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1145 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001146 return false;
1147 }
1148
1149 uint32_t i;
1150 for (i = 0; i < handlers_size; i++) {
1151 if (try_items->handler_off_ == handler_offsets[i]) {
1152 break;
1153 }
1154 }
1155
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001156 if (UNLIKELY(i == handlers_size)) {
1157 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -08001158 return false;
1159 }
1160
1161 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001162 if (UNLIKELY(last_addr > insns_size)) {
1163 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -08001164 return false;
1165 }
1166
1167 try_items++;
1168 }
1169
1170 return true;
1171}
1172
1173bool DexFileVerifier::CheckIntraStringDataItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001174 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
Ian Rogers13735952014-10-08 12:43:28 -07001175 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001176
1177 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001178 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001179 if (UNLIKELY(ptr_ >= file_end)) {
1180 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001181 return false;
1182 }
1183
1184 uint8_t byte = *(ptr_++);
1185
1186 // Switch on the high 4 bits.
1187 switch (byte >> 4) {
1188 case 0x00:
1189 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001190 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001191 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001192 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001193 return false;
1194 }
1195 break;
1196 case 0x01:
1197 case 0x02:
1198 case 0x03:
1199 case 0x04:
1200 case 0x05:
1201 case 0x06:
1202 case 0x07:
1203 // No extra checks necessary for bit pattern 0xxx.
1204 break;
1205 case 0x08:
1206 case 0x09:
1207 case 0x0a:
1208 case 0x0b:
1209 case 0x0f:
1210 // Illegal bit patterns 10xx or 1111.
1211 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001212 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001213 return false;
1214 case 0x0c:
1215 case 0x0d: {
1216 // Bit pattern 110x has an additional byte.
1217 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001218 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1219 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001220 return false;
1221 }
1222 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001223 if (UNLIKELY((value != 0) && (value < 0x80))) {
1224 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001225 return false;
1226 }
1227 break;
1228 }
1229 case 0x0e: {
1230 // Bit pattern 1110 has 2 additional bytes.
1231 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001232 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1233 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001234 return false;
1235 }
1236 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001237 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1238 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001239 return false;
1240 }
1241 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001242 if (UNLIKELY(value < 0x800)) {
1243 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001244 return false;
1245 }
1246 break;
1247 }
1248 }
1249 }
1250
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001251 if (UNLIKELY(*(ptr_++) != '\0')) {
1252 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001253 return false;
1254 }
1255
1256 return true;
1257}
1258
1259bool DexFileVerifier::CheckIntraDebugInfoItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001260 DECODE_UNSIGNED_CHECKED_FROM(ptr_, dummy);
1261 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameters_size);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001262 if (UNLIKELY(parameters_size > 65536)) {
1263 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001264 return false;
1265 }
1266
1267 for (uint32_t j = 0; j < parameters_size; j++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001268 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameter_name);
jeffhao10037c82012-01-23 15:06:23 -08001269 if (parameter_name != 0) {
1270 parameter_name--;
1271 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1272 return false;
1273 }
1274 }
1275 }
1276
1277 while (true) {
1278 uint8_t opcode = *(ptr_++);
1279 switch (opcode) {
1280 case DexFile::DBG_END_SEQUENCE: {
1281 return true;
1282 }
1283 case DexFile::DBG_ADVANCE_PC: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001284 DECODE_UNSIGNED_CHECKED_FROM(ptr_, advance_pc_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001285 break;
1286 }
1287 case DexFile::DBG_ADVANCE_LINE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001288 DECODE_SIGNED_CHECKED_FROM(ptr_, advance_line_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001289 break;
1290 }
1291 case DexFile::DBG_START_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001292 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001293 if (UNLIKELY(reg_num >= 65536)) {
1294 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001295 return false;
1296 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001297 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001298 if (name_idx != 0) {
1299 name_idx--;
1300 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1301 return false;
1302 }
1303 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001304 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001305 if (type_idx != 0) {
1306 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001307 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001308 return false;
1309 }
1310 }
1311 break;
1312 }
1313 case DexFile::DBG_END_LOCAL:
1314 case DexFile::DBG_RESTART_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001315 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001316 if (UNLIKELY(reg_num >= 65536)) {
1317 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001318 return false;
1319 }
1320 break;
1321 }
1322 case DexFile::DBG_START_LOCAL_EXTENDED: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001323 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001324 if (UNLIKELY(reg_num >= 65536)) {
1325 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001326 return false;
1327 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001328 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001329 if (name_idx != 0) {
1330 name_idx--;
1331 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1332 return false;
1333 }
1334 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001335 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001336 if (type_idx != 0) {
1337 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001338 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001339 return false;
1340 }
1341 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001342 DECODE_UNSIGNED_CHECKED_FROM(ptr_, sig_idx);
jeffhao10037c82012-01-23 15:06:23 -08001343 if (sig_idx != 0) {
1344 sig_idx--;
1345 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1346 return false;
1347 }
1348 }
1349 break;
1350 }
1351 case DexFile::DBG_SET_FILE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001352 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001353 if (name_idx != 0) {
1354 name_idx--;
1355 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1356 return false;
1357 }
1358 }
1359 break;
1360 }
1361 }
1362 }
1363}
1364
1365bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001366 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001367 return false;
1368 }
1369
1370 // Check visibility
1371 switch (*(ptr_++)) {
1372 case DexFile::kDexVisibilityBuild:
1373 case DexFile::kDexVisibilityRuntime:
1374 case DexFile::kDexVisibilitySystem:
1375 break;
1376 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001377 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001378 return false;
1379 }
1380
1381 if (!CheckEncodedAnnotation()) {
1382 return false;
1383 }
1384
1385 return true;
1386}
1387
1388bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1389 const DexFile::AnnotationsDirectoryItem* item =
1390 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001391 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001392 return false;
1393 }
1394
1395 // Field annotations follow immediately after the annotations directory.
1396 const DexFile::FieldAnnotationsItem* field_item =
1397 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1398 uint32_t field_count = item->fields_size_;
1399 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1400 return false;
1401 }
1402
1403 uint32_t last_idx = 0;
1404 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001405 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1406 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001407 return false;
1408 }
1409 last_idx = field_item->field_idx_;
1410 field_item++;
1411 }
1412
1413 // Method annotations follow immediately after field annotations.
1414 const DexFile::MethodAnnotationsItem* method_item =
1415 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1416 uint32_t method_count = item->methods_size_;
1417 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1418 return false;
1419 }
1420
1421 last_idx = 0;
1422 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001423 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1424 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1425 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001426 return false;
1427 }
1428 last_idx = method_item->method_idx_;
1429 method_item++;
1430 }
1431
1432 // Parameter annotations follow immediately after method annotations.
1433 const DexFile::ParameterAnnotationsItem* parameter_item =
1434 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1435 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001436 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001437 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001438 return false;
1439 }
1440
1441 last_idx = 0;
1442 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001443 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1444 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1445 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001446 return false;
1447 }
1448 last_idx = parameter_item->method_idx_;
1449 parameter_item++;
1450 }
1451
1452 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001453 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001454 return true;
1455}
1456
Andreas Gampeb061cc12014-09-02 10:22:20 -07001457bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
1458 uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001459 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001460 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001461 switch (type) {
1462 case DexFile::kDexTypeClassDataItem:
1463 case DexFile::kDexTypeStringDataItem:
1464 case DexFile::kDexTypeDebugInfoItem:
1465 case DexFile::kDexTypeAnnotationItem:
1466 case DexFile::kDexTypeEncodedArrayItem:
1467 alignment_mask = sizeof(uint8_t) - 1;
1468 break;
1469 default:
1470 alignment_mask = sizeof(uint32_t) - 1;
1471 break;
1472 }
1473
1474 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001475 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001476 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001477
1478 // Check the padding between items.
1479 if (!CheckPadding(offset, aligned_offset)) {
1480 return false;
1481 }
1482
1483 // Check depending on the section type.
1484 switch (type) {
1485 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001486 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001487 return false;
1488 }
1489 ptr_ += sizeof(DexFile::StringId);
1490 break;
1491 }
1492 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001493 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001494 return false;
1495 }
1496 ptr_ += sizeof(DexFile::TypeId);
1497 break;
1498 }
1499 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001500 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001501 return false;
1502 }
1503 ptr_ += sizeof(DexFile::ProtoId);
1504 break;
1505 }
1506 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001507 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001508 return false;
1509 }
1510 ptr_ += sizeof(DexFile::FieldId);
1511 break;
1512 }
1513 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001514 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001515 return false;
1516 }
1517 ptr_ += sizeof(DexFile::MethodId);
1518 break;
1519 }
1520 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001521 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001522 return false;
1523 }
1524 ptr_ += sizeof(DexFile::ClassDef);
1525 break;
1526 }
1527 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001528 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001529 return false;
1530 }
jeffhao10037c82012-01-23 15:06:23 -08001531 break;
1532 }
1533 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001534 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001535 return false;
1536 }
jeffhao10037c82012-01-23 15:06:23 -08001537 break;
1538 }
1539 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001540 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001541 return false;
1542 }
jeffhao10037c82012-01-23 15:06:23 -08001543 break;
1544 }
1545 case DexFile::kDexTypeClassDataItem: {
1546 if (!CheckIntraClassDataItem()) {
1547 return false;
1548 }
1549 break;
1550 }
1551 case DexFile::kDexTypeCodeItem: {
1552 if (!CheckIntraCodeItem()) {
1553 return false;
1554 }
1555 break;
1556 }
1557 case DexFile::kDexTypeStringDataItem: {
1558 if (!CheckIntraStringDataItem()) {
1559 return false;
1560 }
1561 break;
1562 }
1563 case DexFile::kDexTypeDebugInfoItem: {
1564 if (!CheckIntraDebugInfoItem()) {
1565 return false;
1566 }
1567 break;
1568 }
1569 case DexFile::kDexTypeAnnotationItem: {
1570 if (!CheckIntraAnnotationItem()) {
1571 return false;
1572 }
1573 break;
1574 }
1575 case DexFile::kDexTypeEncodedArrayItem: {
1576 if (!CheckEncodedArray()) {
1577 return false;
1578 }
1579 break;
1580 }
1581 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1582 if (!CheckIntraAnnotationsDirectoryItem()) {
1583 return false;
1584 }
1585 break;
1586 }
1587 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001588 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001589 return false;
1590 }
1591
1592 if (IsDataSectionType(type)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001593 if (aligned_offset == 0u) {
1594 ErrorStringPrintf("Item %d offset is 0", i);
1595 return false;
1596 }
1597 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1598 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001599 }
1600
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001601 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001602 if (UNLIKELY(aligned_offset > size_)) {
1603 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001604 return false;
1605 }
1606
1607 offset = aligned_offset;
1608 }
1609
1610 return true;
1611}
1612
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001613bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001614 uint32_t expected_offset;
1615 uint32_t expected_size;
1616
1617 // Get the expected offset and size from the header.
1618 switch (type) {
1619 case DexFile::kDexTypeStringIdItem:
1620 expected_offset = header_->string_ids_off_;
1621 expected_size = header_->string_ids_size_;
1622 break;
1623 case DexFile::kDexTypeTypeIdItem:
1624 expected_offset = header_->type_ids_off_;
1625 expected_size = header_->type_ids_size_;
1626 break;
1627 case DexFile::kDexTypeProtoIdItem:
1628 expected_offset = header_->proto_ids_off_;
1629 expected_size = header_->proto_ids_size_;
1630 break;
1631 case DexFile::kDexTypeFieldIdItem:
1632 expected_offset = header_->field_ids_off_;
1633 expected_size = header_->field_ids_size_;
1634 break;
1635 case DexFile::kDexTypeMethodIdItem:
1636 expected_offset = header_->method_ids_off_;
1637 expected_size = header_->method_ids_size_;
1638 break;
1639 case DexFile::kDexTypeClassDefItem:
1640 expected_offset = header_->class_defs_off_;
1641 expected_size = header_->class_defs_size_;
1642 break;
1643 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001644 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001645 return false;
1646 }
1647
1648 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001649 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001650 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001651 return false;
1652 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001653 if (UNLIKELY(count != expected_size)) {
1654 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001655 return false;
1656 }
1657
1658 return CheckIntraSectionIterate(offset, count, type);
1659}
1660
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001661bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count, uint16_t type) {
1662 size_t data_start = header_->data_off_;
1663 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001664
1665 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001666 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001667 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001668 return false;
1669 }
1670
1671 if (!CheckIntraSectionIterate(offset, count, type)) {
1672 return false;
1673 }
1674
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001675 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001676 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001677 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001678 return false;
1679 }
1680
1681 return true;
1682}
1683
1684bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001685 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001686 const DexFile::MapItem* item = map->list_;
1687
1688 uint32_t count = map->size_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001689 size_t offset = 0;
Ian Rogers30fab402012-01-23 15:43:46 -08001690 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001691
1692 // Check the items listed in the map.
1693 while (count--) {
1694 uint32_t section_offset = item->offset_;
1695 uint32_t section_count = item->size_;
1696 uint16_t type = item->type_;
1697
1698 // Check for padding and overlap between items.
1699 if (!CheckPadding(offset, section_offset)) {
1700 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001701 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001702 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001703 return false;
1704 }
1705
1706 // Check each item based on its type.
1707 switch (type) {
1708 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001709 if (UNLIKELY(section_count != 1)) {
1710 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001711 return false;
1712 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001713 if (UNLIKELY(section_offset != 0)) {
1714 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001715 return false;
1716 }
Ian Rogers30fab402012-01-23 15:43:46 -08001717 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001718 offset = header_->header_size_;
1719 break;
1720 case DexFile::kDexTypeStringIdItem:
1721 case DexFile::kDexTypeTypeIdItem:
1722 case DexFile::kDexTypeProtoIdItem:
1723 case DexFile::kDexTypeFieldIdItem:
1724 case DexFile::kDexTypeMethodIdItem:
1725 case DexFile::kDexTypeClassDefItem:
1726 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1727 return false;
1728 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001729 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001730 break;
1731 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001732 if (UNLIKELY(section_count != 1)) {
1733 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001734 return false;
1735 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001736 if (UNLIKELY(section_offset != header_->map_off_)) {
1737 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1738 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001739 return false;
1740 }
1741 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1742 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1743 break;
1744 case DexFile::kDexTypeTypeList:
1745 case DexFile::kDexTypeAnnotationSetRefList:
1746 case DexFile::kDexTypeAnnotationSetItem:
1747 case DexFile::kDexTypeClassDataItem:
1748 case DexFile::kDexTypeCodeItem:
1749 case DexFile::kDexTypeStringDataItem:
1750 case DexFile::kDexTypeDebugInfoItem:
1751 case DexFile::kDexTypeAnnotationItem:
1752 case DexFile::kDexTypeEncodedArrayItem:
1753 case DexFile::kDexTypeAnnotationsDirectoryItem:
1754 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1755 return false;
1756 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001757 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001758 break;
1759 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001760 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001761 return false;
1762 }
1763
1764 item++;
1765 }
1766
1767 return true;
1768}
1769
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001770bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001771 DCHECK_NE(offset, 0u);
1772 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001773 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001774 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001775 return false;
1776 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001777 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001778 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001779 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001780 return false;
1781 }
1782 return true;
1783}
1784
Andreas Gampea5b09a62016-11-17 15:21:22 -08001785dex::TypeIndex DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001786 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001787 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001788
1789 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001790 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001791 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001792 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001793 }
1794
1795 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001796 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001797 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001798 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001799 }
1800
Andreas Gampea5b09a62016-11-17 15:21:22 -08001801 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001802}
1803
Andreas Gampea5b09a62016-11-17 15:21:22 -08001804dex::TypeIndex DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr,
1805 bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001806 const DexFile::AnnotationsDirectoryItem* item =
1807 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001808 *success = true;
1809
jeffhao10037c82012-01-23 15:06:23 -08001810 if (item->fields_size_ != 0) {
1811 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001812 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001813 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001814 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001815 }
1816
1817 if (item->methods_size_ != 0) {
1818 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001819 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001820 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001821 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001822 }
1823
1824 if (item->parameters_size_ != 0) {
1825 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001826 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001827 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001828 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001829 }
1830
Andreas Gampea5b09a62016-11-17 15:21:22 -08001831 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001832}
1833
1834bool DexFileVerifier::CheckInterStringIdItem() {
1835 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1836
1837 // Check the map to make sure it has the right offset->type.
1838 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1839 return false;
1840 }
1841
1842 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001843 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001844 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1845 const char* prev_str = dex_file_->GetStringData(*prev_item);
1846 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001847 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1848 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001849 return false;
1850 }
1851 }
1852
1853 ptr_ += sizeof(DexFile::StringId);
1854 return true;
1855}
1856
1857bool DexFileVerifier::CheckInterTypeIdItem() {
1858 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001859
1860 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001861
1862 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001863 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1864 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001865 return false;
1866 }
1867
1868 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001869 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001870 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001871 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1872 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001873 prev_item->descriptor_idx_.index_,
1874 item->descriptor_idx_.index_);
jeffhao10037c82012-01-23 15:06:23 -08001875 return false;
1876 }
1877 }
1878
1879 ptr_ += sizeof(DexFile::TypeId);
1880 return true;
1881}
1882
1883bool DexFileVerifier::CheckInterProtoIdItem() {
1884 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001885
1886 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1887
jeffhao10037c82012-01-23 15:06:23 -08001888 if (item->parameters_off_ != 0 &&
1889 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1890 return false;
1891 }
1892
David Sehr28e74ed2016-11-21 12:52:12 -08001893 // Check that return type is representable as a uint16_t;
1894 if (UNLIKELY(!IsValidOrNoTypeId(item->return_type_idx_.index_, item->pad_))) {
1895 ErrorStringPrintf("proto with return type idx outside uint16_t range '%x:%x'",
1896 item->pad_, item->return_type_idx_.index_);
1897 return false;
1898 }
jeffhao10037c82012-01-23 15:06:23 -08001899 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001900 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1901 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001902 return false;
1903 }
1904 shorty++;
1905
1906 DexFileParameterIterator it(*dex_file_, *item);
1907 while (it.HasNext() && *shorty != '\0') {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001908 if (!CheckIndex(it.GetTypeIdx().index_,
1909 dex_file_->NumTypeIds(),
Andreas Gampebb836e12014-06-13 15:31:40 -07001910 "inter_proto_id_item shorty type_idx")) {
1911 return false;
1912 }
jeffhao10037c82012-01-23 15:06:23 -08001913 const char* descriptor = it.GetDescriptor();
1914 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1915 return false;
1916 }
1917 it.Next();
1918 shorty++;
1919 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001920 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1921 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001922 return false;
1923 }
1924
1925 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001926 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001927 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001928 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1929 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001930 return false;
1931 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1932 DexFileParameterIterator curr_it(*dex_file_, *item);
1933 DexFileParameterIterator prev_it(*dex_file_, *prev);
1934
1935 while (curr_it.HasNext() && prev_it.HasNext()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001936 dex::TypeIndex prev_idx = prev_it.GetTypeIdx();
1937 dex::TypeIndex curr_idx = curr_it.GetTypeIdx();
1938 DCHECK_NE(prev_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
1939 DCHECK_NE(curr_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
jeffhao10037c82012-01-23 15:06:23 -08001940
1941 if (prev_idx < curr_idx) {
1942 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001943 } else if (UNLIKELY(prev_idx > curr_idx)) {
1944 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001945 return false;
1946 }
1947
1948 prev_it.Next();
1949 curr_it.Next();
1950 }
Vladimir Marko0ca8add2016-05-03 17:17:50 +01001951 if (!curr_it.HasNext()) {
1952 // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
1953 // a ProtoId with a longer one. Both cases are forbidden by the specification.
1954 ErrorStringPrintf("Out-of-order proto_id arguments");
1955 return false;
1956 }
jeffhao10037c82012-01-23 15:06:23 -08001957 }
1958 }
1959
1960 ptr_ += sizeof(DexFile::ProtoId);
1961 return true;
1962}
1963
1964bool DexFileVerifier::CheckInterFieldIdItem() {
1965 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1966
1967 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001968 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1969 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1970 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001971 return false;
1972 }
1973
1974 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001975 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1976 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1977 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001978 return false;
1979 }
1980
1981 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001982 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001983 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1984 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001985 return false;
1986 }
1987
1988 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001989 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001990 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001991 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1992 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001993 return false;
1994 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001995 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1996 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001997 return false;
1998 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001999 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
2000 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002001 return false;
2002 }
2003 }
2004 }
2005 }
2006
2007 ptr_ += sizeof(DexFile::FieldId);
2008 return true;
2009}
2010
2011bool DexFileVerifier::CheckInterMethodIdItem() {
2012 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
2013
2014 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07002015 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
2016 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
2017 class_descriptor[0] != '['))) {
2018 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002019 return false;
2020 }
2021
2022 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07002023 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002024 if (UNLIKELY(!IsValidMemberName(descriptor))) {
2025 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002026 return false;
2027 }
2028
Andreas Gampedf10b322014-06-11 21:46:05 -07002029 // Check that the proto id is valid.
2030 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
2031 "inter_method_id_item proto_idx"))) {
2032 return false;
2033 }
2034
jeffhao10037c82012-01-23 15:06:23 -08002035 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002036 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002037 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002038 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
2039 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002040 return false;
2041 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002042 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
2043 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002044 return false;
2045 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002046 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
2047 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002048 return false;
2049 }
2050 }
2051 }
2052 }
2053
2054 ptr_ += sizeof(DexFile::MethodId);
2055 return true;
2056}
2057
2058bool DexFileVerifier::CheckInterClassDefItem() {
2059 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08002060
David Sehr28e74ed2016-11-21 12:52:12 -08002061 // Check that class_idx_ is representable as a uint16_t;
2062 if (UNLIKELY(!IsValidTypeId(item->class_idx_.index_, item->pad1_))) {
2063 ErrorStringPrintf("class with type idx outside uint16_t range '%x:%x'", item->pad1_,
2064 item->class_idx_.index_);
2065 return false;
2066 }
2067 // Check that superclass_idx_ is representable as a uint16_t;
2068 if (UNLIKELY(!IsValidOrNoTypeId(item->superclass_idx_.index_, item->pad2_))) {
2069 ErrorStringPrintf("class with superclass type idx outside uint16_t range '%x:%x'", item->pad2_,
2070 item->superclass_idx_.index_);
2071 return false;
2072 }
Andreas Gampe0ba238d2014-07-29 01:22:07 -07002073 // Check for duplicate class def.
2074 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002075 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_.index_);
Andreas Gampe0ba238d2014-07-29 01:22:07 -07002076 return false;
2077 }
2078 defined_classes_.insert(item->class_idx_);
2079
Andreas Gampee09269c2014-06-06 18:45:35 -07002080 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
2081 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
2082 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002083 return false;
2084 }
2085
Andreas Gampeacc2bb62014-07-17 19:26:50 -07002086 // Only allow non-runtime modifiers.
2087 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
2088 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
2089 return false;
2090 }
2091
jeffhao10037c82012-01-23 15:06:23 -08002092 if (item->interfaces_off_ != 0 &&
2093 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
2094 return false;
2095 }
2096 if (item->annotations_off_ != 0 &&
2097 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
2098 return false;
2099 }
2100 if (item->class_data_off_ != 0 &&
2101 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
2102 return false;
2103 }
2104 if (item->static_values_off_ != 0 &&
2105 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
2106 return false;
2107 }
2108
Andreas Gampea5b09a62016-11-17 15:21:22 -08002109 if (item->superclass_idx_.IsValid()) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002110 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2111 // Check that a class does not inherit from itself directly (by having
2112 // the same type idx as its super class).
2113 if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002114 ErrorStringPrintf("Class with same type idx as its superclass: '%d'",
2115 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002116 return false;
2117 }
2118
2119 // Check that a class is defined after its super class (if the
2120 // latter is defined in the same Dex file).
2121 const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
2122 if (superclass_def != nullptr) {
2123 // The superclass is defined in this Dex file.
2124 if (superclass_def > item) {
2125 // ClassDef item for super class appearing after the class' ClassDef item.
2126 ErrorStringPrintf("Invalid class definition ordering:"
2127 " class with type idx: '%d' defined before"
2128 " superclass with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002129 item->class_idx_.index_,
2130 item->superclass_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002131 return false;
2132 }
2133 }
2134 }
2135
Andreas Gampee09269c2014-06-06 18:45:35 -07002136 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
2137 "inter_class_def_item superclass_idx")
2138 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
2139 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002140 return false;
2141 }
2142 }
2143
Roland Levillain621b5ea2016-05-18 11:41:33 +01002144 // Check interfaces.
jeffhao10037c82012-01-23 15:06:23 -08002145 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002146 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002147 uint32_t size = interfaces->Size();
jeffhao10037c82012-01-23 15:06:23 -08002148 for (uint32_t i = 0; i < size; i++) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002149 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2150 // Check that a class does not implement itself directly (by having the
2151 // same type idx as one of its immediate implemented interfaces).
2152 if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2153 ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002154 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002155 return false;
2156 }
2157
2158 // Check that a class is defined after the interfaces it implements
2159 // (if they are defined in the same Dex file).
2160 const DexFile::ClassDef* interface_def =
2161 dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2162 if (interface_def != nullptr) {
2163 // The interface is defined in this Dex file.
2164 if (interface_def > item) {
2165 // ClassDef item for interface appearing after the class' ClassDef item.
2166 ErrorStringPrintf("Invalid class definition ordering:"
2167 " class with type idx: '%d' defined before"
2168 " implemented interface with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002169 item->class_idx_.index_,
2170 interfaces->GetTypeItem(i).type_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002171 return false;
2172 }
2173 }
2174 }
2175
2176 // Ensure that the interface refers to a class (not an array nor a primitive type).
Andreas Gampee09269c2014-06-06 18:45:35 -07002177 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2178 "inter_class_def_item interface type_idx")
2179 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2180 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002181 return false;
2182 }
2183 }
2184
2185 /*
2186 * Ensure that there are no duplicates. This is an O(N^2) test, but in
2187 * practice the number of interfaces implemented by any given class is low.
2188 */
2189 for (uint32_t i = 1; i < size; i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002190 dex::TypeIndex idx1 = interfaces->GetTypeItem(i).type_idx_;
jeffhao10037c82012-01-23 15:06:23 -08002191 for (uint32_t j =0; j < i; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002192 dex::TypeIndex idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002193 if (UNLIKELY(idx1 == idx2)) {
2194 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08002195 return false;
2196 }
2197 }
2198 }
2199 }
2200
2201 // Check that references in class_data_item are to the right class.
2202 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07002203 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002204 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002205 dex::TypeIndex data_definer = FindFirstClassDataDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002206 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002207 return false;
2208 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08002209 if (UNLIKELY((data_definer != item->class_idx_) &&
2210 (data_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002211 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08002212 return false;
2213 }
2214 }
2215
2216 // Check that references in annotations_directory_item are to right class.
2217 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002218 // annotations_off_ is supposed to be aligned by 4.
2219 if (!IsAlignedParam(item->annotations_off_, 4)) {
2220 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2221 return false;
2222 }
Ian Rogers13735952014-10-08 12:43:28 -07002223 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002224 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002225 dex::TypeIndex annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002226 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002227 return false;
2228 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002229 if (UNLIKELY((annotations_definer != item->class_idx_) &&
Andreas Gampea5b09a62016-11-17 15:21:22 -08002230 (annotations_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002231 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002232 return false;
2233 }
2234 }
2235
2236 ptr_ += sizeof(DexFile::ClassDef);
2237 return true;
2238}
2239
2240bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2241 const DexFile::AnnotationSetRefList* list =
2242 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2243 const DexFile::AnnotationSetRefItem* item = list->list_;
2244 uint32_t count = list->size_;
2245
2246 while (count--) {
2247 if (item->annotations_off_ != 0 &&
2248 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2249 return false;
2250 }
2251 item++;
2252 }
2253
Ian Rogers13735952014-10-08 12:43:28 -07002254 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002255 return true;
2256}
2257
2258bool DexFileVerifier::CheckInterAnnotationSetItem() {
2259 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2260 const uint32_t* offsets = set->entries_;
2261 uint32_t count = set->size_;
2262 uint32_t last_idx = 0;
2263
2264 for (uint32_t i = 0; i < count; i++) {
2265 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2266 return false;
2267 }
2268
2269 // Get the annotation from the offset and the type index for the annotation.
2270 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002271 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002272 const uint8_t* data = annotation->annotation_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002273 DECODE_UNSIGNED_CHECKED_FROM(data, idx);
jeffhao10037c82012-01-23 15:06:23 -08002274
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002275 if (UNLIKELY(last_idx >= idx && i != 0)) {
2276 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002277 return false;
2278 }
2279
2280 last_idx = idx;
2281 offsets++;
2282 }
2283
Ian Rogers13735952014-10-08 12:43:28 -07002284 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002285 return true;
2286}
2287
2288bool DexFileVerifier::CheckInterClassDataItem() {
2289 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002290 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002291 dex::TypeIndex defining_class = FindFirstClassDataDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002292 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002293 return false;
2294 }
jeffhao10037c82012-01-23 15:06:23 -08002295
2296 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002297 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002298 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002299 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002300 return false;
2301 }
2302 }
2303 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2304 uint32_t code_off = it.GetMethodCodeItemOffset();
2305 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2306 return false;
2307 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002308 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002309 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002310 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002311 return false;
2312 }
2313 }
2314
2315 ptr_ = it.EndDataPointer();
2316 return true;
2317}
2318
2319bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2320 const DexFile::AnnotationsDirectoryItem* item =
2321 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002322 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002323 dex::TypeIndex defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002324 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002325 return false;
2326 }
jeffhao10037c82012-01-23 15:06:23 -08002327
2328 if (item->class_annotations_off_ != 0 &&
2329 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2330 return false;
2331 }
2332
2333 // Field annotations follow immediately after the annotations directory.
2334 const DexFile::FieldAnnotationsItem* field_item =
2335 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2336 uint32_t field_count = item->fields_size_;
2337 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002338 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2339 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002340 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002341 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002342 return false;
2343 }
2344 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2345 return false;
2346 }
2347 field_item++;
2348 }
2349
2350 // Method annotations follow immediately after field annotations.
2351 const DexFile::MethodAnnotationsItem* method_item =
2352 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2353 uint32_t method_count = item->methods_size_;
2354 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002355 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002356 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002357 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002358 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002359 return false;
2360 }
2361 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2362 return false;
2363 }
2364 method_item++;
2365 }
2366
2367 // Parameter annotations follow immediately after method annotations.
2368 const DexFile::ParameterAnnotationsItem* parameter_item =
2369 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2370 uint32_t parameter_count = item->parameters_size_;
2371 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002372 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002373 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002374 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002375 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002376 return false;
2377 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002378 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2379 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002380 return false;
2381 }
2382 parameter_item++;
2383 }
2384
Ian Rogers13735952014-10-08 12:43:28 -07002385 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002386 return true;
2387}
2388
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002389bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002390 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002391 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002392 switch (type) {
2393 case DexFile::kDexTypeClassDataItem:
2394 alignment_mask = sizeof(uint8_t) - 1;
2395 break;
2396 default:
2397 alignment_mask = sizeof(uint32_t) - 1;
2398 break;
2399 }
2400
2401 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002402 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002403 for (uint32_t i = 0; i < count; i++) {
2404 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002405 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002406 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002407
2408 // Check depending on the section type.
2409 switch (type) {
2410 case DexFile::kDexTypeStringIdItem: {
2411 if (!CheckInterStringIdItem()) {
2412 return false;
2413 }
2414 break;
2415 }
2416 case DexFile::kDexTypeTypeIdItem: {
2417 if (!CheckInterTypeIdItem()) {
2418 return false;
2419 }
2420 break;
2421 }
2422 case DexFile::kDexTypeProtoIdItem: {
2423 if (!CheckInterProtoIdItem()) {
2424 return false;
2425 }
2426 break;
2427 }
2428 case DexFile::kDexTypeFieldIdItem: {
2429 if (!CheckInterFieldIdItem()) {
2430 return false;
2431 }
2432 break;
2433 }
2434 case DexFile::kDexTypeMethodIdItem: {
2435 if (!CheckInterMethodIdItem()) {
2436 return false;
2437 }
2438 break;
2439 }
2440 case DexFile::kDexTypeClassDefItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002441 // There shouldn't be more class definitions than type ids allow.
2442 // This check should be redundant, since there are checks that the
2443 // class_idx_ is within range and that there is only one definition
2444 // for a given type id.
2445 if (i > kTypeIdLimit) {
2446 ErrorStringPrintf("Too many class definition items");
2447 return false;
2448 }
jeffhao10037c82012-01-23 15:06:23 -08002449 if (!CheckInterClassDefItem()) {
2450 return false;
2451 }
2452 break;
2453 }
2454 case DexFile::kDexTypeAnnotationSetRefList: {
2455 if (!CheckInterAnnotationSetRefList()) {
2456 return false;
2457 }
2458 break;
2459 }
2460 case DexFile::kDexTypeAnnotationSetItem: {
2461 if (!CheckInterAnnotationSetItem()) {
2462 return false;
2463 }
2464 break;
2465 }
2466 case DexFile::kDexTypeClassDataItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002467 // There shouldn't be more class data than type ids allow.
2468 // This check should be redundant, since there are checks that the
2469 // class_idx_ is within range and that there is only one definition
2470 // for a given type id.
2471 if (i > kTypeIdLimit) {
2472 ErrorStringPrintf("Too many class data items");
2473 return false;
2474 }
jeffhao10037c82012-01-23 15:06:23 -08002475 if (!CheckInterClassDataItem()) {
2476 return false;
2477 }
2478 break;
2479 }
2480 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2481 if (!CheckInterAnnotationsDirectoryItem()) {
2482 return false;
2483 }
2484 break;
2485 }
2486 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002487 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002488 return false;
2489 }
2490
2491 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002492 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002493 }
2494
2495 return true;
2496}
2497
2498bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002499 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002500 const DexFile::MapItem* item = map->list_;
2501 uint32_t count = map->size_;
2502
2503 // Cross check the items listed in the map.
2504 while (count--) {
2505 uint32_t section_offset = item->offset_;
2506 uint32_t section_count = item->size_;
2507 uint16_t type = item->type_;
2508
2509 switch (type) {
2510 case DexFile::kDexTypeHeaderItem:
2511 case DexFile::kDexTypeMapList:
2512 case DexFile::kDexTypeTypeList:
2513 case DexFile::kDexTypeCodeItem:
2514 case DexFile::kDexTypeStringDataItem:
2515 case DexFile::kDexTypeDebugInfoItem:
2516 case DexFile::kDexTypeAnnotationItem:
2517 case DexFile::kDexTypeEncodedArrayItem:
2518 break;
2519 case DexFile::kDexTypeStringIdItem:
2520 case DexFile::kDexTypeTypeIdItem:
2521 case DexFile::kDexTypeProtoIdItem:
2522 case DexFile::kDexTypeFieldIdItem:
2523 case DexFile::kDexTypeMethodIdItem:
2524 case DexFile::kDexTypeClassDefItem:
2525 case DexFile::kDexTypeAnnotationSetRefList:
2526 case DexFile::kDexTypeAnnotationSetItem:
2527 case DexFile::kDexTypeClassDataItem:
2528 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2529 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2530 return false;
2531 }
2532 break;
2533 }
2534 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002535 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002536 return false;
2537 }
2538
2539 item++;
2540 }
2541
2542 return true;
2543}
2544
2545bool DexFileVerifier::Verify() {
2546 // Check the header.
2547 if (!CheckHeader()) {
2548 return false;
2549 }
2550
2551 // Check the map section.
2552 if (!CheckMap()) {
2553 return false;
2554 }
2555
2556 // Check structure within remaining sections.
2557 if (!CheckIntraSection()) {
2558 return false;
2559 }
2560
2561 // Check references from one section to another.
2562 if (!CheckInterSection()) {
2563 return false;
2564 }
2565
2566 return true;
2567}
2568
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002569void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2570 va_list ap;
2571 va_start(ap, fmt);
2572 DCHECK(failure_reason_.empty()) << failure_reason_;
2573 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2574 StringAppendV(&failure_reason_, fmt, ap);
2575 va_end(ap);
2576}
2577
Andreas Gampee6215c02015-08-31 18:54:38 -07002578// Fields and methods may have only one of public/protected/private.
2579static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2580 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2581 (((flags & kAccProtected) == 0) ? 0 : 1) +
2582 (((flags & kAccPrivate) == 0) ? 0 : 1);
2583 return count <= 1;
2584}
2585
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002586// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2587// functionality, as we're still verifying the dex file. begin and header correspond to the
2588// underscored variants in the DexFileVerifier.
2589
2590static std::string GetStringOrError(const uint8_t* const begin,
2591 const DexFile::Header* const header,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002592 dex::StringIndex string_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002593 // The `string_idx` is not guaranteed to be valid yet.
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002594 if (header->string_ids_size_ <= string_idx.index_) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002595 return "(error)";
2596 }
2597
2598 const DexFile::StringId* string_id =
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002599 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_)
2600 + string_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002601
2602 // Assume that the data is OK at this point. String data has been checked at this point.
2603
2604 const uint8_t* ptr = begin + string_id->string_data_off_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002605 uint32_t dummy;
2606 if (!DecodeUnsignedLeb128Checked(&ptr, begin + header->file_size_, &dummy)) {
2607 return "(error)";
2608 }
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002609 return reinterpret_cast<const char*>(ptr);
2610}
2611
2612static std::string GetClassOrError(const uint8_t* const begin,
2613 const DexFile::Header* const header,
Andreas Gampea5b09a62016-11-17 15:21:22 -08002614 dex::TypeIndex class_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002615 // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2616 // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2617 // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2618 // a valid defining class.
Andreas Gampea5b09a62016-11-17 15:21:22 -08002619 CHECK_LT(class_idx.index_, header->type_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002620
2621 const DexFile::TypeId* type_id =
Andreas Gampea5b09a62016-11-17 15:21:22 -08002622 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002623
2624 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2625
2626 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2627}
2628
2629static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2630 const DexFile::Header* const header,
2631 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002632 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2633 CHECK_LT(idx, header->field_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002634
2635 const DexFile::FieldId* field_id =
2636 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2637
2638 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2639
2640 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2641 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2642
2643 return class_name + "." + field_name;
2644}
2645
2646static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2647 const DexFile::Header* const header,
2648 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002649 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2650 CHECK_LT(idx, header->method_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002651
2652 const DexFile::MethodId* method_id =
2653 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2654
2655 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2656
2657 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2658 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2659
2660 return class_name + "." + method_name;
2661}
2662
2663bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2664 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002665 uint32_t class_access_flags,
2666 std::string* error_msg) {
2667 // Generally sort out >16-bit flags.
2668 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002669 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2670 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2671 field_access_flags,
2672 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002673 return false;
2674 }
2675
2676 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2677 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2678 kAccPrivate |
2679 kAccProtected |
2680 kAccStatic |
2681 kAccFinal |
2682 kAccVolatile |
2683 kAccTransient |
2684 kAccSynthetic |
2685 kAccEnum;
2686
2687 // Fields may have only one of public/protected/final.
2688 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002689 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2690 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2691 field_access_flags,
2692 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002693 return false;
2694 }
2695
2696 // Interfaces have a pretty restricted list.
2697 if ((class_access_flags & kAccInterface) != 0) {
2698 // Interface fields must be public final static.
2699 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2700 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002701 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2702 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2703 field_access_flags,
2704 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002705 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002706 return false;
2707 } else {
2708 // Allow in older versions, but warn.
2709 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2710 << *error_msg;
2711 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002712 }
2713 // Interface fields may be synthetic, but may not have other flags.
2714 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2715 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002716 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
2717 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2718 field_access_flags,
2719 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002720 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002721 return false;
2722 } else {
2723 // Allow in older versions, but warn.
2724 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2725 << *error_msg;
2726 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002727 }
2728 return true;
2729 }
2730
2731 // Volatile fields may not be final.
2732 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2733 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002734 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
2735 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002736 return false;
2737 }
2738
2739 return true;
2740}
2741
Andreas Gampee6215c02015-08-31 18:54:38 -07002742bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2743 uint32_t method_access_flags,
2744 uint32_t class_access_flags,
Orion Hodson6c4921b2016-09-21 15:41:06 +01002745 uint32_t constructor_flags_by_name,
Andreas Gampee6215c02015-08-31 18:54:38 -07002746 bool has_code,
2747 bool expect_direct,
2748 std::string* error_msg) {
2749 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2750 constexpr uint32_t kAllMethodFlags =
2751 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2752 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002753 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
2754 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2755 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002756 return false;
2757 }
2758
2759 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2760 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2761 kAccPrivate |
2762 kAccProtected |
2763 kAccStatic |
2764 kAccFinal |
2765 kAccSynthetic |
2766 kAccSynchronized |
2767 kAccBridge |
2768 kAccVarargs |
2769 kAccNative |
2770 kAccAbstract |
2771 kAccStrict;
2772
2773 // Methods may have only one of public/protected/final.
2774 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002775 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
2776 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002777 method_access_flags);
2778 return false;
2779 }
2780
Orion Hodson6c4921b2016-09-21 15:41:06 +01002781 constexpr uint32_t kConstructorFlags = kAccStatic | kAccConstructor;
2782 const bool is_constructor_by_name = (constructor_flags_by_name & kConstructorFlags) != 0;
2783 const bool is_clinit_by_name = constructor_flags_by_name == kConstructorFlags;
Andreas Gampee6215c02015-08-31 18:54:38 -07002784
2785 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2786 // the reverse for backwards compatibility reasons.
Orion Hodson6c4921b2016-09-21 15:41:06 +01002787 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002788 *error_msg =
2789 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
Orion Hodson6c4921b2016-09-21 15:41:06 +01002790 method_index,
2791 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002792 return false;
2793 }
Orion Hodson6c4921b2016-09-21 15:41:06 +01002794
2795 if (is_constructor_by_name) {
2796 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2797 // instance constructor is called "<init>".
Andreas Gampee6215c02015-08-31 18:54:38 -07002798 bool is_static = (method_access_flags & kAccStatic) != 0;
2799 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002800 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
2801 method_index,
2802 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002803 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2804 return false;
2805 } else {
2806 // Allow in older versions, but warn.
2807 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2808 << *error_msg;
2809 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002810 }
2811 }
Orion Hodson6c4921b2016-09-21 15:41:06 +01002812
Andreas Gampee6215c02015-08-31 18:54:38 -07002813 // Check that static and private methods, as well as constructors, are in the direct methods list,
2814 // and other methods in the virtual methods list.
Orion Hodson6c4921b2016-09-21 15:41:06 +01002815 bool is_direct = ((method_access_flags & (kAccStatic | kAccPrivate)) != 0) ||
2816 is_constructor_by_name;
Andreas Gampee6215c02015-08-31 18:54:38 -07002817 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002818 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07002819 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002820 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002821 expect_direct);
2822 return false;
2823 }
2824
Andreas Gampee6215c02015-08-31 18:54:38 -07002825 // From here on out it is easier to mask out the bits we're supposed to ignore.
2826 method_access_flags &= kMethodAccessFlags;
2827
Alex Lightd7c10c22016-03-31 10:03:07 -07002828 // Interfaces are special.
2829 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07002830 // Non-static interface methods must be public or private.
2831 uint32_t desired_flags = (kAccPublic | kAccStatic);
2832 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2833 desired_flags |= kAccPrivate;
2834 }
2835 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002836 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
2837 method_index,
2838 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002839 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002840 return false;
2841 } else {
2842 // Allow in older versions, but warn.
2843 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2844 << *error_msg;
2845 }
2846 }
2847 }
2848
Andreas Gampee6215c02015-08-31 18:54:38 -07002849 // If there aren't any instructions, make sure that's expected.
2850 if (!has_code) {
2851 // Only native or abstract methods may not have code.
2852 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002853 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07002854 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002855 method_index,
2856 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002857 return false;
2858 }
2859 // Constructors must always have code.
Orion Hodson6c4921b2016-09-21 15:41:06 +01002860 if (is_constructor_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002861 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
2862 method_index,
2863 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002864 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2865 return false;
2866 } else {
2867 // Allow in older versions, but warn.
2868 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2869 << *error_msg;
2870 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002871 }
2872 if ((method_access_flags & kAccAbstract) != 0) {
2873 // Abstract methods are not allowed to have the following flags.
2874 constexpr uint32_t kForbidden =
2875 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2876 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002877 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
2878 method_index,
2879 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2880 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002881 return false;
2882 }
Andreas Gampe97b11352015-12-10 16:23:41 -08002883 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07002884 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002885 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08002886 << " is abstract, but the declaring class is neither abstract nor an "
2887 << "interface in dex file "
2888 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07002889 }
2890 }
2891 // Interfaces are special.
2892 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002893 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07002894 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002895 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
2896 method_index,
2897 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002898 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002899 return false;
2900 } else {
2901 // Allow in older versions, but warn.
2902 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2903 << *error_msg;
2904 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002905 }
2906 // At this point, we know the method is public and abstract. This means that all the checks
2907 // for invalid combinations above applies. In addition, interface methods must not be
2908 // protected. This is caught by the check for only-one-of-public-protected-private.
2909 }
2910 return true;
2911 }
2912
2913 // When there's code, the method must not be native or abstract.
2914 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002915 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
2916 method_index,
2917 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002918 return false;
2919 }
2920
Andreas Gampee6215c02015-08-31 18:54:38 -07002921 // Instance constructors must not be synchronized and a few other flags.
Orion Hodson6c4921b2016-09-21 15:41:06 +01002922 if (constructor_flags_by_name == kAccConstructor) {
Andreas Gampee6215c02015-08-31 18:54:38 -07002923 static constexpr uint32_t kInitAllowed =
2924 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2925 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002926 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07002927 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002928 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002929 method_access_flags);
2930 return false;
2931 }
2932 }
2933
2934 return true;
2935}
2936
Orion Hodson6c4921b2016-09-21 15:41:06 +01002937bool DexFileVerifier::CheckConstructorProperties(
2938 uint32_t method_index,
2939 uint32_t constructor_flags) {
2940 DCHECK(constructor_flags == kAccConstructor ||
2941 constructor_flags == (kAccConstructor | kAccStatic));
2942
2943 // Check signature matches expectations.
2944 const DexFile::MethodId* const method_id = CheckLoadMethodId(method_index,
2945 "Bad <init>/<clinit> method id");
2946 if (method_id == nullptr) {
2947 return false;
2948 }
2949
2950 // Check the ProtoId for the corresponding method.
2951 //
2952 // TODO(oth): the error message here is to satisfy the MethodId test
2953 // in the DexFileVerifierTest. The test is checking that the error
2954 // contains this string if the index is out of range.
2955 const DexFile::ProtoId* const proto_id = CheckLoadProtoId(method_id->proto_idx_,
2956 "inter_method_id_item proto_idx");
2957 if (proto_id == nullptr) {
2958 return false;
2959 }
2960
2961 Signature signature = dex_file_->GetMethodSignature(*method_id);
2962 if (constructor_flags == (kAccStatic | kAccConstructor)) {
2963 if (!signature.IsVoid() || signature.GetNumberOfParameters() != 0) {
2964 ErrorStringPrintf("<clinit> must have descriptor ()V");
2965 return false;
2966 }
2967 } else if (!signature.IsVoid()) {
2968 ErrorStringPrintf("Constructor %u(%s) must be void",
2969 method_index,
2970 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
2971 return false;
2972 }
2973
2974 return true;
2975}
2976
jeffhao10037c82012-01-23 15:06:23 -08002977} // namespace art