blob: 0b3f16a3cb15e8e9775f6a879525d87281da3459 [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
Orion Hodson12f4ff42017-01-13 16:43:12 +000049static uint32_t MapTypeToBitMask(DexFile::MapItemType map_item_type) {
50 switch (map_item_type) {
jeffhao10037c82012-01-23 15:06:23 -080051 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;
Orion Hodson12f4ff42017-01-13 16:43:12 +000058 case DexFile::kDexTypeCallSiteIdItem: return 1 << 7;
59 case DexFile::kDexTypeMethodHandleItem: return 1 << 8;
60 case DexFile::kDexTypeMapList: return 1 << 9;
61 case DexFile::kDexTypeTypeList: return 1 << 10;
62 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 11;
63 case DexFile::kDexTypeAnnotationSetItem: return 1 << 12;
64 case DexFile::kDexTypeClassDataItem: return 1 << 13;
65 case DexFile::kDexTypeCodeItem: return 1 << 14;
66 case DexFile::kDexTypeStringDataItem: return 1 << 15;
67 case DexFile::kDexTypeDebugInfoItem: return 1 << 16;
68 case DexFile::kDexTypeAnnotationItem: return 1 << 17;
69 case DexFile::kDexTypeEncodedArrayItem: return 1 << 18;
70 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 19;
jeffhao10037c82012-01-23 15:06:23 -080071 }
72 return 0;
73}
74
Orion Hodson12f4ff42017-01-13 16:43:12 +000075static bool IsDataSectionType(DexFile::MapItemType map_item_type) {
76 switch (map_item_type) {
jeffhao10037c82012-01-23 15:06:23 -080077 case DexFile::kDexTypeHeaderItem:
78 case DexFile::kDexTypeStringIdItem:
79 case DexFile::kDexTypeTypeIdItem:
80 case DexFile::kDexTypeProtoIdItem:
81 case DexFile::kDexTypeFieldIdItem:
82 case DexFile::kDexTypeMethodIdItem:
83 case DexFile::kDexTypeClassDefItem:
84 return false;
Orion Hodson12f4ff42017-01-13 16:43:12 +000085 case DexFile::kDexTypeCallSiteIdItem:
86 case DexFile::kDexTypeMethodHandleItem:
87 case DexFile::kDexTypeMapList:
88 case DexFile::kDexTypeTypeList:
89 case DexFile::kDexTypeAnnotationSetRefList:
90 case DexFile::kDexTypeAnnotationSetItem:
91 case DexFile::kDexTypeClassDataItem:
92 case DexFile::kDexTypeCodeItem:
93 case DexFile::kDexTypeStringDataItem:
94 case DexFile::kDexTypeDebugInfoItem:
95 case DexFile::kDexTypeAnnotationItem:
96 case DexFile::kDexTypeEncodedArrayItem:
97 case DexFile::kDexTypeAnnotationsDirectoryItem:
98 return true;
jeffhao10037c82012-01-23 15:06:23 -080099 }
100 return true;
101}
102
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800103const char* DexFileVerifier::CheckLoadStringByIdx(dex::StringIndex idx, const char* error_string) {
104 if (UNLIKELY(!CheckIndex(idx.index_, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700105 return nullptr;
106 }
107 return dex_file_->StringDataByIdx(idx);
108}
109
Orion Hodson6c4921b2016-09-21 15:41:06 +0100110// Try to find the name of the method with the given index. We do not want to rely on DexFile
111// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
112// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
113// (flagged by the return value), otherwise error_msg will contain an error string.
114static bool FindMethodName(uint32_t method_index,
115 const uint8_t* begin,
116 const DexFile::Header* header,
117 const char** str,
118 std::string* error_msg) {
119 if (method_index >= header->method_ids_size_) {
120 *error_msg = "Method index not available for method flags verification";
121 return false;
122 }
123 uint32_t string_idx =
124 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
125 method_index)->name_idx_.index_;
126 if (string_idx >= header->string_ids_size_) {
127 *error_msg = "String index not available for method flags verification";
128 return false;
129 }
130 uint32_t string_off =
131 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
132 string_data_off_;
133 if (string_off >= header->file_size_) {
134 *error_msg = "String offset out of bounds for method flags verification";
135 return false;
136 }
137 const uint8_t* str_data_ptr = begin + string_off;
138 uint32_t dummy;
139 if (!DecodeUnsignedLeb128Checked(&str_data_ptr, begin + header->file_size_, &dummy)) {
140 *error_msg = "String size out of bounds for method flags verification";
141 return false;
142 }
143 *str = reinterpret_cast<const char*>(str_data_ptr);
144 return true;
145}
146
147// Gets constructor flags based on the |method_name|. Returns true if
148// method_name is either <clinit> or <init> and sets
149// |constructor_flags_by_name| appropriately. Otherwise set
150// |constructor_flags_by_name| to zero and returns whether
151// |method_name| is valid.
152bool GetConstructorFlagsForMethodName(const char* method_name,
153 uint32_t* constructor_flags_by_name) {
154 if (method_name[0] != '<') {
155 *constructor_flags_by_name = 0;
156 return true;
157 }
158 if (strcmp(method_name + 1, "clinit>") == 0) {
159 *constructor_flags_by_name = kAccStatic | kAccConstructor;
160 return true;
161 }
162 if (strcmp(method_name + 1, "init>") == 0) {
163 *constructor_flags_by_name = kAccConstructor;
164 return true;
165 }
166 *constructor_flags_by_name = 0;
167 return false;
168}
169
Andreas Gampea5b09a62016-11-17 15:21:22 -0800170const char* DexFileVerifier::CheckLoadStringByTypeIdx(dex::TypeIndex type_idx,
171 const char* error_string) {
172 if (UNLIKELY(!CheckIndex(type_idx.index_, dex_file_->NumTypeIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700173 return nullptr;
174 }
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800175 return CheckLoadStringByIdx(dex_file_->GetTypeId(type_idx).descriptor_idx_, error_string);
Andreas Gampee09269c2014-06-06 18:45:35 -0700176}
177
178const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -0700179 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700180 return nullptr;
181 }
182 return &dex_file_->GetFieldId(idx);
183}
184
185const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -0700186 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700187 return nullptr;
188 }
189 return &dex_file_->GetMethodId(idx);
190}
191
Orion Hodson6c4921b2016-09-21 15:41:06 +0100192const DexFile::ProtoId* DexFileVerifier::CheckLoadProtoId(uint32_t idx, const char* err_string) {
193 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumProtoIds(), err_string))) {
194 return nullptr;
195 }
196 return &dex_file_->GetProtoId(idx);
197}
198
Andreas Gampee09269c2014-06-06 18:45:35 -0700199// Helper macro to load string and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700200#define LOAD_STRING(var, idx, error) \
201 const char* (var) = CheckLoadStringByIdx(idx, error); \
202 if (UNLIKELY((var) == nullptr)) { \
203 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700204 }
205
206// Helper macro to load string by type idx and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700207#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
208 const char* (var) = CheckLoadStringByTypeIdx(type_idx, error); \
209 if (UNLIKELY((var) == nullptr)) { \
210 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700211 }
212
213// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700214#define LOAD_METHOD(var, idx, error_string, error_stmt) \
215 const DexFile::MethodId* (var) = CheckLoadMethodId(idx, error_string); \
216 if (UNLIKELY((var) == nullptr)) { \
217 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700218 }
219
220// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700221#define LOAD_FIELD(var, idx, fmt, error_stmt) \
222 const DexFile::FieldId* (var) = CheckLoadFieldId(idx, fmt); \
223 if (UNLIKELY((var) == nullptr)) { \
224 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700225 }
226
Aart Bik37d6a3b2016-06-21 18:30:10 -0700227bool DexFileVerifier::Verify(const DexFile* dex_file,
228 const uint8_t* begin,
229 size_t size,
230 const char* location,
231 bool verify_checksum,
232 std::string* error_msg) {
233 std::unique_ptr<DexFileVerifier> verifier(
234 new DexFileVerifier(dex_file, begin, size, location, verify_checksum));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700235 if (!verifier->Verify()) {
236 *error_msg = verifier->FailureReason();
237 return false;
238 }
239 return true;
240}
241
242bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
243 bool is_return_type) {
jeffhao10037c82012-01-23 15:06:23 -0800244 switch (shorty_char) {
245 case 'V':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700246 if (UNLIKELY(!is_return_type)) {
247 ErrorStringPrintf("Invalid use of void");
jeffhao10037c82012-01-23 15:06:23 -0800248 return false;
249 }
Ian Rogersfc787ec2014-10-09 21:56:44 -0700250 FALLTHROUGH_INTENDED;
jeffhao10037c82012-01-23 15:06:23 -0800251 case 'B':
252 case 'C':
253 case 'D':
254 case 'F':
255 case 'I':
256 case 'J':
257 case 'S':
258 case 'Z':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700259 if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
260 ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
261 shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800262 return false;
263 }
264 break;
265 case 'L':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700266 if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
267 ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800268 return false;
269 }
270 break;
271 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700272 ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
jeffhao10037c82012-01-23 15:06:23 -0800273 return false;
274 }
275 return true;
276}
277
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700278bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700279 const char* label) {
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700280 // Check that size is not 0.
281 CHECK_NE(elem_size, 0U);
282
Ian Rogers13735952014-10-08 12:43:28 -0700283 const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
284 const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700285
286 // Check for overflow.
287 uintptr_t max = 0 - 1;
288 size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
289 size_t max_count = available_bytes_till_end_of_mem / elem_size;
290 if (max_count < count) {
291 ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
292 static_cast<size_t>(range_start - file_start),
293 count, elem_size);
294 return false;
295 }
296
Ian Rogers13735952014-10-08 12:43:28 -0700297 const uint8_t* range_end = range_start + count * elem_size;
298 const uint8_t* file_end = file_start + size_;
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700299 if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
300 // Note: these two tests are enough as we make sure above that there's no overflow.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800301 ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
Ian Rogerse3d55812014-06-11 13:00:44 -0700302 static_cast<size_t>(range_start - file_start),
303 static_cast<size_t>(range_end - file_start));
jeffhao10037c82012-01-23 15:06:23 -0800304 return false;
305 }
306 return true;
307}
308
Ian Rogers13735952014-10-08 12:43:28 -0700309bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700310 // Check that the list is available. The first 4B are the count.
311 if (!CheckListSize(*ptr, 1, 4U, label)) {
312 return false;
313 }
314
315 uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
316 if (count > 0) {
317 if (!CheckListSize(*ptr + 4, count, element_size, label)) {
318 return false;
319 }
320 }
321
322 *ptr += 4 + count * element_size;
323 return true;
324}
325
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700326bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
327 if (UNLIKELY(field >= limit)) {
328 ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
jeffhao10037c82012-01-23 15:06:23 -0800329 return false;
330 }
331 return true;
332}
333
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800334bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
335 uint32_t size,
336 size_t alignment,
337 const char* label) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700338 if (size == 0) {
339 if (offset != 0) {
340 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
341 return false;
342 }
343 }
344 if (size_ <= offset) {
345 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
346 return false;
347 }
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800348 if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
349 ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
350 return false;
351 }
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700352 return true;
353}
354
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100355bool DexFileVerifier::CheckSizeLimit(uint32_t size, uint32_t limit, const char* label) {
356 if (size > limit) {
357 ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label);
358 return false;
359 }
360 return true;
361}
362
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700363bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800364 // Check file size from the header.
365 uint32_t expected_size = header_->file_size_;
366 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700367 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800368 return false;
369 }
370
371 // Compute and verify the checksum in the header.
372 uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
373 const uint32_t non_sum = sizeof(header_->magic_) + sizeof(header_->checksum_);
Ian Rogers13735952014-10-08 12:43:28 -0700374 const uint8_t* non_sum_ptr = reinterpret_cast<const uint8_t*>(header_) + non_sum;
jeffhaof6174e82012-01-31 16:14:17 -0800375 adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
jeffhao10037c82012-01-23 15:06:23 -0800376 if (adler_checksum != header_->checksum_) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700377 if (verify_checksum_) {
378 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
379 return false;
380 } else {
381 LOG(WARNING) << StringPrintf(
382 "Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
383 }
jeffhao10037c82012-01-23 15:06:23 -0800384 }
385
386 // Check the contents of the header.
387 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700388 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800389 return false;
390 }
391
392 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700393 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800394 return false;
395 }
396
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700397 // Check that all offsets are inside the file.
398 bool result =
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800399 CheckValidOffsetAndSize(header_->link_off_,
400 header_->link_size_,
401 0 /* unaligned */,
402 "link") &&
403 CheckValidOffsetAndSize(header_->map_off_,
404 header_->map_off_,
405 4,
406 "map") &&
407 CheckValidOffsetAndSize(header_->string_ids_off_,
408 header_->string_ids_size_,
409 4,
410 "string-ids") &&
411 CheckValidOffsetAndSize(header_->type_ids_off_,
412 header_->type_ids_size_,
413 4,
414 "type-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100415 CheckSizeLimit(header_->type_ids_size_, DexFile::kDexNoIndex16, "type-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800416 CheckValidOffsetAndSize(header_->proto_ids_off_,
417 header_->proto_ids_size_,
418 4,
419 "proto-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100420 CheckSizeLimit(header_->proto_ids_size_, DexFile::kDexNoIndex16, "proto-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800421 CheckValidOffsetAndSize(header_->field_ids_off_,
422 header_->field_ids_size_,
423 4,
424 "field-ids") &&
425 CheckValidOffsetAndSize(header_->method_ids_off_,
426 header_->method_ids_size_,
427 4,
428 "method-ids") &&
429 CheckValidOffsetAndSize(header_->class_defs_off_,
430 header_->class_defs_size_,
431 4,
432 "class-defs") &&
433 CheckValidOffsetAndSize(header_->data_off_,
434 header_->data_size_,
435 0, // Unaligned, spec doesn't talk about it, even though size
436 // is supposed to be a multiple of 4.
437 "data");
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700438 return result;
jeffhao10037c82012-01-23 15:06:23 -0800439}
440
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700441bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700442 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
443 header_->map_off_);
444 // Check that map list content is available.
445 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
446 return false;
447 }
448
jeffhao10037c82012-01-23 15:06:23 -0800449 const DexFile::MapItem* item = map->list_;
450
451 uint32_t count = map->size_;
452 uint32_t last_offset = 0;
453 uint32_t data_item_count = 0;
454 uint32_t data_items_left = header_->data_size_;
455 uint32_t used_bits = 0;
456
457 // Sanity check the size of the map list.
458 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
459 return false;
460 }
461
462 // Check the items listed in the map.
463 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700464 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
465 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800466 return false;
467 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700468 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
469 ErrorStringPrintf("Map item after end of file: %x, size %x",
470 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800471 return false;
472 }
473
Orion Hodson12f4ff42017-01-13 16:43:12 +0000474 DexFile::MapItemType item_type = static_cast<DexFile::MapItemType>(item->type_);
475 if (IsDataSectionType(item_type)) {
jeffhao10037c82012-01-23 15:06:23 -0800476 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700477 if (UNLIKELY(icount > data_items_left)) {
478 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800479 return false;
480 }
481 data_items_left -= icount;
482 data_item_count += icount;
483 }
484
Orion Hodson12f4ff42017-01-13 16:43:12 +0000485 uint32_t bit = MapTypeToBitMask(item_type);
jeffhao10037c82012-01-23 15:06:23 -0800486
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700487 if (UNLIKELY(bit == 0)) {
488 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800489 return false;
490 }
491
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700492 if (UNLIKELY((used_bits & bit) != 0)) {
493 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800494 return false;
495 }
496
497 used_bits |= bit;
498 last_offset = item->offset_;
499 item++;
500 }
501
502 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700503 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
504 ErrorStringPrintf("Map is missing header entry");
jeffhao10037c82012-01-23 15:06:23 -0800505 return false;
506 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700507 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
508 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800509 return false;
510 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700511 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
512 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
513 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800514 return false;
515 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700516 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
517 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
518 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800519 return false;
520 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700521 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
522 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
523 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800524 return false;
525 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700526 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
527 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
528 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800529 return false;
530 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700531 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
532 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
533 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800534 return false;
535 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700536 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
537 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
538 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800539 return false;
540 }
jeffhao10037c82012-01-23 15:06:23 -0800541 return true;
542}
543
544uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
545 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700546 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700547 for (uint32_t i = 0; i < size; i++) {
548 result |= ((uint32_t) *(ptr_++)) << (i * 8);
549 }
jeffhao10037c82012-01-23 15:06:23 -0800550 }
jeffhao10037c82012-01-23 15:06:23 -0800551 return result;
552}
553
Andreas Gampebed6daf2016-09-02 18:12:00 -0700554
555#define DECODE_UNSIGNED_CHECKED_FROM_WITH_ERROR_VALUE(ptr, var, error_value) \
556 uint32_t var; \
Andreas Gampe44fd2352016-11-03 08:21:21 -0700557 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700558 return error_value; \
559 }
560
Andreas Gampe44fd2352016-11-03 08:21:21 -0700561#define DECODE_UNSIGNED_CHECKED_FROM(ptr, var) \
562 uint32_t var; \
563 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
564 ErrorStringPrintf("Read out of bounds"); \
565 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700566 }
567
Andreas Gampe44fd2352016-11-03 08:21:21 -0700568#define DECODE_SIGNED_CHECKED_FROM(ptr, var) \
569 int32_t var; \
570 if (!DecodeSignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
571 ErrorStringPrintf("Read out of bounds"); \
572 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700573 }
574
jeffhao10037c82012-01-23 15:06:23 -0800575bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700576 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700577 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800578
579 for (uint32_t i = 0; i < handlers_size; i++) {
580 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800581 size_t offset = ptr_ - handlers_base;
Andreas Gampebed6daf2016-09-02 18:12:00 -0700582 DECODE_SIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800583
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700584 if (UNLIKELY((size < -65536) || (size > 65536))) {
585 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800586 return false;
587 }
588
589 if (size <= 0) {
590 catch_all = true;
591 size = -size;
592 } else {
593 catch_all = false;
594 }
595
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800596 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800597
598 while (size-- > 0) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700599 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -0800600 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
601 return false;
602 }
603
Andreas Gampebed6daf2016-09-02 18:12:00 -0700604 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700605 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
606 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800607 return false;
608 }
609 }
610
611 if (catch_all) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700612 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700613 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
614 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800615 return false;
616 }
617 }
618 }
619
620 return true;
621}
622
Andreas Gampee6215c02015-08-31 18:54:38 -0700623bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
624 uint32_t access_flags,
625 uint32_t class_access_flags,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800626 dex::TypeIndex class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700627 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700628 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800629 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
630 return false;
631 }
632
Andreas Gampee6215c02015-08-31 18:54:38 -0700633 // Check that it's the right class.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800634 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700635 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
636 class_idx_;
637 if (class_type_index != my_class_index) {
638 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800639 my_class_index.index_,
640 class_type_index.index_);
Andreas Gampee6215c02015-08-31 18:54:38 -0700641 return false;
642 }
643
644 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800645 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700646 if (UNLIKELY(is_static != expect_static)) {
647 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800648 return false;
649 }
650
Andreas Gampee6215c02015-08-31 18:54:38 -0700651 // Check field access flags.
652 std::string error_msg;
Andreas Gampec9f0ba12016-02-09 09:21:04 -0800653 if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700654 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800655 return false;
656 }
657
658 return true;
659}
660
Andreas Gampee6215c02015-08-31 18:54:38 -0700661bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
662 uint32_t access_flags,
663 uint32_t class_access_flags,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800664 dex::TypeIndex class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700665 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700666 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700667 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700668 DCHECK(direct_method_indexes != nullptr);
669 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800670 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
671 return false;
672 }
673
Andreas Gampee6215c02015-08-31 18:54:38 -0700674 // Check that it's the right class.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800675 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700676 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
677 class_idx_;
678 if (class_type_index != my_class_index) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700679 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 " vs %" PRIu16,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800680 my_class_index.index_,
681 class_type_index.index_);
jeffhao10037c82012-01-23 15:06:23 -0800682 return false;
683 }
684
Andreas Gampee6215c02015-08-31 18:54:38 -0700685 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700686 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700687 direct_method_indexes->insert(idx);
688 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700689 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
690 return false;
691 }
692
Andreas Gampee6215c02015-08-31 18:54:38 -0700693 std::string error_msg;
Orion Hodson6c4921b2016-09-21 15:41:06 +0100694 const char* method_name;
695 if (!FindMethodName(idx, begin_, header_, &method_name, &error_msg)) {
696 ErrorStringPrintf("%s", error_msg.c_str());
697 return false;
698 }
699
700 uint32_t constructor_flags_by_name = 0;
701 if (!GetConstructorFlagsForMethodName(method_name, &constructor_flags_by_name)) {
702 ErrorStringPrintf("Bad method name: %s", method_name);
703 return false;
704 }
705
706 bool has_code = (code_offset != 0);
Andreas Gampee6215c02015-08-31 18:54:38 -0700707 if (!CheckMethodAccessFlags(idx,
708 access_flags,
709 class_access_flags,
Orion Hodson6c4921b2016-09-21 15:41:06 +0100710 constructor_flags_by_name,
Andreas Gampee6215c02015-08-31 18:54:38 -0700711 has_code,
712 expect_direct,
713 &error_msg)) {
714 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800715 return false;
716 }
717
Orion Hodson6c4921b2016-09-21 15:41:06 +0100718 if (constructor_flags_by_name != 0) {
719 if (!CheckConstructorProperties(idx, constructor_flags_by_name)) {
720 DCHECK(FailureReasonIsSet());
721 return false;
722 }
723 }
724
jeffhao10037c82012-01-23 15:06:23 -0800725 return true;
726}
727
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800728bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800729 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700730 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800731 return false;
732 }
733 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700734 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800735 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800736 return false;
737 }
738 ptr_++;
739 offset++;
740 }
741 }
742 return true;
743}
744
745bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700746 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800747 return false;
748 }
749
750 uint8_t header_byte = *(ptr_++);
751 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
752 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
753
754 switch (value_type) {
755 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700756 if (UNLIKELY(value_arg != 0)) {
757 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800758 return false;
759 }
760 ptr_++;
761 break;
762 case DexFile::kDexAnnotationShort:
763 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700764 if (UNLIKELY(value_arg > 1)) {
765 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800766 return false;
767 }
768 ptr_ += value_arg + 1;
769 break;
770 case DexFile::kDexAnnotationInt:
771 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700772 if (UNLIKELY(value_arg > 3)) {
773 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800774 return false;
775 }
776 ptr_ += value_arg + 1;
777 break;
778 case DexFile::kDexAnnotationLong:
779 case DexFile::kDexAnnotationDouble:
780 ptr_ += value_arg + 1;
781 break;
782 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700783 if (UNLIKELY(value_arg > 3)) {
784 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800785 return false;
786 }
787 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
788 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
789 return false;
790 }
791 break;
792 }
793 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700794 if (UNLIKELY(value_arg > 3)) {
795 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800796 return false;
797 }
798 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
799 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
800 return false;
801 }
802 break;
803 }
804 case DexFile::kDexAnnotationField:
805 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700806 if (UNLIKELY(value_arg > 3)) {
807 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800808 return false;
809 }
810 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
811 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
812 return false;
813 }
814 break;
815 }
816 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700817 if (UNLIKELY(value_arg > 3)) {
818 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800819 return false;
820 }
821 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
822 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
823 return false;
824 }
825 break;
826 }
827 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700828 if (UNLIKELY(value_arg != 0)) {
829 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800830 return false;
831 }
832 if (!CheckEncodedArray()) {
833 return false;
834 }
835 break;
836 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700837 if (UNLIKELY(value_arg != 0)) {
838 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800839 return false;
840 }
841 if (!CheckEncodedAnnotation()) {
842 return false;
843 }
844 break;
845 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700846 if (UNLIKELY(value_arg != 0)) {
847 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800848 return false;
849 }
850 break;
851 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700852 if (UNLIKELY(value_arg > 1)) {
853 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800854 return false;
855 }
856 break;
Orion Hodson12f4ff42017-01-13 16:43:12 +0000857 case DexFile::kDexAnnotationMethodType: {
858 if (UNLIKELY(value_arg > 3)) {
859 ErrorStringPrintf("Bad encoded_value method type size %x", value_arg);
860 return false;
861 }
862 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
863 if (!CheckIndex(idx, header_->proto_ids_size_, "method_type value")) {
864 return false;
865 }
866 break;
867 }
868 case DexFile::kDexAnnotationMethodHandle: {
869 if (UNLIKELY(value_arg > 3)) {
870 ErrorStringPrintf("Bad encoded_value method handle size %x", value_arg);
871 return false;
872 }
873 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
874 if (!CheckIndex(idx, dex_file_->NumMethodHandles(), "method_handle value")) {
875 return false;
876 }
877 break;
878 }
jeffhao10037c82012-01-23 15:06:23 -0800879 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700880 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800881 return false;
882 }
883
884 return true;
885}
886
887bool DexFileVerifier::CheckEncodedArray() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700888 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800889
890 while (size--) {
891 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700892 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800893 return false;
894 }
895 }
896 return true;
897}
898
899bool DexFileVerifier::CheckEncodedAnnotation() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700900 DECODE_UNSIGNED_CHECKED_FROM(ptr_, anno_idx);
901 if (!CheckIndex(anno_idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -0800902 return false;
903 }
904
Andreas Gampebed6daf2016-09-02 18:12:00 -0700905 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800906 uint32_t last_idx = 0;
907
908 for (uint32_t i = 0; i < size; i++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700909 DECODE_UNSIGNED_CHECKED_FROM(ptr_, idx);
jeffhao10037c82012-01-23 15:06:23 -0800910 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
911 return false;
912 }
913
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700914 if (UNLIKELY(last_idx >= idx && i != 0)) {
915 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
916 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800917 return false;
918 }
919
920 if (!CheckEncodedValue()) {
921 return false;
922 }
923
924 last_idx = idx;
925 }
926 return true;
927}
928
Andreas Gampee6215c02015-08-31 18:54:38 -0700929bool DexFileVerifier::FindClassFlags(uint32_t index,
930 bool is_field,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800931 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700932 uint32_t* class_access_flags) {
933 DCHECK(class_type_index != nullptr);
934 DCHECK(class_access_flags != nullptr);
935
936 // First check if the index is valid.
937 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
938 return false;
939 }
940
941 // Next get the type index.
942 if (is_field) {
943 *class_type_index =
944 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
945 class_idx_;
946 } else {
947 *class_type_index =
948 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
949 class_idx_;
950 }
951
952 // Check if that is valid.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800953 if (class_type_index->index_ >= header_->type_ids_size_) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700954 return false;
955 }
956
957 // Now search for the class def. This is basically a specialized version of the DexFile code, as
958 // we should not trust that this is a valid DexFile just yet.
959 const DexFile::ClassDef* class_def_begin =
960 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
961 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
962 const DexFile::ClassDef* class_def = class_def_begin + i;
963 if (class_def->class_idx_ == *class_type_index) {
964 *class_access_flags = class_def->access_flags_;
965 return true;
966 }
967 }
968
969 // Didn't find the class-def, not defined here...
970 return false;
971}
972
973bool DexFileVerifier::CheckOrderAndGetClassFlags(bool is_field,
974 const char* type_descr,
975 uint32_t curr_index,
976 uint32_t prev_index,
977 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800978 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700979 uint32_t* class_access_flags) {
980 if (curr_index < prev_index) {
981 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
982 type_descr,
983 prev_index,
984 curr_index);
985 return false;
986 }
987
988 if (!*have_class) {
989 *have_class = FindClassFlags(curr_index, is_field, class_type_index, class_access_flags);
990 if (!*have_class) {
991 // Should have really found one.
992 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
993 type_descr,
994 curr_index);
995 return false;
996 }
997 }
998 return true;
999}
1000
1001template <bool kStatic>
1002bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
1003 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -08001004 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -07001005 uint32_t* class_access_flags) {
1006 DCHECK(it != nullptr);
1007 // These calls use the raw access flags to check whether the whole dex field is valid.
1008 uint32_t prev_index = 0;
1009 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
1010 uint32_t curr_index = it->GetMemberIndex();
1011 if (!CheckOrderAndGetClassFlags(true,
1012 kStatic ? "static field" : "instance field",
1013 curr_index,
1014 prev_index,
1015 have_class,
1016 class_type_index,
1017 class_access_flags)) {
1018 return false;
1019 }
1020 prev_index = curr_index;
1021
1022 if (!CheckClassDataItemField(curr_index,
1023 it->GetRawMemberAccessFlags(),
1024 *class_access_flags,
1025 *class_type_index,
1026 kStatic)) {
1027 return false;
1028 }
1029 }
1030
1031 return true;
1032}
1033
1034template <bool kDirect>
1035bool DexFileVerifier::CheckIntraClassDataItemMethods(
1036 ClassDataItemIterator* it,
1037 std::unordered_set<uint32_t>* direct_method_indexes,
1038 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -08001039 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -07001040 uint32_t* class_access_flags) {
1041 uint32_t prev_index = 0;
1042 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
1043 uint32_t curr_index = it->GetMemberIndex();
1044 if (!CheckOrderAndGetClassFlags(false,
1045 kDirect ? "direct method" : "virtual method",
1046 curr_index,
1047 prev_index,
1048 have_class,
1049 class_type_index,
1050 class_access_flags)) {
1051 return false;
1052 }
1053 prev_index = curr_index;
1054
1055 if (!CheckClassDataItemMethod(curr_index,
1056 it->GetRawMemberAccessFlags(),
1057 *class_access_flags,
1058 *class_type_index,
1059 it->GetMethodCodeItemOffset(),
1060 direct_method_indexes,
1061 kDirect)) {
1062 return false;
1063 }
1064 }
1065
1066 return true;
1067}
1068
jeffhao10037c82012-01-23 15:06:23 -08001069bool DexFileVerifier::CheckIntraClassDataItem() {
1070 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -07001071 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -08001072
Andreas Gampee6215c02015-08-31 18:54:38 -07001073 // This code is complicated by the fact that we don't directly know which class this belongs to.
1074 // So we need to explicitly search with the first item we find (either field or method), and then,
1075 // as the lookup is expensive, cache the result.
1076 bool have_class = false;
Andreas Gampea5b09a62016-11-17 15:21:22 -08001077 dex::TypeIndex class_type_index;
Andreas Gampee6215c02015-08-31 18:54:38 -07001078 uint32_t class_access_flags;
1079
1080 // Check fields.
1081 if (!CheckIntraClassDataItemFields<true>(&it,
1082 &have_class,
1083 &class_type_index,
1084 &class_access_flags)) {
1085 return false;
jeffhao10037c82012-01-23 15:06:23 -08001086 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001087 if (!CheckIntraClassDataItemFields<false>(&it,
1088 &have_class,
1089 &class_type_index,
1090 &class_access_flags)) {
1091 return false;
jeffhao10037c82012-01-23 15:06:23 -08001092 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001093
1094 // Check methods.
1095 if (!CheckIntraClassDataItemMethods<true>(&it,
1096 &direct_method_indexes,
1097 &have_class,
1098 &class_type_index,
1099 &class_access_flags)) {
1100 return false;
jeffhao10037c82012-01-23 15:06:23 -08001101 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001102 if (!CheckIntraClassDataItemMethods<false>(&it,
1103 &direct_method_indexes,
1104 &have_class,
1105 &class_type_index,
1106 &class_access_flags)) {
1107 return false;
jeffhao10037c82012-01-23 15:06:23 -08001108 }
1109
1110 ptr_ = it.EndDataPointer();
1111 return true;
1112}
1113
1114bool DexFileVerifier::CheckIntraCodeItem() {
1115 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001116 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -08001117 return false;
1118 }
1119
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001120 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
1121 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
1122 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -08001123 return false;
1124 }
1125
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001126 if (UNLIKELY((code_item->outs_size_ > 5) &&
1127 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -08001128 /*
1129 * outs_size can be up to 5, even if registers_size is smaller, since the
1130 * short forms of method invocation allow repetitions of a register multiple
1131 * times within a single parameter list. However, longer parameter lists
1132 * need to be represented in-order in the register file.
1133 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001134 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
1135 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -08001136 return false;
1137 }
1138
1139 const uint16_t* insns = code_item->insns_;
1140 uint32_t insns_size = code_item->insns_size_in_code_units_;
1141 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
1142 return false;
1143 }
1144
1145 // Grab the end of the insns if there are no try_items.
1146 uint32_t try_items_size = code_item->tries_size_;
1147 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001148 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001149 return true;
1150 }
1151
1152 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001153 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001154 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001155 return false;
1156 }
1157
1158 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -08001159 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
1160 return false;
1161 }
1162
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001163 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
Andreas Gampebed6daf2016-09-02 18:12:00 -07001164 DECODE_UNSIGNED_CHECKED_FROM(ptr_, handlers_size);
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001165
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001166 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
1167 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -08001168 return false;
1169 }
1170
Ian Rogers700a4022014-05-19 16:49:03 -07001171 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -07001172 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -08001173 return false;
1174 }
1175
1176 uint32_t last_addr = 0;
1177 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001178 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1179 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001180 return false;
1181 }
1182
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001183 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1184 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001185 return false;
1186 }
1187
1188 uint32_t i;
1189 for (i = 0; i < handlers_size; i++) {
1190 if (try_items->handler_off_ == handler_offsets[i]) {
1191 break;
1192 }
1193 }
1194
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001195 if (UNLIKELY(i == handlers_size)) {
1196 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -08001197 return false;
1198 }
1199
1200 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001201 if (UNLIKELY(last_addr > insns_size)) {
1202 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -08001203 return false;
1204 }
1205
1206 try_items++;
1207 }
1208
1209 return true;
1210}
1211
1212bool DexFileVerifier::CheckIntraStringDataItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001213 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
Ian Rogers13735952014-10-08 12:43:28 -07001214 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001215
1216 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001217 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001218 if (UNLIKELY(ptr_ >= file_end)) {
1219 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001220 return false;
1221 }
1222
1223 uint8_t byte = *(ptr_++);
1224
1225 // Switch on the high 4 bits.
1226 switch (byte >> 4) {
1227 case 0x00:
1228 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001229 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001230 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001231 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001232 return false;
1233 }
1234 break;
1235 case 0x01:
1236 case 0x02:
1237 case 0x03:
1238 case 0x04:
1239 case 0x05:
1240 case 0x06:
1241 case 0x07:
1242 // No extra checks necessary for bit pattern 0xxx.
1243 break;
1244 case 0x08:
1245 case 0x09:
1246 case 0x0a:
1247 case 0x0b:
1248 case 0x0f:
1249 // Illegal bit patterns 10xx or 1111.
1250 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001251 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001252 return false;
1253 case 0x0c:
1254 case 0x0d: {
1255 // Bit pattern 110x has an additional byte.
1256 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001257 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1258 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001259 return false;
1260 }
1261 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001262 if (UNLIKELY((value != 0) && (value < 0x80))) {
1263 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001264 return false;
1265 }
1266 break;
1267 }
1268 case 0x0e: {
1269 // Bit pattern 1110 has 2 additional bytes.
1270 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001271 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1272 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001273 return false;
1274 }
1275 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001276 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1277 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001278 return false;
1279 }
1280 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001281 if (UNLIKELY(value < 0x800)) {
1282 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001283 return false;
1284 }
1285 break;
1286 }
1287 }
1288 }
1289
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001290 if (UNLIKELY(*(ptr_++) != '\0')) {
1291 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001292 return false;
1293 }
1294
1295 return true;
1296}
1297
1298bool DexFileVerifier::CheckIntraDebugInfoItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001299 DECODE_UNSIGNED_CHECKED_FROM(ptr_, dummy);
1300 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameters_size);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001301 if (UNLIKELY(parameters_size > 65536)) {
1302 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001303 return false;
1304 }
1305
1306 for (uint32_t j = 0; j < parameters_size; j++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001307 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameter_name);
jeffhao10037c82012-01-23 15:06:23 -08001308 if (parameter_name != 0) {
1309 parameter_name--;
1310 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1311 return false;
1312 }
1313 }
1314 }
1315
1316 while (true) {
1317 uint8_t opcode = *(ptr_++);
1318 switch (opcode) {
1319 case DexFile::DBG_END_SEQUENCE: {
1320 return true;
1321 }
1322 case DexFile::DBG_ADVANCE_PC: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001323 DECODE_UNSIGNED_CHECKED_FROM(ptr_, advance_pc_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001324 break;
1325 }
1326 case DexFile::DBG_ADVANCE_LINE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001327 DECODE_SIGNED_CHECKED_FROM(ptr_, advance_line_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001328 break;
1329 }
1330 case DexFile::DBG_START_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001331 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001332 if (UNLIKELY(reg_num >= 65536)) {
1333 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001334 return false;
1335 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001336 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001337 if (name_idx != 0) {
1338 name_idx--;
1339 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1340 return false;
1341 }
1342 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001343 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001344 if (type_idx != 0) {
1345 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001346 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001347 return false;
1348 }
1349 }
1350 break;
1351 }
1352 case DexFile::DBG_END_LOCAL:
1353 case DexFile::DBG_RESTART_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001354 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001355 if (UNLIKELY(reg_num >= 65536)) {
1356 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001357 return false;
1358 }
1359 break;
1360 }
1361 case DexFile::DBG_START_LOCAL_EXTENDED: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001362 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001363 if (UNLIKELY(reg_num >= 65536)) {
1364 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001365 return false;
1366 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001367 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001368 if (name_idx != 0) {
1369 name_idx--;
1370 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1371 return false;
1372 }
1373 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001374 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001375 if (type_idx != 0) {
1376 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001377 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001378 return false;
1379 }
1380 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001381 DECODE_UNSIGNED_CHECKED_FROM(ptr_, sig_idx);
jeffhao10037c82012-01-23 15:06:23 -08001382 if (sig_idx != 0) {
1383 sig_idx--;
1384 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1385 return false;
1386 }
1387 }
1388 break;
1389 }
1390 case DexFile::DBG_SET_FILE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001391 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001392 if (name_idx != 0) {
1393 name_idx--;
1394 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1395 return false;
1396 }
1397 }
1398 break;
1399 }
1400 }
1401 }
1402}
1403
1404bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001405 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001406 return false;
1407 }
1408
1409 // Check visibility
1410 switch (*(ptr_++)) {
1411 case DexFile::kDexVisibilityBuild:
1412 case DexFile::kDexVisibilityRuntime:
1413 case DexFile::kDexVisibilitySystem:
1414 break;
1415 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001416 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001417 return false;
1418 }
1419
1420 if (!CheckEncodedAnnotation()) {
1421 return false;
1422 }
1423
1424 return true;
1425}
1426
1427bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1428 const DexFile::AnnotationsDirectoryItem* item =
1429 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001430 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001431 return false;
1432 }
1433
1434 // Field annotations follow immediately after the annotations directory.
1435 const DexFile::FieldAnnotationsItem* field_item =
1436 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1437 uint32_t field_count = item->fields_size_;
1438 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1439 return false;
1440 }
1441
1442 uint32_t last_idx = 0;
1443 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001444 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1445 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001446 return false;
1447 }
1448 last_idx = field_item->field_idx_;
1449 field_item++;
1450 }
1451
1452 // Method annotations follow immediately after field annotations.
1453 const DexFile::MethodAnnotationsItem* method_item =
1454 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1455 uint32_t method_count = item->methods_size_;
1456 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1457 return false;
1458 }
1459
1460 last_idx = 0;
1461 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001462 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1463 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1464 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001465 return false;
1466 }
1467 last_idx = method_item->method_idx_;
1468 method_item++;
1469 }
1470
1471 // Parameter annotations follow immediately after method annotations.
1472 const DexFile::ParameterAnnotationsItem* parameter_item =
1473 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1474 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001475 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001476 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001477 return false;
1478 }
1479
1480 last_idx = 0;
1481 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001482 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1483 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1484 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001485 return false;
1486 }
1487 last_idx = parameter_item->method_idx_;
1488 parameter_item++;
1489 }
1490
1491 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001492 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001493 return true;
1494}
1495
Andreas Gampeb061cc12014-09-02 10:22:20 -07001496bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
Orion Hodson12f4ff42017-01-13 16:43:12 +00001497 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -08001498 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001499 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001500 switch (type) {
1501 case DexFile::kDexTypeClassDataItem:
1502 case DexFile::kDexTypeStringDataItem:
1503 case DexFile::kDexTypeDebugInfoItem:
1504 case DexFile::kDexTypeAnnotationItem:
1505 case DexFile::kDexTypeEncodedArrayItem:
1506 alignment_mask = sizeof(uint8_t) - 1;
1507 break;
1508 default:
1509 alignment_mask = sizeof(uint32_t) - 1;
1510 break;
1511 }
1512
1513 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001514 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001515 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001516
1517 // Check the padding between items.
1518 if (!CheckPadding(offset, aligned_offset)) {
1519 return false;
1520 }
1521
1522 // Check depending on the section type.
Orion Hodson12f4ff42017-01-13 16:43:12 +00001523 const uint8_t* start_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08001524 switch (type) {
1525 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001526 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001527 return false;
1528 }
1529 ptr_ += sizeof(DexFile::StringId);
1530 break;
1531 }
1532 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001533 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001534 return false;
1535 }
1536 ptr_ += sizeof(DexFile::TypeId);
1537 break;
1538 }
1539 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001540 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001541 return false;
1542 }
1543 ptr_ += sizeof(DexFile::ProtoId);
1544 break;
1545 }
1546 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001547 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001548 return false;
1549 }
1550 ptr_ += sizeof(DexFile::FieldId);
1551 break;
1552 }
1553 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001554 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001555 return false;
1556 }
1557 ptr_ += sizeof(DexFile::MethodId);
1558 break;
1559 }
1560 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001561 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001562 return false;
1563 }
1564 ptr_ += sizeof(DexFile::ClassDef);
1565 break;
1566 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00001567 case DexFile::kDexTypeCallSiteIdItem: {
1568 if (!CheckListSize(ptr_, 1, sizeof(DexFile::CallSiteIdItem), "call_site_ids")) {
1569 return false;
1570 }
1571 ptr_ += sizeof(DexFile::CallSiteIdItem);
1572 break;
1573 }
1574 case DexFile::kDexTypeMethodHandleItem: {
1575 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodHandleItem), "method_handles")) {
1576 return false;
1577 }
1578 ptr_ += sizeof(DexFile::MethodHandleItem);
1579 break;
1580 }
jeffhao10037c82012-01-23 15:06:23 -08001581 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001582 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001583 return false;
1584 }
jeffhao10037c82012-01-23 15:06:23 -08001585 break;
1586 }
1587 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001588 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001589 return false;
1590 }
jeffhao10037c82012-01-23 15:06:23 -08001591 break;
1592 }
1593 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001594 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001595 return false;
1596 }
jeffhao10037c82012-01-23 15:06:23 -08001597 break;
1598 }
1599 case DexFile::kDexTypeClassDataItem: {
1600 if (!CheckIntraClassDataItem()) {
1601 return false;
1602 }
1603 break;
1604 }
1605 case DexFile::kDexTypeCodeItem: {
1606 if (!CheckIntraCodeItem()) {
1607 return false;
1608 }
1609 break;
1610 }
1611 case DexFile::kDexTypeStringDataItem: {
1612 if (!CheckIntraStringDataItem()) {
1613 return false;
1614 }
1615 break;
1616 }
1617 case DexFile::kDexTypeDebugInfoItem: {
1618 if (!CheckIntraDebugInfoItem()) {
1619 return false;
1620 }
1621 break;
1622 }
1623 case DexFile::kDexTypeAnnotationItem: {
1624 if (!CheckIntraAnnotationItem()) {
1625 return false;
1626 }
1627 break;
1628 }
1629 case DexFile::kDexTypeEncodedArrayItem: {
1630 if (!CheckEncodedArray()) {
1631 return false;
1632 }
1633 break;
1634 }
1635 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1636 if (!CheckIntraAnnotationsDirectoryItem()) {
1637 return false;
1638 }
1639 break;
1640 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00001641 case DexFile::kDexTypeHeaderItem:
1642 case DexFile::kDexTypeMapList:
1643 break;
1644 }
1645
1646 if (start_ptr == ptr_) {
1647 ErrorStringPrintf("Unknown map item type %x", type);
1648 return false;
jeffhao10037c82012-01-23 15:06:23 -08001649 }
1650
1651 if (IsDataSectionType(type)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001652 if (aligned_offset == 0u) {
1653 ErrorStringPrintf("Item %d offset is 0", i);
1654 return false;
1655 }
1656 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1657 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001658 }
1659
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001660 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001661 if (UNLIKELY(aligned_offset > size_)) {
1662 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001663 return false;
1664 }
1665
1666 offset = aligned_offset;
1667 }
1668
1669 return true;
1670}
1671
Orion Hodson12f4ff42017-01-13 16:43:12 +00001672bool DexFileVerifier::CheckIntraIdSection(size_t offset,
1673 uint32_t count,
1674 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -08001675 uint32_t expected_offset;
1676 uint32_t expected_size;
1677
1678 // Get the expected offset and size from the header.
1679 switch (type) {
1680 case DexFile::kDexTypeStringIdItem:
1681 expected_offset = header_->string_ids_off_;
1682 expected_size = header_->string_ids_size_;
1683 break;
1684 case DexFile::kDexTypeTypeIdItem:
1685 expected_offset = header_->type_ids_off_;
1686 expected_size = header_->type_ids_size_;
1687 break;
1688 case DexFile::kDexTypeProtoIdItem:
1689 expected_offset = header_->proto_ids_off_;
1690 expected_size = header_->proto_ids_size_;
1691 break;
1692 case DexFile::kDexTypeFieldIdItem:
1693 expected_offset = header_->field_ids_off_;
1694 expected_size = header_->field_ids_size_;
1695 break;
1696 case DexFile::kDexTypeMethodIdItem:
1697 expected_offset = header_->method_ids_off_;
1698 expected_size = header_->method_ids_size_;
1699 break;
1700 case DexFile::kDexTypeClassDefItem:
1701 expected_offset = header_->class_defs_off_;
1702 expected_size = header_->class_defs_size_;
1703 break;
1704 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001705 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001706 return false;
1707 }
1708
1709 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001710 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001711 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001712 return false;
1713 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001714 if (UNLIKELY(count != expected_size)) {
1715 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001716 return false;
1717 }
1718
1719 return CheckIntraSectionIterate(offset, count, type);
1720}
1721
Orion Hodson12f4ff42017-01-13 16:43:12 +00001722bool DexFileVerifier::CheckIntraDataSection(size_t offset,
1723 uint32_t count,
1724 DexFile::MapItemType type) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001725 size_t data_start = header_->data_off_;
1726 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001727
1728 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001729 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001730 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001731 return false;
1732 }
1733
1734 if (!CheckIntraSectionIterate(offset, count, type)) {
1735 return false;
1736 }
1737
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001738 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001739 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001740 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001741 return false;
1742 }
1743
1744 return true;
1745}
1746
1747bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001748 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001749 const DexFile::MapItem* item = map->list_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001750 size_t offset = 0;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001751 uint32_t count = map->size_;
Ian Rogers30fab402012-01-23 15:43:46 -08001752 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001753
1754 // Check the items listed in the map.
1755 while (count--) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00001756 const size_t current_offset = offset;
jeffhao10037c82012-01-23 15:06:23 -08001757 uint32_t section_offset = item->offset_;
1758 uint32_t section_count = item->size_;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001759 DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
jeffhao10037c82012-01-23 15:06:23 -08001760
1761 // Check for padding and overlap between items.
1762 if (!CheckPadding(offset, section_offset)) {
1763 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001764 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001765 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001766 return false;
1767 }
1768
1769 // Check each item based on its type.
1770 switch (type) {
1771 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001772 if (UNLIKELY(section_count != 1)) {
1773 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001774 return false;
1775 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001776 if (UNLIKELY(section_offset != 0)) {
1777 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001778 return false;
1779 }
Ian Rogers30fab402012-01-23 15:43:46 -08001780 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001781 offset = header_->header_size_;
1782 break;
1783 case DexFile::kDexTypeStringIdItem:
1784 case DexFile::kDexTypeTypeIdItem:
1785 case DexFile::kDexTypeProtoIdItem:
1786 case DexFile::kDexTypeFieldIdItem:
1787 case DexFile::kDexTypeMethodIdItem:
1788 case DexFile::kDexTypeClassDefItem:
1789 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1790 return false;
1791 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001792 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001793 break;
1794 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001795 if (UNLIKELY(section_count != 1)) {
1796 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001797 return false;
1798 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001799 if (UNLIKELY(section_offset != header_->map_off_)) {
1800 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1801 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001802 return false;
1803 }
1804 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1805 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1806 break;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001807 case DexFile::kDexTypeMethodHandleItem:
1808 case DexFile::kDexTypeCallSiteIdItem:
1809 CheckIntraSectionIterate(section_offset, section_count, type);
1810 offset = ptr_ - begin_;
1811 break;
jeffhao10037c82012-01-23 15:06:23 -08001812 case DexFile::kDexTypeTypeList:
1813 case DexFile::kDexTypeAnnotationSetRefList:
1814 case DexFile::kDexTypeAnnotationSetItem:
1815 case DexFile::kDexTypeClassDataItem:
1816 case DexFile::kDexTypeCodeItem:
1817 case DexFile::kDexTypeStringDataItem:
1818 case DexFile::kDexTypeDebugInfoItem:
1819 case DexFile::kDexTypeAnnotationItem:
1820 case DexFile::kDexTypeEncodedArrayItem:
1821 case DexFile::kDexTypeAnnotationsDirectoryItem:
1822 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1823 return false;
1824 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001825 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001826 break;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001827 }
1828
1829 if (offset == current_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001830 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001831 return false;
1832 }
1833
1834 item++;
1835 }
1836
1837 return true;
1838}
1839
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001840bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001841 DCHECK_NE(offset, 0u);
1842 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001843 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001844 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001845 return false;
1846 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001847 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001848 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001849 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001850 return false;
1851 }
1852 return true;
1853}
1854
Andreas Gampea5b09a62016-11-17 15:21:22 -08001855dex::TypeIndex DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001856 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001857 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001858
1859 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001860 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001861 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001862 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001863 }
1864
1865 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001866 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001867 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001868 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001869 }
1870
Andreas Gampea5b09a62016-11-17 15:21:22 -08001871 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001872}
1873
Andreas Gampea5b09a62016-11-17 15:21:22 -08001874dex::TypeIndex DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr,
1875 bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001876 const DexFile::AnnotationsDirectoryItem* item =
1877 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001878 *success = true;
1879
jeffhao10037c82012-01-23 15:06:23 -08001880 if (item->fields_size_ != 0) {
1881 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001882 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001883 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001884 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001885 }
1886
1887 if (item->methods_size_ != 0) {
1888 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001889 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001890 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001891 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001892 }
1893
1894 if (item->parameters_size_ != 0) {
1895 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001896 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001897 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001898 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001899 }
1900
Andreas Gampea5b09a62016-11-17 15:21:22 -08001901 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001902}
1903
1904bool DexFileVerifier::CheckInterStringIdItem() {
1905 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1906
1907 // Check the map to make sure it has the right offset->type.
1908 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1909 return false;
1910 }
1911
1912 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001913 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001914 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1915 const char* prev_str = dex_file_->GetStringData(*prev_item);
1916 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001917 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1918 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001919 return false;
1920 }
1921 }
1922
1923 ptr_ += sizeof(DexFile::StringId);
1924 return true;
1925}
1926
1927bool DexFileVerifier::CheckInterTypeIdItem() {
1928 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001929
1930 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001931
1932 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001933 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1934 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001935 return false;
1936 }
1937
1938 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001939 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001940 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001941 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1942 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001943 prev_item->descriptor_idx_.index_,
1944 item->descriptor_idx_.index_);
jeffhao10037c82012-01-23 15:06:23 -08001945 return false;
1946 }
1947 }
1948
1949 ptr_ += sizeof(DexFile::TypeId);
1950 return true;
1951}
1952
1953bool DexFileVerifier::CheckInterProtoIdItem() {
1954 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001955
1956 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1957
jeffhao10037c82012-01-23 15:06:23 -08001958 if (item->parameters_off_ != 0 &&
1959 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1960 return false;
1961 }
1962
David Sehr28e74ed2016-11-21 12:52:12 -08001963 // Check that return type is representable as a uint16_t;
1964 if (UNLIKELY(!IsValidOrNoTypeId(item->return_type_idx_.index_, item->pad_))) {
1965 ErrorStringPrintf("proto with return type idx outside uint16_t range '%x:%x'",
1966 item->pad_, item->return_type_idx_.index_);
1967 return false;
1968 }
jeffhao10037c82012-01-23 15:06:23 -08001969 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001970 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1971 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001972 return false;
1973 }
1974 shorty++;
1975
1976 DexFileParameterIterator it(*dex_file_, *item);
1977 while (it.HasNext() && *shorty != '\0') {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001978 if (!CheckIndex(it.GetTypeIdx().index_,
1979 dex_file_->NumTypeIds(),
Andreas Gampebb836e12014-06-13 15:31:40 -07001980 "inter_proto_id_item shorty type_idx")) {
1981 return false;
1982 }
jeffhao10037c82012-01-23 15:06:23 -08001983 const char* descriptor = it.GetDescriptor();
1984 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1985 return false;
1986 }
1987 it.Next();
1988 shorty++;
1989 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001990 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1991 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001992 return false;
1993 }
1994
1995 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001996 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001997 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001998 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1999 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08002000 return false;
2001 } else if (prev->return_type_idx_ == item->return_type_idx_) {
2002 DexFileParameterIterator curr_it(*dex_file_, *item);
2003 DexFileParameterIterator prev_it(*dex_file_, *prev);
2004
2005 while (curr_it.HasNext() && prev_it.HasNext()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002006 dex::TypeIndex prev_idx = prev_it.GetTypeIdx();
2007 dex::TypeIndex curr_idx = curr_it.GetTypeIdx();
2008 DCHECK_NE(prev_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
2009 DCHECK_NE(curr_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
jeffhao10037c82012-01-23 15:06:23 -08002010
2011 if (prev_idx < curr_idx) {
2012 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002013 } else if (UNLIKELY(prev_idx > curr_idx)) {
2014 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08002015 return false;
2016 }
2017
2018 prev_it.Next();
2019 curr_it.Next();
2020 }
Vladimir Marko0ca8add2016-05-03 17:17:50 +01002021 if (!curr_it.HasNext()) {
2022 // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
2023 // a ProtoId with a longer one. Both cases are forbidden by the specification.
2024 ErrorStringPrintf("Out-of-order proto_id arguments");
2025 return false;
2026 }
jeffhao10037c82012-01-23 15:06:23 -08002027 }
2028 }
2029
2030 ptr_ += sizeof(DexFile::ProtoId);
2031 return true;
2032}
2033
2034bool DexFileVerifier::CheckInterFieldIdItem() {
2035 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
2036
2037 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07002038 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
2039 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
2040 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002041 return false;
2042 }
2043
2044 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07002045 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
2046 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
2047 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002048 return false;
2049 }
2050
2051 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07002052 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002053 if (UNLIKELY(!IsValidMemberName(descriptor))) {
2054 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002055 return false;
2056 }
2057
2058 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002059 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002060 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002061 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
2062 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002063 return false;
2064 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002065 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
2066 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002067 return false;
2068 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002069 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
2070 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002071 return false;
2072 }
2073 }
2074 }
2075 }
2076
2077 ptr_ += sizeof(DexFile::FieldId);
2078 return true;
2079}
2080
2081bool DexFileVerifier::CheckInterMethodIdItem() {
2082 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
2083
2084 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07002085 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
2086 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
2087 class_descriptor[0] != '['))) {
2088 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002089 return false;
2090 }
2091
2092 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07002093 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002094 if (UNLIKELY(!IsValidMemberName(descriptor))) {
2095 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002096 return false;
2097 }
2098
Andreas Gampedf10b322014-06-11 21:46:05 -07002099 // Check that the proto id is valid.
2100 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
2101 "inter_method_id_item proto_idx"))) {
2102 return false;
2103 }
2104
jeffhao10037c82012-01-23 15:06:23 -08002105 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002106 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002107 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002108 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
2109 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002110 return false;
2111 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002112 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
2113 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002114 return false;
2115 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002116 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
2117 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002118 return false;
2119 }
2120 }
2121 }
2122 }
2123
2124 ptr_ += sizeof(DexFile::MethodId);
2125 return true;
2126}
2127
2128bool DexFileVerifier::CheckInterClassDefItem() {
2129 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08002130
David Sehr28e74ed2016-11-21 12:52:12 -08002131 // Check that class_idx_ is representable as a uint16_t;
2132 if (UNLIKELY(!IsValidTypeId(item->class_idx_.index_, item->pad1_))) {
2133 ErrorStringPrintf("class with type idx outside uint16_t range '%x:%x'", item->pad1_,
2134 item->class_idx_.index_);
2135 return false;
2136 }
2137 // Check that superclass_idx_ is representable as a uint16_t;
2138 if (UNLIKELY(!IsValidOrNoTypeId(item->superclass_idx_.index_, item->pad2_))) {
2139 ErrorStringPrintf("class with superclass type idx outside uint16_t range '%x:%x'", item->pad2_,
2140 item->superclass_idx_.index_);
2141 return false;
2142 }
Andreas Gampe0ba238d2014-07-29 01:22:07 -07002143 // Check for duplicate class def.
2144 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002145 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_.index_);
Andreas Gampe0ba238d2014-07-29 01:22:07 -07002146 return false;
2147 }
2148 defined_classes_.insert(item->class_idx_);
2149
Andreas Gampee09269c2014-06-06 18:45:35 -07002150 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
2151 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
2152 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002153 return false;
2154 }
2155
Andreas Gampeacc2bb62014-07-17 19:26:50 -07002156 // Only allow non-runtime modifiers.
2157 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
2158 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
2159 return false;
2160 }
2161
jeffhao10037c82012-01-23 15:06:23 -08002162 if (item->interfaces_off_ != 0 &&
2163 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
2164 return false;
2165 }
2166 if (item->annotations_off_ != 0 &&
2167 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
2168 return false;
2169 }
2170 if (item->class_data_off_ != 0 &&
2171 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
2172 return false;
2173 }
2174 if (item->static_values_off_ != 0 &&
2175 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
2176 return false;
2177 }
2178
Andreas Gampea5b09a62016-11-17 15:21:22 -08002179 if (item->superclass_idx_.IsValid()) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002180 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2181 // Check that a class does not inherit from itself directly (by having
2182 // the same type idx as its super class).
2183 if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002184 ErrorStringPrintf("Class with same type idx as its superclass: '%d'",
2185 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002186 return false;
2187 }
2188
2189 // Check that a class is defined after its super class (if the
2190 // latter is defined in the same Dex file).
2191 const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
2192 if (superclass_def != nullptr) {
2193 // The superclass is defined in this Dex file.
2194 if (superclass_def > item) {
2195 // ClassDef item for super class appearing after the class' ClassDef item.
2196 ErrorStringPrintf("Invalid class definition ordering:"
2197 " class with type idx: '%d' defined before"
2198 " superclass with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002199 item->class_idx_.index_,
2200 item->superclass_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002201 return false;
2202 }
2203 }
2204 }
2205
Andreas Gampee09269c2014-06-06 18:45:35 -07002206 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
2207 "inter_class_def_item superclass_idx")
2208 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
2209 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002210 return false;
2211 }
2212 }
2213
Roland Levillain621b5ea2016-05-18 11:41:33 +01002214 // Check interfaces.
jeffhao10037c82012-01-23 15:06:23 -08002215 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002216 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002217 uint32_t size = interfaces->Size();
jeffhao10037c82012-01-23 15:06:23 -08002218 for (uint32_t i = 0; i < size; i++) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002219 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2220 // Check that a class does not implement itself directly (by having the
2221 // same type idx as one of its immediate implemented interfaces).
2222 if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2223 ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002224 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002225 return false;
2226 }
2227
2228 // Check that a class is defined after the interfaces it implements
2229 // (if they are defined in the same Dex file).
2230 const DexFile::ClassDef* interface_def =
2231 dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2232 if (interface_def != nullptr) {
2233 // The interface is defined in this Dex file.
2234 if (interface_def > item) {
2235 // ClassDef item for interface appearing after the class' ClassDef item.
2236 ErrorStringPrintf("Invalid class definition ordering:"
2237 " class with type idx: '%d' defined before"
2238 " implemented interface with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002239 item->class_idx_.index_,
2240 interfaces->GetTypeItem(i).type_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002241 return false;
2242 }
2243 }
2244 }
2245
2246 // Ensure that the interface refers to a class (not an array nor a primitive type).
Andreas Gampee09269c2014-06-06 18:45:35 -07002247 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2248 "inter_class_def_item interface type_idx")
2249 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2250 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002251 return false;
2252 }
2253 }
2254
2255 /*
2256 * Ensure that there are no duplicates. This is an O(N^2) test, but in
2257 * practice the number of interfaces implemented by any given class is low.
2258 */
2259 for (uint32_t i = 1; i < size; i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002260 dex::TypeIndex idx1 = interfaces->GetTypeItem(i).type_idx_;
jeffhao10037c82012-01-23 15:06:23 -08002261 for (uint32_t j =0; j < i; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002262 dex::TypeIndex idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002263 if (UNLIKELY(idx1 == idx2)) {
2264 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08002265 return false;
2266 }
2267 }
2268 }
2269 }
2270
2271 // Check that references in class_data_item are to the right class.
2272 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07002273 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002274 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002275 dex::TypeIndex data_definer = FindFirstClassDataDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002276 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002277 return false;
2278 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08002279 if (UNLIKELY((data_definer != item->class_idx_) &&
2280 (data_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002281 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08002282 return false;
2283 }
2284 }
2285
2286 // Check that references in annotations_directory_item are to right class.
2287 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002288 // annotations_off_ is supposed to be aligned by 4.
2289 if (!IsAlignedParam(item->annotations_off_, 4)) {
2290 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2291 return false;
2292 }
Ian Rogers13735952014-10-08 12:43:28 -07002293 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002294 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002295 dex::TypeIndex annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002296 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002297 return false;
2298 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002299 if (UNLIKELY((annotations_definer != item->class_idx_) &&
Andreas Gampea5b09a62016-11-17 15:21:22 -08002300 (annotations_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002301 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002302 return false;
2303 }
2304 }
2305
2306 ptr_ += sizeof(DexFile::ClassDef);
2307 return true;
2308}
2309
Orion Hodson12f4ff42017-01-13 16:43:12 +00002310bool DexFileVerifier::CheckInterCallSiteIdItem() {
2311 const DexFile::CallSiteIdItem* item = reinterpret_cast<const DexFile::CallSiteIdItem*>(ptr_);
2312
2313 // Check call site referenced by item is in encoded array section.
2314 if (!CheckOffsetToTypeMap(item->data_off_, DexFile::kDexTypeEncodedArrayItem)) {
2315 ErrorStringPrintf("Invalid offset in CallSideIdItem");
2316 return false;
2317 }
2318
2319 CallSiteArrayValueIterator it(*dex_file_, *item);
2320
2321 // Check Method Handle
2322 if (!it.HasNext() || it.GetValueType() != EncodedArrayValueIterator::ValueType::kMethodHandle) {
2323 ErrorStringPrintf("CallSiteArray missing method handle");
2324 return false;
2325 }
2326
2327 uint32_t handle_index = static_cast<uint32_t>(it.GetJavaValue().i);
2328 if (handle_index >= dex_file_->NumMethodHandles()) {
2329 ErrorStringPrintf("CallSite has bad method handle id: %x", handle_index);
2330 return false;
2331 }
2332
2333 // Check target method name.
2334 it.Next();
2335 if (!it.HasNext() ||
2336 it.GetValueType() != EncodedArrayValueIterator::ValueType::kString) {
2337 ErrorStringPrintf("CallSiteArray missing target method name");
2338 return false;
2339 }
2340
2341 uint32_t name_index = static_cast<uint32_t>(it.GetJavaValue().i);
2342 if (name_index >= dex_file_->NumStringIds()) {
2343 ErrorStringPrintf("CallSite has bad method name id: %x", name_index);
2344 return false;
2345 }
2346
2347 // Check method type.
2348 it.Next();
2349 if (!it.HasNext() ||
2350 it.GetValueType() != EncodedArrayValueIterator::ValueType::kMethodType) {
2351 ErrorStringPrintf("CallSiteArray missing method type");
2352 return false;
2353 }
2354
2355 uint32_t proto_index = static_cast<uint32_t>(it.GetJavaValue().i);
2356 if (proto_index >= dex_file_->NumProtoIds()) {
2357 ErrorStringPrintf("CallSite has bad method type: %x", proto_index);
2358 return false;
2359 }
2360
2361 ptr_ += sizeof(DexFile::CallSiteIdItem);
2362 return true;
2363}
2364
2365bool DexFileVerifier::CheckInterMethodHandleItem() {
2366 const DexFile::MethodHandleItem* item = reinterpret_cast<const DexFile::MethodHandleItem*>(ptr_);
2367
2368 DexFile::MethodHandleType method_handle_type =
2369 static_cast<DexFile::MethodHandleType>(item->method_handle_type_);
2370 if (method_handle_type > DexFile::MethodHandleType::kLast) {
2371 ErrorStringPrintf("Bad method handle type %x", item->method_handle_type_);
2372 return false;
2373 }
2374
2375 uint32_t index = item->field_or_method_idx_;
2376 switch (method_handle_type) {
Orion Hodsonc069a302017-01-18 09:23:12 +00002377 case DexFile::MethodHandleType::kStaticPut:
2378 case DexFile::MethodHandleType::kStaticGet:
2379 case DexFile::MethodHandleType::kInstancePut:
2380 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson12f4ff42017-01-13 16:43:12 +00002381 LOAD_FIELD(field, index, "method_handle_item field_idx", return false);
2382 break;
2383 }
2384 case DexFile::MethodHandleType::kInvokeStatic:
2385 case DexFile::MethodHandleType::kInvokeInstance:
2386 case DexFile::MethodHandleType::kInvokeConstructor: {
2387 LOAD_METHOD(method, index, "method_handle_item method_idx", return false);
2388 break;
2389 }
2390 }
2391
2392 ptr_ += sizeof(DexFile::MethodHandleItem);
2393 return true;
2394}
2395
jeffhao10037c82012-01-23 15:06:23 -08002396bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2397 const DexFile::AnnotationSetRefList* list =
2398 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2399 const DexFile::AnnotationSetRefItem* item = list->list_;
2400 uint32_t count = list->size_;
2401
2402 while (count--) {
2403 if (item->annotations_off_ != 0 &&
2404 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2405 return false;
2406 }
2407 item++;
2408 }
2409
Ian Rogers13735952014-10-08 12:43:28 -07002410 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002411 return true;
2412}
2413
2414bool DexFileVerifier::CheckInterAnnotationSetItem() {
2415 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2416 const uint32_t* offsets = set->entries_;
2417 uint32_t count = set->size_;
2418 uint32_t last_idx = 0;
2419
2420 for (uint32_t i = 0; i < count; i++) {
2421 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2422 return false;
2423 }
2424
2425 // Get the annotation from the offset and the type index for the annotation.
2426 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002427 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002428 const uint8_t* data = annotation->annotation_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002429 DECODE_UNSIGNED_CHECKED_FROM(data, idx);
jeffhao10037c82012-01-23 15:06:23 -08002430
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002431 if (UNLIKELY(last_idx >= idx && i != 0)) {
2432 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002433 return false;
2434 }
2435
2436 last_idx = idx;
2437 offsets++;
2438 }
2439
Ian Rogers13735952014-10-08 12:43:28 -07002440 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002441 return true;
2442}
2443
2444bool DexFileVerifier::CheckInterClassDataItem() {
2445 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002446 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002447 dex::TypeIndex defining_class = FindFirstClassDataDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002448 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002449 return false;
2450 }
jeffhao10037c82012-01-23 15:06:23 -08002451
2452 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002453 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002454 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002455 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002456 return false;
2457 }
2458 }
2459 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2460 uint32_t code_off = it.GetMethodCodeItemOffset();
2461 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2462 return false;
2463 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002464 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002465 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002466 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002467 return false;
2468 }
2469 }
2470
2471 ptr_ = it.EndDataPointer();
2472 return true;
2473}
2474
2475bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2476 const DexFile::AnnotationsDirectoryItem* item =
2477 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002478 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002479 dex::TypeIndex defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002480 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002481 return false;
2482 }
jeffhao10037c82012-01-23 15:06:23 -08002483
2484 if (item->class_annotations_off_ != 0 &&
2485 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2486 return false;
2487 }
2488
2489 // Field annotations follow immediately after the annotations directory.
2490 const DexFile::FieldAnnotationsItem* field_item =
2491 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2492 uint32_t field_count = item->fields_size_;
2493 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002494 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2495 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002496 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002497 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002498 return false;
2499 }
2500 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2501 return false;
2502 }
2503 field_item++;
2504 }
2505
2506 // Method annotations follow immediately after field annotations.
2507 const DexFile::MethodAnnotationsItem* method_item =
2508 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2509 uint32_t method_count = item->methods_size_;
2510 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002511 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002512 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002513 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002514 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002515 return false;
2516 }
2517 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2518 return false;
2519 }
2520 method_item++;
2521 }
2522
2523 // Parameter annotations follow immediately after method annotations.
2524 const DexFile::ParameterAnnotationsItem* parameter_item =
2525 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2526 uint32_t parameter_count = item->parameters_size_;
2527 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002528 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002529 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002530 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002531 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002532 return false;
2533 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002534 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2535 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002536 return false;
2537 }
2538 parameter_item++;
2539 }
2540
Ian Rogers13735952014-10-08 12:43:28 -07002541 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002542 return true;
2543}
2544
Orion Hodson12f4ff42017-01-13 16:43:12 +00002545bool DexFileVerifier::CheckInterSectionIterate(size_t offset,
2546 uint32_t count,
2547 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -08002548 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002549 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002550 switch (type) {
2551 case DexFile::kDexTypeClassDataItem:
2552 alignment_mask = sizeof(uint8_t) - 1;
2553 break;
2554 default:
2555 alignment_mask = sizeof(uint32_t) - 1;
2556 break;
2557 }
2558
2559 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002560 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002561 for (uint32_t i = 0; i < count; i++) {
2562 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002563 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002564 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002565
Orion Hodson12f4ff42017-01-13 16:43:12 +00002566 if (MapTypeToBitMask(type) == 0) {
2567 ErrorStringPrintf("Unknown map item type %x", type);
2568 return false;
2569 }
2570
jeffhao10037c82012-01-23 15:06:23 -08002571 // Check depending on the section type.
2572 switch (type) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00002573 case DexFile::kDexTypeHeaderItem:
2574 case DexFile::kDexTypeMapList:
2575 case DexFile::kDexTypeTypeList:
2576 case DexFile::kDexTypeCodeItem:
2577 case DexFile::kDexTypeStringDataItem:
2578 case DexFile::kDexTypeDebugInfoItem:
2579 case DexFile::kDexTypeAnnotationItem:
2580 case DexFile::kDexTypeEncodedArrayItem:
2581 break;
jeffhao10037c82012-01-23 15:06:23 -08002582 case DexFile::kDexTypeStringIdItem: {
2583 if (!CheckInterStringIdItem()) {
2584 return false;
2585 }
2586 break;
2587 }
2588 case DexFile::kDexTypeTypeIdItem: {
2589 if (!CheckInterTypeIdItem()) {
2590 return false;
2591 }
2592 break;
2593 }
2594 case DexFile::kDexTypeProtoIdItem: {
2595 if (!CheckInterProtoIdItem()) {
2596 return false;
2597 }
2598 break;
2599 }
2600 case DexFile::kDexTypeFieldIdItem: {
2601 if (!CheckInterFieldIdItem()) {
2602 return false;
2603 }
2604 break;
2605 }
2606 case DexFile::kDexTypeMethodIdItem: {
2607 if (!CheckInterMethodIdItem()) {
2608 return false;
2609 }
2610 break;
2611 }
2612 case DexFile::kDexTypeClassDefItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002613 // There shouldn't be more class definitions than type ids allow.
2614 // This check should be redundant, since there are checks that the
2615 // class_idx_ is within range and that there is only one definition
2616 // for a given type id.
2617 if (i > kTypeIdLimit) {
2618 ErrorStringPrintf("Too many class definition items");
2619 return false;
2620 }
jeffhao10037c82012-01-23 15:06:23 -08002621 if (!CheckInterClassDefItem()) {
2622 return false;
2623 }
2624 break;
2625 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00002626 case DexFile::kDexTypeCallSiteIdItem: {
2627 if (!CheckInterCallSiteIdItem()) {
2628 return false;
2629 }
2630 break;
2631 }
2632 case DexFile::kDexTypeMethodHandleItem: {
2633 if (!CheckInterMethodHandleItem()) {
2634 return false;
2635 }
2636 break;
2637 }
jeffhao10037c82012-01-23 15:06:23 -08002638 case DexFile::kDexTypeAnnotationSetRefList: {
2639 if (!CheckInterAnnotationSetRefList()) {
2640 return false;
2641 }
2642 break;
2643 }
2644 case DexFile::kDexTypeAnnotationSetItem: {
2645 if (!CheckInterAnnotationSetItem()) {
2646 return false;
2647 }
2648 break;
2649 }
2650 case DexFile::kDexTypeClassDataItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002651 // There shouldn't be more class data than type ids allow.
2652 // This check should be redundant, since there are checks that the
2653 // class_idx_ is within range and that there is only one definition
2654 // for a given type id.
2655 if (i > kTypeIdLimit) {
2656 ErrorStringPrintf("Too many class data items");
2657 return false;
2658 }
jeffhao10037c82012-01-23 15:06:23 -08002659 if (!CheckInterClassDataItem()) {
2660 return false;
2661 }
2662 break;
2663 }
2664 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2665 if (!CheckInterAnnotationsDirectoryItem()) {
2666 return false;
2667 }
2668 break;
2669 }
jeffhao10037c82012-01-23 15:06:23 -08002670 }
2671
2672 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002673 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002674 }
2675
2676 return true;
2677}
2678
2679bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002680 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002681 const DexFile::MapItem* item = map->list_;
2682 uint32_t count = map->size_;
2683
2684 // Cross check the items listed in the map.
2685 while (count--) {
2686 uint32_t section_offset = item->offset_;
2687 uint32_t section_count = item->size_;
Orion Hodson12f4ff42017-01-13 16:43:12 +00002688 DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
2689 bool found = false;
jeffhao10037c82012-01-23 15:06:23 -08002690
2691 switch (type) {
2692 case DexFile::kDexTypeHeaderItem:
2693 case DexFile::kDexTypeMapList:
2694 case DexFile::kDexTypeTypeList:
2695 case DexFile::kDexTypeCodeItem:
2696 case DexFile::kDexTypeStringDataItem:
2697 case DexFile::kDexTypeDebugInfoItem:
2698 case DexFile::kDexTypeAnnotationItem:
2699 case DexFile::kDexTypeEncodedArrayItem:
Orion Hodson12f4ff42017-01-13 16:43:12 +00002700 found = true;
jeffhao10037c82012-01-23 15:06:23 -08002701 break;
2702 case DexFile::kDexTypeStringIdItem:
2703 case DexFile::kDexTypeTypeIdItem:
2704 case DexFile::kDexTypeProtoIdItem:
2705 case DexFile::kDexTypeFieldIdItem:
2706 case DexFile::kDexTypeMethodIdItem:
2707 case DexFile::kDexTypeClassDefItem:
Orion Hodson12f4ff42017-01-13 16:43:12 +00002708 case DexFile::kDexTypeCallSiteIdItem:
2709 case DexFile::kDexTypeMethodHandleItem:
jeffhao10037c82012-01-23 15:06:23 -08002710 case DexFile::kDexTypeAnnotationSetRefList:
2711 case DexFile::kDexTypeAnnotationSetItem:
2712 case DexFile::kDexTypeClassDataItem:
2713 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2714 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2715 return false;
2716 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00002717 found = true;
jeffhao10037c82012-01-23 15:06:23 -08002718 break;
2719 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00002720 }
2721
2722 if (!found) {
2723 ErrorStringPrintf("Unknown map item type %x", item->type_);
2724 return false;
jeffhao10037c82012-01-23 15:06:23 -08002725 }
2726
2727 item++;
2728 }
2729
2730 return true;
2731}
2732
2733bool DexFileVerifier::Verify() {
2734 // Check the header.
2735 if (!CheckHeader()) {
2736 return false;
2737 }
2738
2739 // Check the map section.
2740 if (!CheckMap()) {
2741 return false;
2742 }
2743
2744 // Check structure within remaining sections.
2745 if (!CheckIntraSection()) {
2746 return false;
2747 }
2748
2749 // Check references from one section to another.
2750 if (!CheckInterSection()) {
2751 return false;
2752 }
2753
2754 return true;
2755}
2756
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002757void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2758 va_list ap;
2759 va_start(ap, fmt);
2760 DCHECK(failure_reason_.empty()) << failure_reason_;
2761 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2762 StringAppendV(&failure_reason_, fmt, ap);
2763 va_end(ap);
2764}
2765
Andreas Gampee6215c02015-08-31 18:54:38 -07002766// Fields and methods may have only one of public/protected/private.
2767static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2768 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2769 (((flags & kAccProtected) == 0) ? 0 : 1) +
2770 (((flags & kAccPrivate) == 0) ? 0 : 1);
2771 return count <= 1;
2772}
2773
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002774// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2775// functionality, as we're still verifying the dex file. begin and header correspond to the
2776// underscored variants in the DexFileVerifier.
2777
2778static std::string GetStringOrError(const uint8_t* const begin,
2779 const DexFile::Header* const header,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002780 dex::StringIndex string_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002781 // The `string_idx` is not guaranteed to be valid yet.
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002782 if (header->string_ids_size_ <= string_idx.index_) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002783 return "(error)";
2784 }
2785
2786 const DexFile::StringId* string_id =
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002787 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_)
2788 + string_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002789
2790 // Assume that the data is OK at this point. String data has been checked at this point.
2791
2792 const uint8_t* ptr = begin + string_id->string_data_off_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002793 uint32_t dummy;
2794 if (!DecodeUnsignedLeb128Checked(&ptr, begin + header->file_size_, &dummy)) {
2795 return "(error)";
2796 }
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002797 return reinterpret_cast<const char*>(ptr);
2798}
2799
2800static std::string GetClassOrError(const uint8_t* const begin,
2801 const DexFile::Header* const header,
Andreas Gampea5b09a62016-11-17 15:21:22 -08002802 dex::TypeIndex class_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002803 // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2804 // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2805 // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2806 // a valid defining class.
Andreas Gampea5b09a62016-11-17 15:21:22 -08002807 CHECK_LT(class_idx.index_, header->type_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002808
2809 const DexFile::TypeId* type_id =
Andreas Gampea5b09a62016-11-17 15:21:22 -08002810 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002811
2812 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2813
2814 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2815}
2816
2817static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2818 const DexFile::Header* const header,
2819 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002820 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2821 CHECK_LT(idx, header->field_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002822
2823 const DexFile::FieldId* field_id =
2824 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2825
2826 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2827
2828 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2829 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2830
2831 return class_name + "." + field_name;
2832}
2833
2834static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2835 const DexFile::Header* const header,
2836 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002837 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2838 CHECK_LT(idx, header->method_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002839
2840 const DexFile::MethodId* method_id =
2841 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2842
2843 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2844
2845 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2846 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2847
2848 return class_name + "." + method_name;
2849}
2850
2851bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2852 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002853 uint32_t class_access_flags,
2854 std::string* error_msg) {
2855 // Generally sort out >16-bit flags.
2856 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002857 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2858 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2859 field_access_flags,
2860 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002861 return false;
2862 }
2863
2864 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2865 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2866 kAccPrivate |
2867 kAccProtected |
2868 kAccStatic |
2869 kAccFinal |
2870 kAccVolatile |
2871 kAccTransient |
2872 kAccSynthetic |
2873 kAccEnum;
2874
2875 // Fields may have only one of public/protected/final.
2876 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002877 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2878 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2879 field_access_flags,
2880 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002881 return false;
2882 }
2883
2884 // Interfaces have a pretty restricted list.
2885 if ((class_access_flags & kAccInterface) != 0) {
2886 // Interface fields must be public final static.
2887 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2888 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002889 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2890 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2891 field_access_flags,
2892 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002893 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002894 return false;
2895 } else {
2896 // Allow in older versions, but warn.
2897 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2898 << *error_msg;
2899 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002900 }
2901 // Interface fields may be synthetic, but may not have other flags.
2902 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2903 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002904 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
2905 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2906 field_access_flags,
2907 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002908 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002909 return false;
2910 } else {
2911 // Allow in older versions, but warn.
2912 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2913 << *error_msg;
2914 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002915 }
2916 return true;
2917 }
2918
2919 // Volatile fields may not be final.
2920 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2921 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002922 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
2923 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002924 return false;
2925 }
2926
2927 return true;
2928}
2929
Andreas Gampee6215c02015-08-31 18:54:38 -07002930bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2931 uint32_t method_access_flags,
2932 uint32_t class_access_flags,
Orion Hodson6c4921b2016-09-21 15:41:06 +01002933 uint32_t constructor_flags_by_name,
Andreas Gampee6215c02015-08-31 18:54:38 -07002934 bool has_code,
2935 bool expect_direct,
2936 std::string* error_msg) {
2937 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2938 constexpr uint32_t kAllMethodFlags =
2939 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2940 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002941 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
2942 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2943 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002944 return false;
2945 }
2946
2947 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2948 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2949 kAccPrivate |
2950 kAccProtected |
2951 kAccStatic |
2952 kAccFinal |
2953 kAccSynthetic |
2954 kAccSynchronized |
2955 kAccBridge |
2956 kAccVarargs |
2957 kAccNative |
2958 kAccAbstract |
2959 kAccStrict;
2960
2961 // Methods may have only one of public/protected/final.
2962 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002963 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
2964 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002965 method_access_flags);
2966 return false;
2967 }
2968
Orion Hodson6c4921b2016-09-21 15:41:06 +01002969 constexpr uint32_t kConstructorFlags = kAccStatic | kAccConstructor;
2970 const bool is_constructor_by_name = (constructor_flags_by_name & kConstructorFlags) != 0;
2971 const bool is_clinit_by_name = constructor_flags_by_name == kConstructorFlags;
Andreas Gampee6215c02015-08-31 18:54:38 -07002972
2973 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2974 // the reverse for backwards compatibility reasons.
Orion Hodson6c4921b2016-09-21 15:41:06 +01002975 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002976 *error_msg =
2977 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
Orion Hodson6c4921b2016-09-21 15:41:06 +01002978 method_index,
2979 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002980 return false;
2981 }
Orion Hodson6c4921b2016-09-21 15:41:06 +01002982
2983 if (is_constructor_by_name) {
2984 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2985 // instance constructor is called "<init>".
Andreas Gampee6215c02015-08-31 18:54:38 -07002986 bool is_static = (method_access_flags & kAccStatic) != 0;
2987 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002988 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
2989 method_index,
2990 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002991 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2992 return false;
2993 } else {
2994 // Allow in older versions, but warn.
2995 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2996 << *error_msg;
2997 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002998 }
2999 }
Orion Hodson6c4921b2016-09-21 15:41:06 +01003000
Andreas Gampee6215c02015-08-31 18:54:38 -07003001 // Check that static and private methods, as well as constructors, are in the direct methods list,
3002 // and other methods in the virtual methods list.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003003 bool is_direct = ((method_access_flags & (kAccStatic | kAccPrivate)) != 0) ||
3004 is_constructor_by_name;
Andreas Gampee6215c02015-08-31 18:54:38 -07003005 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003006 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07003007 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003008 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07003009 expect_direct);
3010 return false;
3011 }
3012
Andreas Gampee6215c02015-08-31 18:54:38 -07003013 // From here on out it is easier to mask out the bits we're supposed to ignore.
3014 method_access_flags &= kMethodAccessFlags;
3015
Alex Lightd7c10c22016-03-31 10:03:07 -07003016 // Interfaces are special.
3017 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07003018 // Non-static interface methods must be public or private.
3019 uint32_t desired_flags = (kAccPublic | kAccStatic);
3020 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3021 desired_flags |= kAccPrivate;
3022 }
3023 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07003024 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
3025 method_index,
3026 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07003027 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07003028 return false;
3029 } else {
3030 // Allow in older versions, but warn.
3031 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3032 << *error_msg;
3033 }
3034 }
3035 }
3036
Andreas Gampee6215c02015-08-31 18:54:38 -07003037 // If there aren't any instructions, make sure that's expected.
3038 if (!has_code) {
3039 // Only native or abstract methods may not have code.
3040 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003041 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07003042 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003043 method_index,
3044 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003045 return false;
3046 }
3047 // Constructors must always have code.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003048 if (is_constructor_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003049 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
3050 method_index,
3051 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07003052 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3053 return false;
3054 } else {
3055 // Allow in older versions, but warn.
3056 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3057 << *error_msg;
3058 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003059 }
3060 if ((method_access_flags & kAccAbstract) != 0) {
3061 // Abstract methods are not allowed to have the following flags.
3062 constexpr uint32_t kForbidden =
3063 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
3064 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003065 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
3066 method_index,
3067 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3068 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07003069 return false;
3070 }
Andreas Gampe97b11352015-12-10 16:23:41 -08003071 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07003072 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003073 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08003074 << " is abstract, but the declaring class is neither abstract nor an "
3075 << "interface in dex file "
3076 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07003077 }
3078 }
3079 // Interfaces are special.
3080 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07003081 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07003082 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003083 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
3084 method_index,
3085 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07003086 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07003087 return false;
3088 } else {
3089 // Allow in older versions, but warn.
3090 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3091 << *error_msg;
3092 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003093 }
3094 // At this point, we know the method is public and abstract. This means that all the checks
3095 // for invalid combinations above applies. In addition, interface methods must not be
3096 // protected. This is caught by the check for only-one-of-public-protected-private.
3097 }
3098 return true;
3099 }
3100
3101 // When there's code, the method must not be native or abstract.
3102 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003103 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
3104 method_index,
3105 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003106 return false;
3107 }
3108
Andreas Gampee6215c02015-08-31 18:54:38 -07003109 // Instance constructors must not be synchronized and a few other flags.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003110 if (constructor_flags_by_name == kAccConstructor) {
Andreas Gampee6215c02015-08-31 18:54:38 -07003111 static constexpr uint32_t kInitAllowed =
3112 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
3113 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003114 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07003115 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003116 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07003117 method_access_flags);
3118 return false;
3119 }
3120 }
3121
3122 return true;
3123}
3124
Orion Hodson6c4921b2016-09-21 15:41:06 +01003125bool DexFileVerifier::CheckConstructorProperties(
3126 uint32_t method_index,
3127 uint32_t constructor_flags) {
3128 DCHECK(constructor_flags == kAccConstructor ||
3129 constructor_flags == (kAccConstructor | kAccStatic));
3130
3131 // Check signature matches expectations.
3132 const DexFile::MethodId* const method_id = CheckLoadMethodId(method_index,
3133 "Bad <init>/<clinit> method id");
3134 if (method_id == nullptr) {
3135 return false;
3136 }
3137
3138 // Check the ProtoId for the corresponding method.
3139 //
3140 // TODO(oth): the error message here is to satisfy the MethodId test
3141 // in the DexFileVerifierTest. The test is checking that the error
3142 // contains this string if the index is out of range.
3143 const DexFile::ProtoId* const proto_id = CheckLoadProtoId(method_id->proto_idx_,
3144 "inter_method_id_item proto_idx");
3145 if (proto_id == nullptr) {
3146 return false;
3147 }
3148
3149 Signature signature = dex_file_->GetMethodSignature(*method_id);
3150 if (constructor_flags == (kAccStatic | kAccConstructor)) {
3151 if (!signature.IsVoid() || signature.GetNumberOfParameters() != 0) {
3152 ErrorStringPrintf("<clinit> must have descriptor ()V");
3153 return false;
3154 }
3155 } else if (!signature.IsVoid()) {
3156 ErrorStringPrintf("Constructor %u(%s) must be void",
3157 method_index,
3158 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3159 return false;
3160 }
3161
3162 return true;
3163}
3164
jeffhao10037c82012-01-23 15:06:23 -08003165} // namespace art