blob: be25803f5920941b5a0689cb223f3bba21baf175 [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
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Narayan Kamath92572be2013-11-28 14:06:24 +000023
Elliott Hughese222ee02012-12-13 14:41:43 -080024#include "base/stringprintf.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070025#include "dex_file-inl.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070026#include "experimental_flags.h"
jeffhao10037c82012-01-23 15:06:23 -080027#include "leb128.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070028#include "safe_map.h"
Ian Rogersa6724902013-09-23 09:23:37 -070029#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "utils.h"
jeffhao10037c82012-01-23 15:06:23 -080031
32namespace art {
33
34static uint32_t MapTypeToBitMask(uint32_t map_type) {
35 switch (map_type) {
36 case DexFile::kDexTypeHeaderItem: return 1 << 0;
37 case DexFile::kDexTypeStringIdItem: return 1 << 1;
38 case DexFile::kDexTypeTypeIdItem: return 1 << 2;
39 case DexFile::kDexTypeProtoIdItem: return 1 << 3;
40 case DexFile::kDexTypeFieldIdItem: return 1 << 4;
41 case DexFile::kDexTypeMethodIdItem: return 1 << 5;
42 case DexFile::kDexTypeClassDefItem: return 1 << 6;
43 case DexFile::kDexTypeMapList: return 1 << 7;
44 case DexFile::kDexTypeTypeList: return 1 << 8;
45 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9;
46 case DexFile::kDexTypeAnnotationSetItem: return 1 << 10;
47 case DexFile::kDexTypeClassDataItem: return 1 << 11;
48 case DexFile::kDexTypeCodeItem: return 1 << 12;
49 case DexFile::kDexTypeStringDataItem: return 1 << 13;
50 case DexFile::kDexTypeDebugInfoItem: return 1 << 14;
51 case DexFile::kDexTypeAnnotationItem: return 1 << 15;
52 case DexFile::kDexTypeEncodedArrayItem: return 1 << 16;
53 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17;
54 }
55 return 0;
56}
57
58static bool IsDataSectionType(uint32_t map_type) {
59 switch (map_type) {
60 case DexFile::kDexTypeHeaderItem:
61 case DexFile::kDexTypeStringIdItem:
62 case DexFile::kDexTypeTypeIdItem:
63 case DexFile::kDexTypeProtoIdItem:
64 case DexFile::kDexTypeFieldIdItem:
65 case DexFile::kDexTypeMethodIdItem:
66 case DexFile::kDexTypeClassDefItem:
67 return false;
68 }
69 return true;
70}
71
Andreas Gampee09269c2014-06-06 18:45:35 -070072const char* DexFileVerifier::CheckLoadStringByIdx(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070073 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070074 return nullptr;
75 }
76 return dex_file_->StringDataByIdx(idx);
77}
78
79const char* DexFileVerifier::CheckLoadStringByTypeIdx(uint32_t type_idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070080 if (UNLIKELY(!CheckIndex(type_idx, dex_file_->NumTypeIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070081 return nullptr;
82 }
83 const DexFile::TypeId& type_id = dex_file_->GetTypeId(type_idx);
84 uint32_t idx = type_id.descriptor_idx_;
85 return CheckLoadStringByIdx(idx, error_string);
86}
87
88const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070089 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070090 return nullptr;
91 }
92 return &dex_file_->GetFieldId(idx);
93}
94
95const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070096 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070097 return nullptr;
98 }
99 return &dex_file_->GetMethodId(idx);
100}
101
102// Helper macro to load string and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700103#define LOAD_STRING(var, idx, error) \
104 const char* (var) = CheckLoadStringByIdx(idx, error); \
105 if (UNLIKELY((var) == nullptr)) { \
106 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700107 }
108
109// Helper macro to load string by type idx and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700110#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
111 const char* (var) = CheckLoadStringByTypeIdx(type_idx, error); \
112 if (UNLIKELY((var) == nullptr)) { \
113 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700114 }
115
116// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700117#define LOAD_METHOD(var, idx, error_string, error_stmt) \
118 const DexFile::MethodId* (var) = CheckLoadMethodId(idx, error_string); \
119 if (UNLIKELY((var) == nullptr)) { \
120 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700121 }
122
123// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700124#define LOAD_FIELD(var, idx, fmt, error_stmt) \
125 const DexFile::FieldId* (var) = CheckLoadFieldId(idx, fmt); \
126 if (UNLIKELY((var) == nullptr)) { \
127 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700128 }
129
Aart Bik37d6a3b2016-06-21 18:30:10 -0700130bool DexFileVerifier::Verify(const DexFile* dex_file,
131 const uint8_t* begin,
132 size_t size,
133 const char* location,
134 bool verify_checksum,
135 std::string* error_msg) {
136 std::unique_ptr<DexFileVerifier> verifier(
137 new DexFileVerifier(dex_file, begin, size, location, verify_checksum));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700138 if (!verifier->Verify()) {
139 *error_msg = verifier->FailureReason();
140 return false;
141 }
142 return true;
143}
144
145bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
146 bool is_return_type) {
jeffhao10037c82012-01-23 15:06:23 -0800147 switch (shorty_char) {
148 case 'V':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700149 if (UNLIKELY(!is_return_type)) {
150 ErrorStringPrintf("Invalid use of void");
jeffhao10037c82012-01-23 15:06:23 -0800151 return false;
152 }
Ian Rogersfc787ec2014-10-09 21:56:44 -0700153 FALLTHROUGH_INTENDED;
jeffhao10037c82012-01-23 15:06:23 -0800154 case 'B':
155 case 'C':
156 case 'D':
157 case 'F':
158 case 'I':
159 case 'J':
160 case 'S':
161 case 'Z':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700162 if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
163 ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
164 shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800165 return false;
166 }
167 break;
168 case 'L':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700169 if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
170 ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800171 return false;
172 }
173 break;
174 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700175 ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
jeffhao10037c82012-01-23 15:06:23 -0800176 return false;
177 }
178 return true;
179}
180
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700181bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700182 const char* label) {
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700183 // Check that size is not 0.
184 CHECK_NE(elem_size, 0U);
185
Ian Rogers13735952014-10-08 12:43:28 -0700186 const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
187 const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700188
189 // Check for overflow.
190 uintptr_t max = 0 - 1;
191 size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
192 size_t max_count = available_bytes_till_end_of_mem / elem_size;
193 if (max_count < count) {
194 ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
195 static_cast<size_t>(range_start - file_start),
196 count, elem_size);
197 return false;
198 }
199
Ian Rogers13735952014-10-08 12:43:28 -0700200 const uint8_t* range_end = range_start + count * elem_size;
201 const uint8_t* file_end = file_start + size_;
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700202 if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
203 // Note: these two tests are enough as we make sure above that there's no overflow.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800204 ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
Ian Rogerse3d55812014-06-11 13:00:44 -0700205 static_cast<size_t>(range_start - file_start),
206 static_cast<size_t>(range_end - file_start));
jeffhao10037c82012-01-23 15:06:23 -0800207 return false;
208 }
209 return true;
210}
211
Ian Rogers13735952014-10-08 12:43:28 -0700212bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700213 // Check that the list is available. The first 4B are the count.
214 if (!CheckListSize(*ptr, 1, 4U, label)) {
215 return false;
216 }
217
218 uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
219 if (count > 0) {
220 if (!CheckListSize(*ptr + 4, count, element_size, label)) {
221 return false;
222 }
223 }
224
225 *ptr += 4 + count * element_size;
226 return true;
227}
228
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700229bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
230 if (UNLIKELY(field >= limit)) {
231 ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
jeffhao10037c82012-01-23 15:06:23 -0800232 return false;
233 }
234 return true;
235}
236
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800237bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
238 uint32_t size,
239 size_t alignment,
240 const char* label) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700241 if (size == 0) {
242 if (offset != 0) {
243 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
244 return false;
245 }
246 }
247 if (size_ <= offset) {
248 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
249 return false;
250 }
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800251 if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
252 ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
253 return false;
254 }
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700255 return true;
256}
257
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100258bool DexFileVerifier::CheckSizeLimit(uint32_t size, uint32_t limit, const char* label) {
259 if (size > limit) {
260 ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label);
261 return false;
262 }
263 return true;
264}
265
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700266bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800267 // Check file size from the header.
268 uint32_t expected_size = header_->file_size_;
269 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700270 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800271 return false;
272 }
273
274 // Compute and verify the checksum in the header.
275 uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
276 const uint32_t non_sum = sizeof(header_->magic_) + sizeof(header_->checksum_);
Ian Rogers13735952014-10-08 12:43:28 -0700277 const uint8_t* non_sum_ptr = reinterpret_cast<const uint8_t*>(header_) + non_sum;
jeffhaof6174e82012-01-31 16:14:17 -0800278 adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
jeffhao10037c82012-01-23 15:06:23 -0800279 if (adler_checksum != header_->checksum_) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700280 if (verify_checksum_) {
281 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
282 return false;
283 } else {
284 LOG(WARNING) << StringPrintf(
285 "Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
286 }
jeffhao10037c82012-01-23 15:06:23 -0800287 }
288
289 // Check the contents of the header.
290 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700291 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800292 return false;
293 }
294
295 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700296 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800297 return false;
298 }
299
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700300 // Check that all offsets are inside the file.
301 bool result =
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800302 CheckValidOffsetAndSize(header_->link_off_,
303 header_->link_size_,
304 0 /* unaligned */,
305 "link") &&
306 CheckValidOffsetAndSize(header_->map_off_,
307 header_->map_off_,
308 4,
309 "map") &&
310 CheckValidOffsetAndSize(header_->string_ids_off_,
311 header_->string_ids_size_,
312 4,
313 "string-ids") &&
314 CheckValidOffsetAndSize(header_->type_ids_off_,
315 header_->type_ids_size_,
316 4,
317 "type-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100318 CheckSizeLimit(header_->type_ids_size_, DexFile::kDexNoIndex16, "type-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800319 CheckValidOffsetAndSize(header_->proto_ids_off_,
320 header_->proto_ids_size_,
321 4,
322 "proto-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100323 CheckSizeLimit(header_->proto_ids_size_, DexFile::kDexNoIndex16, "proto-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800324 CheckValidOffsetAndSize(header_->field_ids_off_,
325 header_->field_ids_size_,
326 4,
327 "field-ids") &&
328 CheckValidOffsetAndSize(header_->method_ids_off_,
329 header_->method_ids_size_,
330 4,
331 "method-ids") &&
332 CheckValidOffsetAndSize(header_->class_defs_off_,
333 header_->class_defs_size_,
334 4,
335 "class-defs") &&
336 CheckValidOffsetAndSize(header_->data_off_,
337 header_->data_size_,
338 0, // Unaligned, spec doesn't talk about it, even though size
339 // is supposed to be a multiple of 4.
340 "data");
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700341 return result;
jeffhao10037c82012-01-23 15:06:23 -0800342}
343
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700344bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700345 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
346 header_->map_off_);
347 // Check that map list content is available.
348 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
349 return false;
350 }
351
jeffhao10037c82012-01-23 15:06:23 -0800352 const DexFile::MapItem* item = map->list_;
353
354 uint32_t count = map->size_;
355 uint32_t last_offset = 0;
356 uint32_t data_item_count = 0;
357 uint32_t data_items_left = header_->data_size_;
358 uint32_t used_bits = 0;
359
360 // Sanity check the size of the map list.
361 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
362 return false;
363 }
364
365 // Check the items listed in the map.
366 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700367 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
368 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800369 return false;
370 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700371 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
372 ErrorStringPrintf("Map item after end of file: %x, size %x",
373 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800374 return false;
375 }
376
377 if (IsDataSectionType(item->type_)) {
378 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700379 if (UNLIKELY(icount > data_items_left)) {
380 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800381 return false;
382 }
383 data_items_left -= icount;
384 data_item_count += icount;
385 }
386
387 uint32_t bit = MapTypeToBitMask(item->type_);
388
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700389 if (UNLIKELY(bit == 0)) {
390 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800391 return false;
392 }
393
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700394 if (UNLIKELY((used_bits & bit) != 0)) {
395 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800396 return false;
397 }
398
399 used_bits |= bit;
400 last_offset = item->offset_;
401 item++;
402 }
403
404 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700405 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
406 ErrorStringPrintf("Map is missing header entry");
jeffhao10037c82012-01-23 15:06:23 -0800407 return false;
408 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700409 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
410 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800411 return false;
412 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700413 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
414 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
415 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800416 return false;
417 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700418 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
419 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
420 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800421 return false;
422 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700423 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
424 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
425 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800426 return false;
427 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700428 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
429 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
430 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800431 return false;
432 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700433 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
434 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
435 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800436 return false;
437 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700438 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
439 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
440 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800441 return false;
442 }
jeffhao10037c82012-01-23 15:06:23 -0800443 return true;
444}
445
446uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
447 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700448 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700449 for (uint32_t i = 0; i < size; i++) {
450 result |= ((uint32_t) *(ptr_++)) << (i * 8);
451 }
jeffhao10037c82012-01-23 15:06:23 -0800452 }
jeffhao10037c82012-01-23 15:06:23 -0800453 return result;
454}
455
Andreas Gampebed6daf2016-09-02 18:12:00 -0700456
457#define DECODE_UNSIGNED_CHECKED_FROM_WITH_ERROR_VALUE(ptr, var, error_value) \
458 uint32_t var; \
Andreas Gampe44fd2352016-11-03 08:21:21 -0700459 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700460 return error_value; \
461 }
462
Andreas Gampe44fd2352016-11-03 08:21:21 -0700463#define DECODE_UNSIGNED_CHECKED_FROM(ptr, var) \
464 uint32_t var; \
465 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
466 ErrorStringPrintf("Read out of bounds"); \
467 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700468 }
469
Andreas Gampe44fd2352016-11-03 08:21:21 -0700470#define DECODE_SIGNED_CHECKED_FROM(ptr, var) \
471 int32_t var; \
472 if (!DecodeSignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
473 ErrorStringPrintf("Read out of bounds"); \
474 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700475 }
476
jeffhao10037c82012-01-23 15:06:23 -0800477bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700478 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700479 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800480
481 for (uint32_t i = 0; i < handlers_size; i++) {
482 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800483 size_t offset = ptr_ - handlers_base;
Andreas Gampebed6daf2016-09-02 18:12:00 -0700484 DECODE_SIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800485
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700486 if (UNLIKELY((size < -65536) || (size > 65536))) {
487 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800488 return false;
489 }
490
491 if (size <= 0) {
492 catch_all = true;
493 size = -size;
494 } else {
495 catch_all = false;
496 }
497
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800498 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800499
500 while (size-- > 0) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700501 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -0800502 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
503 return false;
504 }
505
Andreas Gampebed6daf2016-09-02 18:12:00 -0700506 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700507 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
508 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800509 return false;
510 }
511 }
512
513 if (catch_all) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700514 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700515 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
516 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800517 return false;
518 }
519 }
520 }
521
522 return true;
523}
524
Andreas Gampee6215c02015-08-31 18:54:38 -0700525bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
526 uint32_t access_flags,
527 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700528 uint16_t class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700529 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700530 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800531 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
532 return false;
533 }
534
Andreas Gampee6215c02015-08-31 18:54:38 -0700535 // Check that it's the right class.
536 uint16_t my_class_index =
537 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
538 class_idx_;
539 if (class_type_index != my_class_index) {
540 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
541 my_class_index,
542 class_type_index);
543 return false;
544 }
545
546 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800547 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700548 if (UNLIKELY(is_static != expect_static)) {
549 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800550 return false;
551 }
552
Andreas Gampee6215c02015-08-31 18:54:38 -0700553 // Check field access flags.
554 std::string error_msg;
Andreas Gampec9f0ba12016-02-09 09:21:04 -0800555 if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700556 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800557 return false;
558 }
559
560 return true;
561}
562
Andreas Gampee6215c02015-08-31 18:54:38 -0700563bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
564 uint32_t access_flags,
565 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700566 uint16_t class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700567 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700568 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700569 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700570 DCHECK(direct_method_indexes != nullptr);
571 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800572 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
573 return false;
574 }
575
Andreas Gampee6215c02015-08-31 18:54:38 -0700576 // Check that it's the right class.
577 uint16_t my_class_index =
578 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
579 class_idx_;
580 if (class_type_index != my_class_index) {
581 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 "vs %" PRIu16,
582 my_class_index,
583 class_type_index);
jeffhao10037c82012-01-23 15:06:23 -0800584 return false;
585 }
586
Andreas Gampee6215c02015-08-31 18:54:38 -0700587 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700588 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700589 direct_method_indexes->insert(idx);
590 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700591 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
592 return false;
593 }
594
Andreas Gampee6215c02015-08-31 18:54:38 -0700595 // Check method access flags.
596 bool has_code = (code_offset != 0);
597 std::string error_msg;
598 if (!CheckMethodAccessFlags(idx,
599 access_flags,
600 class_access_flags,
601 has_code,
602 expect_direct,
603 &error_msg)) {
604 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800605 return false;
606 }
607
608 return true;
609}
610
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800611bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800612 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700613 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800614 return false;
615 }
616 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700617 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800618 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800619 return false;
620 }
621 ptr_++;
622 offset++;
623 }
624 }
625 return true;
626}
627
628bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700629 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800630 return false;
631 }
632
633 uint8_t header_byte = *(ptr_++);
634 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
635 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
636
637 switch (value_type) {
638 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700639 if (UNLIKELY(value_arg != 0)) {
640 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800641 return false;
642 }
643 ptr_++;
644 break;
645 case DexFile::kDexAnnotationShort:
646 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700647 if (UNLIKELY(value_arg > 1)) {
648 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800649 return false;
650 }
651 ptr_ += value_arg + 1;
652 break;
653 case DexFile::kDexAnnotationInt:
654 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700655 if (UNLIKELY(value_arg > 3)) {
656 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800657 return false;
658 }
659 ptr_ += value_arg + 1;
660 break;
661 case DexFile::kDexAnnotationLong:
662 case DexFile::kDexAnnotationDouble:
663 ptr_ += value_arg + 1;
664 break;
665 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700666 if (UNLIKELY(value_arg > 3)) {
667 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800668 return false;
669 }
670 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
671 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
672 return false;
673 }
674 break;
675 }
676 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700677 if (UNLIKELY(value_arg > 3)) {
678 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800679 return false;
680 }
681 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
682 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
683 return false;
684 }
685 break;
686 }
687 case DexFile::kDexAnnotationField:
688 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700689 if (UNLIKELY(value_arg > 3)) {
690 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800691 return false;
692 }
693 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
694 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
695 return false;
696 }
697 break;
698 }
699 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700700 if (UNLIKELY(value_arg > 3)) {
701 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800702 return false;
703 }
704 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
705 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
706 return false;
707 }
708 break;
709 }
710 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700711 if (UNLIKELY(value_arg != 0)) {
712 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800713 return false;
714 }
715 if (!CheckEncodedArray()) {
716 return false;
717 }
718 break;
719 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700720 if (UNLIKELY(value_arg != 0)) {
721 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800722 return false;
723 }
724 if (!CheckEncodedAnnotation()) {
725 return false;
726 }
727 break;
728 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700729 if (UNLIKELY(value_arg != 0)) {
730 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800731 return false;
732 }
733 break;
734 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700735 if (UNLIKELY(value_arg > 1)) {
736 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800737 return false;
738 }
739 break;
740 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700741 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800742 return false;
743 }
744
745 return true;
746}
747
748bool DexFileVerifier::CheckEncodedArray() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700749 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800750
751 while (size--) {
752 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700753 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800754 return false;
755 }
756 }
757 return true;
758}
759
760bool DexFileVerifier::CheckEncodedAnnotation() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700761 DECODE_UNSIGNED_CHECKED_FROM(ptr_, anno_idx);
762 if (!CheckIndex(anno_idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -0800763 return false;
764 }
765
Andreas Gampebed6daf2016-09-02 18:12:00 -0700766 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800767 uint32_t last_idx = 0;
768
769 for (uint32_t i = 0; i < size; i++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700770 DECODE_UNSIGNED_CHECKED_FROM(ptr_, idx);
jeffhao10037c82012-01-23 15:06:23 -0800771 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
772 return false;
773 }
774
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700775 if (UNLIKELY(last_idx >= idx && i != 0)) {
776 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
777 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800778 return false;
779 }
780
781 if (!CheckEncodedValue()) {
782 return false;
783 }
784
785 last_idx = idx;
786 }
787 return true;
788}
789
Andreas Gampee6215c02015-08-31 18:54:38 -0700790bool DexFileVerifier::FindClassFlags(uint32_t index,
791 bool is_field,
792 uint16_t* class_type_index,
793 uint32_t* class_access_flags) {
794 DCHECK(class_type_index != nullptr);
795 DCHECK(class_access_flags != nullptr);
796
797 // First check if the index is valid.
798 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
799 return false;
800 }
801
802 // Next get the type index.
803 if (is_field) {
804 *class_type_index =
805 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
806 class_idx_;
807 } else {
808 *class_type_index =
809 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
810 class_idx_;
811 }
812
813 // Check if that is valid.
814 if (*class_type_index >= header_->type_ids_size_) {
815 return false;
816 }
817
818 // Now search for the class def. This is basically a specialized version of the DexFile code, as
819 // we should not trust that this is a valid DexFile just yet.
820 const DexFile::ClassDef* class_def_begin =
821 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
822 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
823 const DexFile::ClassDef* class_def = class_def_begin + i;
824 if (class_def->class_idx_ == *class_type_index) {
825 *class_access_flags = class_def->access_flags_;
826 return true;
827 }
828 }
829
830 // Didn't find the class-def, not defined here...
831 return false;
832}
833
834bool DexFileVerifier::CheckOrderAndGetClassFlags(bool is_field,
835 const char* type_descr,
836 uint32_t curr_index,
837 uint32_t prev_index,
838 bool* have_class,
839 uint16_t* class_type_index,
840 uint32_t* class_access_flags) {
841 if (curr_index < prev_index) {
842 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
843 type_descr,
844 prev_index,
845 curr_index);
846 return false;
847 }
848
849 if (!*have_class) {
850 *have_class = FindClassFlags(curr_index, is_field, class_type_index, class_access_flags);
851 if (!*have_class) {
852 // Should have really found one.
853 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
854 type_descr,
855 curr_index);
856 return false;
857 }
858 }
859 return true;
860}
861
862template <bool kStatic>
863bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
864 bool* have_class,
865 uint16_t* class_type_index,
866 uint32_t* class_access_flags) {
867 DCHECK(it != nullptr);
868 // These calls use the raw access flags to check whether the whole dex field is valid.
869 uint32_t prev_index = 0;
870 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
871 uint32_t curr_index = it->GetMemberIndex();
872 if (!CheckOrderAndGetClassFlags(true,
873 kStatic ? "static field" : "instance field",
874 curr_index,
875 prev_index,
876 have_class,
877 class_type_index,
878 class_access_flags)) {
879 return false;
880 }
881 prev_index = curr_index;
882
883 if (!CheckClassDataItemField(curr_index,
884 it->GetRawMemberAccessFlags(),
885 *class_access_flags,
886 *class_type_index,
887 kStatic)) {
888 return false;
889 }
890 }
891
892 return true;
893}
894
895template <bool kDirect>
896bool DexFileVerifier::CheckIntraClassDataItemMethods(
897 ClassDataItemIterator* it,
898 std::unordered_set<uint32_t>* direct_method_indexes,
899 bool* have_class,
900 uint16_t* class_type_index,
901 uint32_t* class_access_flags) {
902 uint32_t prev_index = 0;
903 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
904 uint32_t curr_index = it->GetMemberIndex();
905 if (!CheckOrderAndGetClassFlags(false,
906 kDirect ? "direct method" : "virtual method",
907 curr_index,
908 prev_index,
909 have_class,
910 class_type_index,
911 class_access_flags)) {
912 return false;
913 }
914 prev_index = curr_index;
915
916 if (!CheckClassDataItemMethod(curr_index,
917 it->GetRawMemberAccessFlags(),
918 *class_access_flags,
919 *class_type_index,
920 it->GetMethodCodeItemOffset(),
921 direct_method_indexes,
922 kDirect)) {
923 return false;
924 }
925 }
926
927 return true;
928}
929
jeffhao10037c82012-01-23 15:06:23 -0800930bool DexFileVerifier::CheckIntraClassDataItem() {
931 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -0700932 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -0800933
Andreas Gampee6215c02015-08-31 18:54:38 -0700934 // This code is complicated by the fact that we don't directly know which class this belongs to.
935 // So we need to explicitly search with the first item we find (either field or method), and then,
936 // as the lookup is expensive, cache the result.
937 bool have_class = false;
938 uint16_t class_type_index;
939 uint32_t class_access_flags;
940
941 // Check fields.
942 if (!CheckIntraClassDataItemFields<true>(&it,
943 &have_class,
944 &class_type_index,
945 &class_access_flags)) {
946 return false;
jeffhao10037c82012-01-23 15:06:23 -0800947 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700948 if (!CheckIntraClassDataItemFields<false>(&it,
949 &have_class,
950 &class_type_index,
951 &class_access_flags)) {
952 return false;
jeffhao10037c82012-01-23 15:06:23 -0800953 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700954
955 // Check methods.
956 if (!CheckIntraClassDataItemMethods<true>(&it,
957 &direct_method_indexes,
958 &have_class,
959 &class_type_index,
960 &class_access_flags)) {
961 return false;
jeffhao10037c82012-01-23 15:06:23 -0800962 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700963 if (!CheckIntraClassDataItemMethods<false>(&it,
964 &direct_method_indexes,
965 &have_class,
966 &class_type_index,
967 &class_access_flags)) {
968 return false;
jeffhao10037c82012-01-23 15:06:23 -0800969 }
970
971 ptr_ = it.EndDataPointer();
972 return true;
973}
974
975bool DexFileVerifier::CheckIntraCodeItem() {
976 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700977 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -0800978 return false;
979 }
980
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700981 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
982 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
983 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800984 return false;
985 }
986
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700987 if (UNLIKELY((code_item->outs_size_ > 5) &&
988 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -0800989 /*
990 * outs_size can be up to 5, even if registers_size is smaller, since the
991 * short forms of method invocation allow repetitions of a register multiple
992 * times within a single parameter list. However, longer parameter lists
993 * need to be represented in-order in the register file.
994 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700995 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
996 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800997 return false;
998 }
999
1000 const uint16_t* insns = code_item->insns_;
1001 uint32_t insns_size = code_item->insns_size_in_code_units_;
1002 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
1003 return false;
1004 }
1005
1006 // Grab the end of the insns if there are no try_items.
1007 uint32_t try_items_size = code_item->tries_size_;
1008 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001009 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001010 return true;
1011 }
1012
1013 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001014 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001015 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001016 return false;
1017 }
1018
1019 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -08001020 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
1021 return false;
1022 }
1023
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001024 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
Andreas Gampebed6daf2016-09-02 18:12:00 -07001025 DECODE_UNSIGNED_CHECKED_FROM(ptr_, handlers_size);
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001026
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001027 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
1028 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -08001029 return false;
1030 }
1031
Ian Rogers700a4022014-05-19 16:49:03 -07001032 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -07001033 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -08001034 return false;
1035 }
1036
1037 uint32_t last_addr = 0;
1038 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001039 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1040 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001041 return false;
1042 }
1043
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001044 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1045 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001046 return false;
1047 }
1048
1049 uint32_t i;
1050 for (i = 0; i < handlers_size; i++) {
1051 if (try_items->handler_off_ == handler_offsets[i]) {
1052 break;
1053 }
1054 }
1055
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001056 if (UNLIKELY(i == handlers_size)) {
1057 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -08001058 return false;
1059 }
1060
1061 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001062 if (UNLIKELY(last_addr > insns_size)) {
1063 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -08001064 return false;
1065 }
1066
1067 try_items++;
1068 }
1069
1070 return true;
1071}
1072
1073bool DexFileVerifier::CheckIntraStringDataItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001074 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
Ian Rogers13735952014-10-08 12:43:28 -07001075 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001076
1077 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001078 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001079 if (UNLIKELY(ptr_ >= file_end)) {
1080 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001081 return false;
1082 }
1083
1084 uint8_t byte = *(ptr_++);
1085
1086 // Switch on the high 4 bits.
1087 switch (byte >> 4) {
1088 case 0x00:
1089 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001090 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001091 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001092 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001093 return false;
1094 }
1095 break;
1096 case 0x01:
1097 case 0x02:
1098 case 0x03:
1099 case 0x04:
1100 case 0x05:
1101 case 0x06:
1102 case 0x07:
1103 // No extra checks necessary for bit pattern 0xxx.
1104 break;
1105 case 0x08:
1106 case 0x09:
1107 case 0x0a:
1108 case 0x0b:
1109 case 0x0f:
1110 // Illegal bit patterns 10xx or 1111.
1111 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001112 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001113 return false;
1114 case 0x0c:
1115 case 0x0d: {
1116 // Bit pattern 110x has an additional byte.
1117 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001118 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1119 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001120 return false;
1121 }
1122 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001123 if (UNLIKELY((value != 0) && (value < 0x80))) {
1124 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001125 return false;
1126 }
1127 break;
1128 }
1129 case 0x0e: {
1130 // Bit pattern 1110 has 2 additional bytes.
1131 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001132 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1133 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001134 return false;
1135 }
1136 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001137 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1138 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001139 return false;
1140 }
1141 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001142 if (UNLIKELY(value < 0x800)) {
1143 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001144 return false;
1145 }
1146 break;
1147 }
1148 }
1149 }
1150
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001151 if (UNLIKELY(*(ptr_++) != '\0')) {
1152 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001153 return false;
1154 }
1155
1156 return true;
1157}
1158
1159bool DexFileVerifier::CheckIntraDebugInfoItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001160 DECODE_UNSIGNED_CHECKED_FROM(ptr_, dummy);
1161 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameters_size);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001162 if (UNLIKELY(parameters_size > 65536)) {
1163 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001164 return false;
1165 }
1166
1167 for (uint32_t j = 0; j < parameters_size; j++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001168 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameter_name);
jeffhao10037c82012-01-23 15:06:23 -08001169 if (parameter_name != 0) {
1170 parameter_name--;
1171 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1172 return false;
1173 }
1174 }
1175 }
1176
1177 while (true) {
1178 uint8_t opcode = *(ptr_++);
1179 switch (opcode) {
1180 case DexFile::DBG_END_SEQUENCE: {
1181 return true;
1182 }
1183 case DexFile::DBG_ADVANCE_PC: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001184 DECODE_UNSIGNED_CHECKED_FROM(ptr_, advance_pc_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001185 break;
1186 }
1187 case DexFile::DBG_ADVANCE_LINE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001188 DECODE_SIGNED_CHECKED_FROM(ptr_, advance_line_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001189 break;
1190 }
1191 case DexFile::DBG_START_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001192 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001193 if (UNLIKELY(reg_num >= 65536)) {
1194 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001195 return false;
1196 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001197 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001198 if (name_idx != 0) {
1199 name_idx--;
1200 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1201 return false;
1202 }
1203 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001204 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001205 if (type_idx != 0) {
1206 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001207 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001208 return false;
1209 }
1210 }
1211 break;
1212 }
1213 case DexFile::DBG_END_LOCAL:
1214 case DexFile::DBG_RESTART_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001215 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001216 if (UNLIKELY(reg_num >= 65536)) {
1217 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001218 return false;
1219 }
1220 break;
1221 }
1222 case DexFile::DBG_START_LOCAL_EXTENDED: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001223 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001224 if (UNLIKELY(reg_num >= 65536)) {
1225 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001226 return false;
1227 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001228 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001229 if (name_idx != 0) {
1230 name_idx--;
1231 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1232 return false;
1233 }
1234 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001235 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001236 if (type_idx != 0) {
1237 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001238 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001239 return false;
1240 }
1241 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001242 DECODE_UNSIGNED_CHECKED_FROM(ptr_, sig_idx);
jeffhao10037c82012-01-23 15:06:23 -08001243 if (sig_idx != 0) {
1244 sig_idx--;
1245 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1246 return false;
1247 }
1248 }
1249 break;
1250 }
1251 case DexFile::DBG_SET_FILE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001252 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001253 if (name_idx != 0) {
1254 name_idx--;
1255 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1256 return false;
1257 }
1258 }
1259 break;
1260 }
1261 }
1262 }
1263}
1264
1265bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001266 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001267 return false;
1268 }
1269
1270 // Check visibility
1271 switch (*(ptr_++)) {
1272 case DexFile::kDexVisibilityBuild:
1273 case DexFile::kDexVisibilityRuntime:
1274 case DexFile::kDexVisibilitySystem:
1275 break;
1276 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001277 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001278 return false;
1279 }
1280
1281 if (!CheckEncodedAnnotation()) {
1282 return false;
1283 }
1284
1285 return true;
1286}
1287
1288bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1289 const DexFile::AnnotationsDirectoryItem* item =
1290 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001291 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001292 return false;
1293 }
1294
1295 // Field annotations follow immediately after the annotations directory.
1296 const DexFile::FieldAnnotationsItem* field_item =
1297 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1298 uint32_t field_count = item->fields_size_;
1299 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1300 return false;
1301 }
1302
1303 uint32_t last_idx = 0;
1304 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001305 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1306 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001307 return false;
1308 }
1309 last_idx = field_item->field_idx_;
1310 field_item++;
1311 }
1312
1313 // Method annotations follow immediately after field annotations.
1314 const DexFile::MethodAnnotationsItem* method_item =
1315 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1316 uint32_t method_count = item->methods_size_;
1317 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1318 return false;
1319 }
1320
1321 last_idx = 0;
1322 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001323 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1324 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1325 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001326 return false;
1327 }
1328 last_idx = method_item->method_idx_;
1329 method_item++;
1330 }
1331
1332 // Parameter annotations follow immediately after method annotations.
1333 const DexFile::ParameterAnnotationsItem* parameter_item =
1334 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1335 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001336 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001337 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001338 return false;
1339 }
1340
1341 last_idx = 0;
1342 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001343 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1344 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1345 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001346 return false;
1347 }
1348 last_idx = parameter_item->method_idx_;
1349 parameter_item++;
1350 }
1351
1352 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001353 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001354 return true;
1355}
1356
Andreas Gampeb061cc12014-09-02 10:22:20 -07001357bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
1358 uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001359 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001360 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001361 switch (type) {
1362 case DexFile::kDexTypeClassDataItem:
1363 case DexFile::kDexTypeStringDataItem:
1364 case DexFile::kDexTypeDebugInfoItem:
1365 case DexFile::kDexTypeAnnotationItem:
1366 case DexFile::kDexTypeEncodedArrayItem:
1367 alignment_mask = sizeof(uint8_t) - 1;
1368 break;
1369 default:
1370 alignment_mask = sizeof(uint32_t) - 1;
1371 break;
1372 }
1373
1374 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001375 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001376 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001377
1378 // Check the padding between items.
1379 if (!CheckPadding(offset, aligned_offset)) {
1380 return false;
1381 }
1382
1383 // Check depending on the section type.
1384 switch (type) {
1385 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001386 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001387 return false;
1388 }
1389 ptr_ += sizeof(DexFile::StringId);
1390 break;
1391 }
1392 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001393 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001394 return false;
1395 }
1396 ptr_ += sizeof(DexFile::TypeId);
1397 break;
1398 }
1399 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001400 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001401 return false;
1402 }
1403 ptr_ += sizeof(DexFile::ProtoId);
1404 break;
1405 }
1406 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001407 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001408 return false;
1409 }
1410 ptr_ += sizeof(DexFile::FieldId);
1411 break;
1412 }
1413 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001414 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001415 return false;
1416 }
1417 ptr_ += sizeof(DexFile::MethodId);
1418 break;
1419 }
1420 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001421 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001422 return false;
1423 }
1424 ptr_ += sizeof(DexFile::ClassDef);
1425 break;
1426 }
1427 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001428 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001429 return false;
1430 }
jeffhao10037c82012-01-23 15:06:23 -08001431 break;
1432 }
1433 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001434 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001435 return false;
1436 }
jeffhao10037c82012-01-23 15:06:23 -08001437 break;
1438 }
1439 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001440 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001441 return false;
1442 }
jeffhao10037c82012-01-23 15:06:23 -08001443 break;
1444 }
1445 case DexFile::kDexTypeClassDataItem: {
1446 if (!CheckIntraClassDataItem()) {
1447 return false;
1448 }
1449 break;
1450 }
1451 case DexFile::kDexTypeCodeItem: {
1452 if (!CheckIntraCodeItem()) {
1453 return false;
1454 }
1455 break;
1456 }
1457 case DexFile::kDexTypeStringDataItem: {
1458 if (!CheckIntraStringDataItem()) {
1459 return false;
1460 }
1461 break;
1462 }
1463 case DexFile::kDexTypeDebugInfoItem: {
1464 if (!CheckIntraDebugInfoItem()) {
1465 return false;
1466 }
1467 break;
1468 }
1469 case DexFile::kDexTypeAnnotationItem: {
1470 if (!CheckIntraAnnotationItem()) {
1471 return false;
1472 }
1473 break;
1474 }
1475 case DexFile::kDexTypeEncodedArrayItem: {
1476 if (!CheckEncodedArray()) {
1477 return false;
1478 }
1479 break;
1480 }
1481 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1482 if (!CheckIntraAnnotationsDirectoryItem()) {
1483 return false;
1484 }
1485 break;
1486 }
1487 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001488 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001489 return false;
1490 }
1491
1492 if (IsDataSectionType(type)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001493 if (aligned_offset == 0u) {
1494 ErrorStringPrintf("Item %d offset is 0", i);
1495 return false;
1496 }
1497 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1498 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001499 }
1500
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001501 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001502 if (UNLIKELY(aligned_offset > size_)) {
1503 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001504 return false;
1505 }
1506
1507 offset = aligned_offset;
1508 }
1509
1510 return true;
1511}
1512
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001513bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001514 uint32_t expected_offset;
1515 uint32_t expected_size;
1516
1517 // Get the expected offset and size from the header.
1518 switch (type) {
1519 case DexFile::kDexTypeStringIdItem:
1520 expected_offset = header_->string_ids_off_;
1521 expected_size = header_->string_ids_size_;
1522 break;
1523 case DexFile::kDexTypeTypeIdItem:
1524 expected_offset = header_->type_ids_off_;
1525 expected_size = header_->type_ids_size_;
1526 break;
1527 case DexFile::kDexTypeProtoIdItem:
1528 expected_offset = header_->proto_ids_off_;
1529 expected_size = header_->proto_ids_size_;
1530 break;
1531 case DexFile::kDexTypeFieldIdItem:
1532 expected_offset = header_->field_ids_off_;
1533 expected_size = header_->field_ids_size_;
1534 break;
1535 case DexFile::kDexTypeMethodIdItem:
1536 expected_offset = header_->method_ids_off_;
1537 expected_size = header_->method_ids_size_;
1538 break;
1539 case DexFile::kDexTypeClassDefItem:
1540 expected_offset = header_->class_defs_off_;
1541 expected_size = header_->class_defs_size_;
1542 break;
1543 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001544 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001545 return false;
1546 }
1547
1548 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001549 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001550 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001551 return false;
1552 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001553 if (UNLIKELY(count != expected_size)) {
1554 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001555 return false;
1556 }
1557
1558 return CheckIntraSectionIterate(offset, count, type);
1559}
1560
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001561bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count, uint16_t type) {
1562 size_t data_start = header_->data_off_;
1563 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001564
1565 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001566 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001567 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001568 return false;
1569 }
1570
1571 if (!CheckIntraSectionIterate(offset, count, type)) {
1572 return false;
1573 }
1574
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001575 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001576 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001577 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001578 return false;
1579 }
1580
1581 return true;
1582}
1583
1584bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001585 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001586 const DexFile::MapItem* item = map->list_;
1587
1588 uint32_t count = map->size_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001589 size_t offset = 0;
Ian Rogers30fab402012-01-23 15:43:46 -08001590 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001591
1592 // Check the items listed in the map.
1593 while (count--) {
1594 uint32_t section_offset = item->offset_;
1595 uint32_t section_count = item->size_;
1596 uint16_t type = item->type_;
1597
1598 // Check for padding and overlap between items.
1599 if (!CheckPadding(offset, section_offset)) {
1600 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001601 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001602 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001603 return false;
1604 }
1605
1606 // Check each item based on its type.
1607 switch (type) {
1608 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001609 if (UNLIKELY(section_count != 1)) {
1610 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001611 return false;
1612 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001613 if (UNLIKELY(section_offset != 0)) {
1614 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001615 return false;
1616 }
Ian Rogers30fab402012-01-23 15:43:46 -08001617 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001618 offset = header_->header_size_;
1619 break;
1620 case DexFile::kDexTypeStringIdItem:
1621 case DexFile::kDexTypeTypeIdItem:
1622 case DexFile::kDexTypeProtoIdItem:
1623 case DexFile::kDexTypeFieldIdItem:
1624 case DexFile::kDexTypeMethodIdItem:
1625 case DexFile::kDexTypeClassDefItem:
1626 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1627 return false;
1628 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001629 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001630 break;
1631 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001632 if (UNLIKELY(section_count != 1)) {
1633 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001634 return false;
1635 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001636 if (UNLIKELY(section_offset != header_->map_off_)) {
1637 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1638 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001639 return false;
1640 }
1641 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1642 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1643 break;
1644 case DexFile::kDexTypeTypeList:
1645 case DexFile::kDexTypeAnnotationSetRefList:
1646 case DexFile::kDexTypeAnnotationSetItem:
1647 case DexFile::kDexTypeClassDataItem:
1648 case DexFile::kDexTypeCodeItem:
1649 case DexFile::kDexTypeStringDataItem:
1650 case DexFile::kDexTypeDebugInfoItem:
1651 case DexFile::kDexTypeAnnotationItem:
1652 case DexFile::kDexTypeEncodedArrayItem:
1653 case DexFile::kDexTypeAnnotationsDirectoryItem:
1654 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1655 return false;
1656 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001657 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001658 break;
1659 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001660 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001661 return false;
1662 }
1663
1664 item++;
1665 }
1666
1667 return true;
1668}
1669
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001670bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001671 DCHECK_NE(offset, 0u);
1672 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001673 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001674 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001675 return false;
1676 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001677 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001678 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001679 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001680 return false;
1681 }
1682 return true;
1683}
1684
Ian Rogers13735952014-10-08 12:43:28 -07001685uint16_t DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001686 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001687 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001688
1689 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001690 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
1691 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001692 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001693 }
1694
1695 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001696 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
1697 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001698 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001699 }
1700
1701 return DexFile::kDexNoIndex16;
1702}
1703
Ian Rogers13735952014-10-08 12:43:28 -07001704uint16_t DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001705 const DexFile::AnnotationsDirectoryItem* item =
1706 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001707 *success = true;
1708
jeffhao10037c82012-01-23 15:06:23 -08001709 if (item->fields_size_ != 0) {
1710 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001711 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
1712 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001713 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001714 }
1715
1716 if (item->methods_size_ != 0) {
1717 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001718 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001719 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001720 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001721 }
1722
1723 if (item->parameters_size_ != 0) {
1724 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001725 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001726 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001727 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001728 }
1729
1730 return DexFile::kDexNoIndex16;
1731}
1732
1733bool DexFileVerifier::CheckInterStringIdItem() {
1734 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1735
1736 // Check the map to make sure it has the right offset->type.
1737 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1738 return false;
1739 }
1740
1741 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001742 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001743 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1744 const char* prev_str = dex_file_->GetStringData(*prev_item);
1745 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001746 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1747 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001748 return false;
1749 }
1750 }
1751
1752 ptr_ += sizeof(DexFile::StringId);
1753 return true;
1754}
1755
1756bool DexFileVerifier::CheckInterTypeIdItem() {
1757 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001758
1759 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001760
1761 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001762 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1763 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001764 return false;
1765 }
1766
1767 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001768 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001769 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001770 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1771 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
1772 prev_item->descriptor_idx_, item->descriptor_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001773 return false;
1774 }
1775 }
1776
1777 ptr_ += sizeof(DexFile::TypeId);
1778 return true;
1779}
1780
1781bool DexFileVerifier::CheckInterProtoIdItem() {
1782 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001783
1784 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1785
jeffhao10037c82012-01-23 15:06:23 -08001786 if (item->parameters_off_ != 0 &&
1787 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1788 return false;
1789 }
1790
1791 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001792 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1793 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001794 return false;
1795 }
1796 shorty++;
1797
1798 DexFileParameterIterator it(*dex_file_, *item);
1799 while (it.HasNext() && *shorty != '\0') {
Andreas Gampebb836e12014-06-13 15:31:40 -07001800 if (!CheckIndex(it.GetTypeIdx(), dex_file_->NumTypeIds(),
1801 "inter_proto_id_item shorty type_idx")) {
1802 return false;
1803 }
jeffhao10037c82012-01-23 15:06:23 -08001804 const char* descriptor = it.GetDescriptor();
1805 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1806 return false;
1807 }
1808 it.Next();
1809 shorty++;
1810 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001811 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1812 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001813 return false;
1814 }
1815
1816 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001817 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001818 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001819 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1820 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001821 return false;
1822 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1823 DexFileParameterIterator curr_it(*dex_file_, *item);
1824 DexFileParameterIterator prev_it(*dex_file_, *prev);
1825
1826 while (curr_it.HasNext() && prev_it.HasNext()) {
1827 uint16_t prev_idx = prev_it.GetTypeIdx();
1828 uint16_t curr_idx = curr_it.GetTypeIdx();
Vladimir Marko0ca8add2016-05-03 17:17:50 +01001829 DCHECK_NE(prev_idx, DexFile::kDexNoIndex16);
1830 DCHECK_NE(curr_idx, DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001831
1832 if (prev_idx < curr_idx) {
1833 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001834 } else if (UNLIKELY(prev_idx > curr_idx)) {
1835 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001836 return false;
1837 }
1838
1839 prev_it.Next();
1840 curr_it.Next();
1841 }
Vladimir Marko0ca8add2016-05-03 17:17:50 +01001842 if (!curr_it.HasNext()) {
1843 // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
1844 // a ProtoId with a longer one. Both cases are forbidden by the specification.
1845 ErrorStringPrintf("Out-of-order proto_id arguments");
1846 return false;
1847 }
jeffhao10037c82012-01-23 15:06:23 -08001848 }
1849 }
1850
1851 ptr_ += sizeof(DexFile::ProtoId);
1852 return true;
1853}
1854
1855bool DexFileVerifier::CheckInterFieldIdItem() {
1856 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1857
1858 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001859 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1860 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1861 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001862 return false;
1863 }
1864
1865 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001866 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1867 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1868 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001869 return false;
1870 }
1871
1872 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001873 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001874 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1875 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001876 return false;
1877 }
1878
1879 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001880 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001881 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001882 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1883 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001884 return false;
1885 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001886 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1887 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001888 return false;
1889 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001890 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
1891 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001892 return false;
1893 }
1894 }
1895 }
1896 }
1897
1898 ptr_ += sizeof(DexFile::FieldId);
1899 return true;
1900}
1901
1902bool DexFileVerifier::CheckInterMethodIdItem() {
1903 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
1904
1905 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001906 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
1907 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
1908 class_descriptor[0] != '['))) {
1909 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001910 return false;
1911 }
1912
1913 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07001914 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001915 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1916 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001917 return false;
1918 }
1919
Andreas Gampedf10b322014-06-11 21:46:05 -07001920 // Check that the proto id is valid.
1921 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
1922 "inter_method_id_item proto_idx"))) {
1923 return false;
1924 }
1925
jeffhao10037c82012-01-23 15:06:23 -08001926 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001927 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001928 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001929 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1930 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001931 return false;
1932 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001933 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1934 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001935 return false;
1936 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001937 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
1938 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001939 return false;
1940 }
1941 }
1942 }
1943 }
1944
1945 ptr_ += sizeof(DexFile::MethodId);
1946 return true;
1947}
1948
1949bool DexFileVerifier::CheckInterClassDefItem() {
1950 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001951
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001952 // Check for duplicate class def.
1953 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
1954 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_);
1955 return false;
1956 }
1957 defined_classes_.insert(item->class_idx_);
1958
Andreas Gampee09269c2014-06-06 18:45:35 -07001959 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
1960 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1961 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001962 return false;
1963 }
1964
Andreas Gampeacc2bb62014-07-17 19:26:50 -07001965 // Only allow non-runtime modifiers.
1966 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
1967 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
1968 return false;
1969 }
1970
jeffhao10037c82012-01-23 15:06:23 -08001971 if (item->interfaces_off_ != 0 &&
1972 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
1973 return false;
1974 }
1975 if (item->annotations_off_ != 0 &&
1976 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
1977 return false;
1978 }
1979 if (item->class_data_off_ != 0 &&
1980 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
1981 return false;
1982 }
1983 if (item->static_values_off_ != 0 &&
1984 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
1985 return false;
1986 }
1987
1988 if (item->superclass_idx_ != DexFile::kDexNoIndex16) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01001989 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
1990 // Check that a class does not inherit from itself directly (by having
1991 // the same type idx as its super class).
1992 if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
1993 ErrorStringPrintf("Class with same type idx as its superclass: '%d'", item->class_idx_);
1994 return false;
1995 }
1996
1997 // Check that a class is defined after its super class (if the
1998 // latter is defined in the same Dex file).
1999 const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
2000 if (superclass_def != nullptr) {
2001 // The superclass is defined in this Dex file.
2002 if (superclass_def > item) {
2003 // ClassDef item for super class appearing after the class' ClassDef item.
2004 ErrorStringPrintf("Invalid class definition ordering:"
2005 " class with type idx: '%d' defined before"
2006 " superclass with type idx: '%d'",
2007 item->class_idx_,
2008 item->superclass_idx_);
2009 return false;
2010 }
2011 }
2012 }
2013
Andreas Gampee09269c2014-06-06 18:45:35 -07002014 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
2015 "inter_class_def_item superclass_idx")
2016 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
2017 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002018 return false;
2019 }
2020 }
2021
Roland Levillain621b5ea2016-05-18 11:41:33 +01002022 // Check interfaces.
jeffhao10037c82012-01-23 15:06:23 -08002023 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002024 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002025 uint32_t size = interfaces->Size();
jeffhao10037c82012-01-23 15:06:23 -08002026 for (uint32_t i = 0; i < size; i++) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002027 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2028 // Check that a class does not implement itself directly (by having the
2029 // same type idx as one of its immediate implemented interfaces).
2030 if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2031 ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
2032 item->class_idx_);
2033 return false;
2034 }
2035
2036 // Check that a class is defined after the interfaces it implements
2037 // (if they are defined in the same Dex file).
2038 const DexFile::ClassDef* interface_def =
2039 dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2040 if (interface_def != nullptr) {
2041 // The interface is defined in this Dex file.
2042 if (interface_def > item) {
2043 // ClassDef item for interface appearing after the class' ClassDef item.
2044 ErrorStringPrintf("Invalid class definition ordering:"
2045 " class with type idx: '%d' defined before"
2046 " implemented interface with type idx: '%d'",
2047 item->class_idx_,
2048 interfaces->GetTypeItem(i).type_idx_);
2049 return false;
2050 }
2051 }
2052 }
2053
2054 // Ensure that the interface refers to a class (not an array nor a primitive type).
Andreas Gampee09269c2014-06-06 18:45:35 -07002055 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2056 "inter_class_def_item interface type_idx")
2057 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2058 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002059 return false;
2060 }
2061 }
2062
2063 /*
2064 * Ensure that there are no duplicates. This is an O(N^2) test, but in
2065 * practice the number of interfaces implemented by any given class is low.
2066 */
2067 for (uint32_t i = 1; i < size; i++) {
2068 uint32_t idx1 = interfaces->GetTypeItem(i).type_idx_;
2069 for (uint32_t j =0; j < i; j++) {
2070 uint32_t idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002071 if (UNLIKELY(idx1 == idx2)) {
2072 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08002073 return false;
2074 }
2075 }
2076 }
2077 }
2078
2079 // Check that references in class_data_item are to the right class.
2080 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07002081 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002082 bool success;
2083 uint16_t data_definer = FindFirstClassDataDefiner(data, &success);
2084 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002085 return false;
2086 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002087 if (UNLIKELY((data_definer != item->class_idx_) && (data_definer != DexFile::kDexNoIndex16))) {
2088 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08002089 return false;
2090 }
2091 }
2092
2093 // Check that references in annotations_directory_item are to right class.
2094 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002095 // annotations_off_ is supposed to be aligned by 4.
2096 if (!IsAlignedParam(item->annotations_off_, 4)) {
2097 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2098 return false;
2099 }
Ian Rogers13735952014-10-08 12:43:28 -07002100 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002101 bool success;
2102 uint16_t annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
2103 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002104 return false;
2105 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002106 if (UNLIKELY((annotations_definer != item->class_idx_) &&
2107 (annotations_definer != DexFile::kDexNoIndex16))) {
2108 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002109 return false;
2110 }
2111 }
2112
2113 ptr_ += sizeof(DexFile::ClassDef);
2114 return true;
2115}
2116
2117bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2118 const DexFile::AnnotationSetRefList* list =
2119 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2120 const DexFile::AnnotationSetRefItem* item = list->list_;
2121 uint32_t count = list->size_;
2122
2123 while (count--) {
2124 if (item->annotations_off_ != 0 &&
2125 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2126 return false;
2127 }
2128 item++;
2129 }
2130
Ian Rogers13735952014-10-08 12:43:28 -07002131 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002132 return true;
2133}
2134
2135bool DexFileVerifier::CheckInterAnnotationSetItem() {
2136 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2137 const uint32_t* offsets = set->entries_;
2138 uint32_t count = set->size_;
2139 uint32_t last_idx = 0;
2140
2141 for (uint32_t i = 0; i < count; i++) {
2142 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2143 return false;
2144 }
2145
2146 // Get the annotation from the offset and the type index for the annotation.
2147 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002148 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002149 const uint8_t* data = annotation->annotation_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002150 DECODE_UNSIGNED_CHECKED_FROM(data, idx);
jeffhao10037c82012-01-23 15:06:23 -08002151
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002152 if (UNLIKELY(last_idx >= idx && i != 0)) {
2153 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002154 return false;
2155 }
2156
2157 last_idx = idx;
2158 offsets++;
2159 }
2160
Ian Rogers13735952014-10-08 12:43:28 -07002161 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002162 return true;
2163}
2164
2165bool DexFileVerifier::CheckInterClassDataItem() {
2166 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002167 bool success;
2168 uint16_t defining_class = FindFirstClassDataDefiner(ptr_, &success);
2169 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002170 return false;
2171 }
jeffhao10037c82012-01-23 15:06:23 -08002172
2173 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002174 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002175 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002176 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002177 return false;
2178 }
2179 }
2180 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2181 uint32_t code_off = it.GetMethodCodeItemOffset();
2182 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2183 return false;
2184 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002185 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002186 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002187 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002188 return false;
2189 }
2190 }
2191
2192 ptr_ = it.EndDataPointer();
2193 return true;
2194}
2195
2196bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2197 const DexFile::AnnotationsDirectoryItem* item =
2198 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002199 bool success;
2200 uint16_t defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
2201 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002202 return false;
2203 }
jeffhao10037c82012-01-23 15:06:23 -08002204
2205 if (item->class_annotations_off_ != 0 &&
2206 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2207 return false;
2208 }
2209
2210 // Field annotations follow immediately after the annotations directory.
2211 const DexFile::FieldAnnotationsItem* field_item =
2212 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2213 uint32_t field_count = item->fields_size_;
2214 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002215 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2216 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002217 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002218 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002219 return false;
2220 }
2221 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2222 return false;
2223 }
2224 field_item++;
2225 }
2226
2227 // Method annotations follow immediately after field annotations.
2228 const DexFile::MethodAnnotationsItem* method_item =
2229 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2230 uint32_t method_count = item->methods_size_;
2231 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002232 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002233 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002234 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002235 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002236 return false;
2237 }
2238 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2239 return false;
2240 }
2241 method_item++;
2242 }
2243
2244 // Parameter annotations follow immediately after method annotations.
2245 const DexFile::ParameterAnnotationsItem* parameter_item =
2246 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2247 uint32_t parameter_count = item->parameters_size_;
2248 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002249 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002250 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002251 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002252 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002253 return false;
2254 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002255 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2256 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002257 return false;
2258 }
2259 parameter_item++;
2260 }
2261
Ian Rogers13735952014-10-08 12:43:28 -07002262 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002263 return true;
2264}
2265
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002266bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002267 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002268 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002269 switch (type) {
2270 case DexFile::kDexTypeClassDataItem:
2271 alignment_mask = sizeof(uint8_t) - 1;
2272 break;
2273 default:
2274 alignment_mask = sizeof(uint32_t) - 1;
2275 break;
2276 }
2277
2278 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002279 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002280 for (uint32_t i = 0; i < count; i++) {
2281 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002282 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002283 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002284
2285 // Check depending on the section type.
2286 switch (type) {
2287 case DexFile::kDexTypeStringIdItem: {
2288 if (!CheckInterStringIdItem()) {
2289 return false;
2290 }
2291 break;
2292 }
2293 case DexFile::kDexTypeTypeIdItem: {
2294 if (!CheckInterTypeIdItem()) {
2295 return false;
2296 }
2297 break;
2298 }
2299 case DexFile::kDexTypeProtoIdItem: {
2300 if (!CheckInterProtoIdItem()) {
2301 return false;
2302 }
2303 break;
2304 }
2305 case DexFile::kDexTypeFieldIdItem: {
2306 if (!CheckInterFieldIdItem()) {
2307 return false;
2308 }
2309 break;
2310 }
2311 case DexFile::kDexTypeMethodIdItem: {
2312 if (!CheckInterMethodIdItem()) {
2313 return false;
2314 }
2315 break;
2316 }
2317 case DexFile::kDexTypeClassDefItem: {
2318 if (!CheckInterClassDefItem()) {
2319 return false;
2320 }
2321 break;
2322 }
2323 case DexFile::kDexTypeAnnotationSetRefList: {
2324 if (!CheckInterAnnotationSetRefList()) {
2325 return false;
2326 }
2327 break;
2328 }
2329 case DexFile::kDexTypeAnnotationSetItem: {
2330 if (!CheckInterAnnotationSetItem()) {
2331 return false;
2332 }
2333 break;
2334 }
2335 case DexFile::kDexTypeClassDataItem: {
2336 if (!CheckInterClassDataItem()) {
2337 return false;
2338 }
2339 break;
2340 }
2341 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2342 if (!CheckInterAnnotationsDirectoryItem()) {
2343 return false;
2344 }
2345 break;
2346 }
2347 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002348 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002349 return false;
2350 }
2351
2352 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002353 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002354 }
2355
2356 return true;
2357}
2358
2359bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002360 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002361 const DexFile::MapItem* item = map->list_;
2362 uint32_t count = map->size_;
2363
2364 // Cross check the items listed in the map.
2365 while (count--) {
2366 uint32_t section_offset = item->offset_;
2367 uint32_t section_count = item->size_;
2368 uint16_t type = item->type_;
2369
2370 switch (type) {
2371 case DexFile::kDexTypeHeaderItem:
2372 case DexFile::kDexTypeMapList:
2373 case DexFile::kDexTypeTypeList:
2374 case DexFile::kDexTypeCodeItem:
2375 case DexFile::kDexTypeStringDataItem:
2376 case DexFile::kDexTypeDebugInfoItem:
2377 case DexFile::kDexTypeAnnotationItem:
2378 case DexFile::kDexTypeEncodedArrayItem:
2379 break;
2380 case DexFile::kDexTypeStringIdItem:
2381 case DexFile::kDexTypeTypeIdItem:
2382 case DexFile::kDexTypeProtoIdItem:
2383 case DexFile::kDexTypeFieldIdItem:
2384 case DexFile::kDexTypeMethodIdItem:
2385 case DexFile::kDexTypeClassDefItem:
2386 case DexFile::kDexTypeAnnotationSetRefList:
2387 case DexFile::kDexTypeAnnotationSetItem:
2388 case DexFile::kDexTypeClassDataItem:
2389 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2390 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2391 return false;
2392 }
2393 break;
2394 }
2395 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002396 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002397 return false;
2398 }
2399
2400 item++;
2401 }
2402
2403 return true;
2404}
2405
2406bool DexFileVerifier::Verify() {
2407 // Check the header.
2408 if (!CheckHeader()) {
2409 return false;
2410 }
2411
2412 // Check the map section.
2413 if (!CheckMap()) {
2414 return false;
2415 }
2416
2417 // Check structure within remaining sections.
2418 if (!CheckIntraSection()) {
2419 return false;
2420 }
2421
2422 // Check references from one section to another.
2423 if (!CheckInterSection()) {
2424 return false;
2425 }
2426
2427 return true;
2428}
2429
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002430void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2431 va_list ap;
2432 va_start(ap, fmt);
2433 DCHECK(failure_reason_.empty()) << failure_reason_;
2434 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2435 StringAppendV(&failure_reason_, fmt, ap);
2436 va_end(ap);
2437}
2438
Andreas Gampee6215c02015-08-31 18:54:38 -07002439// Fields and methods may have only one of public/protected/private.
2440static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2441 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2442 (((flags & kAccProtected) == 0) ? 0 : 1) +
2443 (((flags & kAccPrivate) == 0) ? 0 : 1);
2444 return count <= 1;
2445}
2446
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002447// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2448// functionality, as we're still verifying the dex file. begin and header correspond to the
2449// underscored variants in the DexFileVerifier.
2450
2451static std::string GetStringOrError(const uint8_t* const begin,
2452 const DexFile::Header* const header,
2453 uint32_t string_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002454 // The `string_idx` is not guaranteed to be valid yet.
2455 if (header->string_ids_size_ <= string_idx) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002456 return "(error)";
2457 }
2458
2459 const DexFile::StringId* string_id =
2460 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx;
2461
2462 // Assume that the data is OK at this point. String data has been checked at this point.
2463
2464 const uint8_t* ptr = begin + string_id->string_data_off_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002465 uint32_t dummy;
2466 if (!DecodeUnsignedLeb128Checked(&ptr, begin + header->file_size_, &dummy)) {
2467 return "(error)";
2468 }
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002469 return reinterpret_cast<const char*>(ptr);
2470}
2471
2472static std::string GetClassOrError(const uint8_t* const begin,
2473 const DexFile::Header* const header,
2474 uint32_t class_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002475 // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2476 // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2477 // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2478 // a valid defining class.
2479 CHECK_LT(class_idx, header->type_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002480
2481 const DexFile::TypeId* type_id =
2482 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx;
2483
2484 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2485
2486 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2487}
2488
2489static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2490 const DexFile::Header* const header,
2491 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002492 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2493 CHECK_LT(idx, header->field_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002494
2495 const DexFile::FieldId* field_id =
2496 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2497
2498 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2499
2500 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2501 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2502
2503 return class_name + "." + field_name;
2504}
2505
2506static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2507 const DexFile::Header* const header,
2508 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002509 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2510 CHECK_LT(idx, header->method_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002511
2512 const DexFile::MethodId* method_id =
2513 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2514
2515 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2516
2517 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2518 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2519
2520 return class_name + "." + method_name;
2521}
2522
2523bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2524 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002525 uint32_t class_access_flags,
2526 std::string* error_msg) {
2527 // Generally sort out >16-bit flags.
2528 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002529 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2530 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2531 field_access_flags,
2532 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002533 return false;
2534 }
2535
2536 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2537 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2538 kAccPrivate |
2539 kAccProtected |
2540 kAccStatic |
2541 kAccFinal |
2542 kAccVolatile |
2543 kAccTransient |
2544 kAccSynthetic |
2545 kAccEnum;
2546
2547 // Fields may have only one of public/protected/final.
2548 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002549 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2550 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2551 field_access_flags,
2552 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002553 return false;
2554 }
2555
2556 // Interfaces have a pretty restricted list.
2557 if ((class_access_flags & kAccInterface) != 0) {
2558 // Interface fields must be public final static.
2559 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2560 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002561 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2562 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2563 field_access_flags,
2564 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002565 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002566 return false;
2567 } else {
2568 // Allow in older versions, but warn.
2569 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2570 << *error_msg;
2571 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002572 }
2573 // Interface fields may be synthetic, but may not have other flags.
2574 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2575 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002576 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
2577 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2578 field_access_flags,
2579 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002580 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002581 return false;
2582 } else {
2583 // Allow in older versions, but warn.
2584 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2585 << *error_msg;
2586 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002587 }
2588 return true;
2589 }
2590
2591 // Volatile fields may not be final.
2592 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2593 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002594 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
2595 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002596 return false;
2597 }
2598
2599 return true;
2600}
2601
2602// Try to find the name of the method with the given index. We do not want to rely on DexFile
2603// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
2604// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
2605// (flagged by the return value), otherwise error_msg will contain an error string.
2606static bool FindMethodName(uint32_t method_index,
2607 const uint8_t* begin,
2608 const DexFile::Header* header,
2609 const char** str,
2610 std::string* error_msg) {
2611 if (method_index >= header->method_ids_size_) {
2612 *error_msg = "Method index not available for method flags verification";
2613 return false;
2614 }
2615 uint32_t string_idx =
2616 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
2617 method_index)->name_idx_;
2618 if (string_idx >= header->string_ids_size_) {
2619 *error_msg = "String index not available for method flags verification";
2620 return false;
2621 }
2622 uint32_t string_off =
2623 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
2624 string_data_off_;
2625 if (string_off >= header->file_size_) {
2626 *error_msg = "String offset out of bounds for method flags verification";
2627 return false;
2628 }
2629 const uint8_t* str_data_ptr = begin + string_off;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002630 uint32_t dummy;
2631 if (!DecodeUnsignedLeb128Checked(&str_data_ptr, begin + header->file_size_, &dummy)) {
2632 *error_msg = "String size out of bounds for method flags verification";
2633 return false;
2634 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002635 *str = reinterpret_cast<const char*>(str_data_ptr);
2636 return true;
2637}
2638
2639bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2640 uint32_t method_access_flags,
2641 uint32_t class_access_flags,
2642 bool has_code,
2643 bool expect_direct,
2644 std::string* error_msg) {
2645 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2646 constexpr uint32_t kAllMethodFlags =
2647 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2648 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002649 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
2650 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2651 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002652 return false;
2653 }
2654
2655 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2656 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2657 kAccPrivate |
2658 kAccProtected |
2659 kAccStatic |
2660 kAccFinal |
2661 kAccSynthetic |
2662 kAccSynchronized |
2663 kAccBridge |
2664 kAccVarargs |
2665 kAccNative |
2666 kAccAbstract |
2667 kAccStrict;
2668
2669 // Methods may have only one of public/protected/final.
2670 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002671 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
2672 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002673 method_access_flags);
2674 return false;
2675 }
2676
2677 // Try to find the name, to check for constructor properties.
2678 const char* str;
2679 if (!FindMethodName(method_index, begin_, header_, &str, error_msg)) {
2680 return false;
2681 }
2682 bool is_init_by_name = false;
2683 constexpr const char* kInitName = "<init>";
2684 size_t str_offset = (reinterpret_cast<const uint8_t*>(str) - begin_);
2685 if (header_->file_size_ - str_offset >= sizeof(kInitName)) {
2686 is_init_by_name = strcmp(kInitName, str) == 0;
2687 }
2688 bool is_clinit_by_name = false;
2689 constexpr const char* kClinitName = "<clinit>";
2690 if (header_->file_size_ - str_offset >= sizeof(kClinitName)) {
2691 is_clinit_by_name = strcmp(kClinitName, str) == 0;
2692 }
2693 bool is_constructor = is_init_by_name || is_clinit_by_name;
2694
2695 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2696 // the reverse for backwards compatibility reasons.
2697 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002698 *error_msg =
2699 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
2700 method_index,
2701 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002702 return false;
2703 }
2704 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2705 // instance constructor is called "<init>".
2706 if (is_constructor) {
2707 bool is_static = (method_access_flags & kAccStatic) != 0;
2708 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002709 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
2710 method_index,
2711 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002712 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2713 return false;
2714 } else {
2715 // Allow in older versions, but warn.
2716 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2717 << *error_msg;
2718 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002719 }
2720 }
2721 // Check that static and private methods, as well as constructors, are in the direct methods list,
2722 // and other methods in the virtual methods list.
2723 bool is_direct = (method_access_flags & (kAccStatic | kAccPrivate)) != 0 || is_constructor;
2724 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002725 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07002726 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002727 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002728 expect_direct);
2729 return false;
2730 }
2731
2732
2733 // From here on out it is easier to mask out the bits we're supposed to ignore.
2734 method_access_flags &= kMethodAccessFlags;
2735
Alex Lightd7c10c22016-03-31 10:03:07 -07002736 // Interfaces are special.
2737 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07002738 // Non-static interface methods must be public or private.
2739 uint32_t desired_flags = (kAccPublic | kAccStatic);
2740 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2741 desired_flags |= kAccPrivate;
2742 }
2743 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002744 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
2745 method_index,
2746 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002747 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002748 return false;
2749 } else {
2750 // Allow in older versions, but warn.
2751 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2752 << *error_msg;
2753 }
2754 }
2755 }
2756
Andreas Gampee6215c02015-08-31 18:54:38 -07002757 // If there aren't any instructions, make sure that's expected.
2758 if (!has_code) {
2759 // Only native or abstract methods may not have code.
2760 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002761 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07002762 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002763 method_index,
2764 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002765 return false;
2766 }
2767 // Constructors must always have code.
2768 if (is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002769 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
2770 method_index,
2771 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002772 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2773 return false;
2774 } else {
2775 // Allow in older versions, but warn.
2776 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2777 << *error_msg;
2778 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002779 }
2780 if ((method_access_flags & kAccAbstract) != 0) {
2781 // Abstract methods are not allowed to have the following flags.
2782 constexpr uint32_t kForbidden =
2783 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2784 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002785 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
2786 method_index,
2787 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2788 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002789 return false;
2790 }
Andreas Gampe97b11352015-12-10 16:23:41 -08002791 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07002792 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002793 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08002794 << " is abstract, but the declaring class is neither abstract nor an "
2795 << "interface in dex file "
2796 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07002797 }
2798 }
2799 // Interfaces are special.
2800 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002801 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07002802 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002803 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
2804 method_index,
2805 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002806 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002807 return false;
2808 } else {
2809 // Allow in older versions, but warn.
2810 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2811 << *error_msg;
2812 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002813 }
2814 // At this point, we know the method is public and abstract. This means that all the checks
2815 // for invalid combinations above applies. In addition, interface methods must not be
2816 // protected. This is caught by the check for only-one-of-public-protected-private.
2817 }
2818 return true;
2819 }
2820
2821 // When there's code, the method must not be native or abstract.
2822 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002823 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
2824 method_index,
2825 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002826 return false;
2827 }
2828
Andreas Gampee6215c02015-08-31 18:54:38 -07002829 // Instance constructors must not be synchronized and a few other flags.
2830 if (is_init_by_name) {
2831 static constexpr uint32_t kInitAllowed =
2832 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2833 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002834 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07002835 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002836 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002837 method_access_flags);
2838 return false;
2839 }
2840 }
2841
2842 return true;
2843}
2844
jeffhao10037c82012-01-23 15:06:23 -08002845} // namespace art