blob: a3ab9fa5bd000961b9d3a764bc55e9f1011eb441 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
jeffhao10037c82012-01-23 15:06:23 -080016
17#include "dex_file_verifier.h"
18
Andreas Gampee6215c02015-08-31 18:54:38 -070019#include <inttypes.h>
Narayan Kamath92572be2013-11-28 14:06:24 +000020#include <zlib.h>
Andreas Gampee6215c02015-08-31 18:54:38 -070021
David Sehr28e74ed2016-11-21 12:52:12 -080022#include <limits>
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Narayan Kamath92572be2013-11-28 14:06:24 +000024
Andreas Gampe46ee31b2016-12-14 10:11:49 -080025#include "android-base/stringprintf.h"
26
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "dex_file-inl.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070028#include "experimental_flags.h"
jeffhao10037c82012-01-23 15:06:23 -080029#include "leb128.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070030#include "safe_map.h"
Ian Rogersa6724902013-09-23 09:23:37 -070031#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "utils.h"
jeffhao10037c82012-01-23 15:06:23 -080033
34namespace art {
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036using android::base::StringAppendV;
37using android::base::StringPrintf;
38
David Sehr28e74ed2016-11-21 12:52:12 -080039static constexpr uint32_t kTypeIdLimit = std::numeric_limits<uint16_t>::max();
40
41static bool IsValidOrNoTypeId(uint16_t low, uint16_t high) {
42 return (high == 0) || ((high == 0xffffU) && (low == 0xffffU));
43}
44
45static bool IsValidTypeId(uint16_t low ATTRIBUTE_UNUSED, uint16_t high) {
46 return (high == 0);
47}
48
jeffhao10037c82012-01-23 15:06:23 -080049static uint32_t MapTypeToBitMask(uint32_t map_type) {
50 switch (map_type) {
51 case DexFile::kDexTypeHeaderItem: return 1 << 0;
52 case DexFile::kDexTypeStringIdItem: return 1 << 1;
53 case DexFile::kDexTypeTypeIdItem: return 1 << 2;
54 case DexFile::kDexTypeProtoIdItem: return 1 << 3;
55 case DexFile::kDexTypeFieldIdItem: return 1 << 4;
56 case DexFile::kDexTypeMethodIdItem: return 1 << 5;
57 case DexFile::kDexTypeClassDefItem: return 1 << 6;
58 case DexFile::kDexTypeMapList: return 1 << 7;
59 case DexFile::kDexTypeTypeList: return 1 << 8;
60 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9;
61 case DexFile::kDexTypeAnnotationSetItem: return 1 << 10;
62 case DexFile::kDexTypeClassDataItem: return 1 << 11;
63 case DexFile::kDexTypeCodeItem: return 1 << 12;
64 case DexFile::kDexTypeStringDataItem: return 1 << 13;
65 case DexFile::kDexTypeDebugInfoItem: return 1 << 14;
66 case DexFile::kDexTypeAnnotationItem: return 1 << 15;
67 case DexFile::kDexTypeEncodedArrayItem: return 1 << 16;
68 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17;
69 }
70 return 0;
71}
72
73static bool IsDataSectionType(uint32_t map_type) {
74 switch (map_type) {
75 case DexFile::kDexTypeHeaderItem:
76 case DexFile::kDexTypeStringIdItem:
77 case DexFile::kDexTypeTypeIdItem:
78 case DexFile::kDexTypeProtoIdItem:
79 case DexFile::kDexTypeFieldIdItem:
80 case DexFile::kDexTypeMethodIdItem:
81 case DexFile::kDexTypeClassDefItem:
82 return false;
83 }
84 return true;
85}
86
Andreas Gampe8a0128a2016-11-28 07:38:35 -080087const char* DexFileVerifier::CheckLoadStringByIdx(dex::StringIndex idx, const char* error_string) {
88 if (UNLIKELY(!CheckIndex(idx.index_, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070089 return nullptr;
90 }
91 return dex_file_->StringDataByIdx(idx);
92}
93
Andreas Gampea5b09a62016-11-17 15:21:22 -080094const char* DexFileVerifier::CheckLoadStringByTypeIdx(dex::TypeIndex type_idx,
95 const char* error_string) {
96 if (UNLIKELY(!CheckIndex(type_idx.index_, dex_file_->NumTypeIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070097 return nullptr;
98 }
Andreas Gampe8a0128a2016-11-28 07:38:35 -080099 return CheckLoadStringByIdx(dex_file_->GetTypeId(type_idx).descriptor_idx_, error_string);
Andreas Gampee09269c2014-06-06 18:45:35 -0700100}
101
102const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -0700103 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700104 return nullptr;
105 }
106 return &dex_file_->GetFieldId(idx);
107}
108
109const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -0700110 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700111 return nullptr;
112 }
113 return &dex_file_->GetMethodId(idx);
114}
115
116// Helper macro to load string and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700117#define LOAD_STRING(var, idx, error) \
118 const char* (var) = CheckLoadStringByIdx(idx, error); \
119 if (UNLIKELY((var) == nullptr)) { \
120 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700121 }
122
123// Helper macro to load string by type idx and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700124#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
125 const char* (var) = CheckLoadStringByTypeIdx(type_idx, error); \
126 if (UNLIKELY((var) == nullptr)) { \
127 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700128 }
129
130// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700131#define LOAD_METHOD(var, idx, error_string, error_stmt) \
132 const DexFile::MethodId* (var) = CheckLoadMethodId(idx, error_string); \
133 if (UNLIKELY((var) == nullptr)) { \
134 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700135 }
136
137// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700138#define LOAD_FIELD(var, idx, fmt, error_stmt) \
139 const DexFile::FieldId* (var) = CheckLoadFieldId(idx, fmt); \
140 if (UNLIKELY((var) == nullptr)) { \
141 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700142 }
143
Aart Bik37d6a3b2016-06-21 18:30:10 -0700144bool DexFileVerifier::Verify(const DexFile* dex_file,
145 const uint8_t* begin,
146 size_t size,
147 const char* location,
148 bool verify_checksum,
149 std::string* error_msg) {
150 std::unique_ptr<DexFileVerifier> verifier(
151 new DexFileVerifier(dex_file, begin, size, location, verify_checksum));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700152 if (!verifier->Verify()) {
153 *error_msg = verifier->FailureReason();
154 return false;
155 }
156 return true;
157}
158
159bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
160 bool is_return_type) {
jeffhao10037c82012-01-23 15:06:23 -0800161 switch (shorty_char) {
162 case 'V':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700163 if (UNLIKELY(!is_return_type)) {
164 ErrorStringPrintf("Invalid use of void");
jeffhao10037c82012-01-23 15:06:23 -0800165 return false;
166 }
Ian Rogersfc787ec2014-10-09 21:56:44 -0700167 FALLTHROUGH_INTENDED;
jeffhao10037c82012-01-23 15:06:23 -0800168 case 'B':
169 case 'C':
170 case 'D':
171 case 'F':
172 case 'I':
173 case 'J':
174 case 'S':
175 case 'Z':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700176 if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
177 ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
178 shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800179 return false;
180 }
181 break;
182 case 'L':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700183 if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
184 ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800185 return false;
186 }
187 break;
188 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700189 ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
jeffhao10037c82012-01-23 15:06:23 -0800190 return false;
191 }
192 return true;
193}
194
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700195bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700196 const char* label) {
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700197 // Check that size is not 0.
198 CHECK_NE(elem_size, 0U);
199
Ian Rogers13735952014-10-08 12:43:28 -0700200 const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
201 const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700202
203 // Check for overflow.
204 uintptr_t max = 0 - 1;
205 size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
206 size_t max_count = available_bytes_till_end_of_mem / elem_size;
207 if (max_count < count) {
208 ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
209 static_cast<size_t>(range_start - file_start),
210 count, elem_size);
211 return false;
212 }
213
Ian Rogers13735952014-10-08 12:43:28 -0700214 const uint8_t* range_end = range_start + count * elem_size;
215 const uint8_t* file_end = file_start + size_;
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700216 if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
217 // Note: these two tests are enough as we make sure above that there's no overflow.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800218 ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
Ian Rogerse3d55812014-06-11 13:00:44 -0700219 static_cast<size_t>(range_start - file_start),
220 static_cast<size_t>(range_end - file_start));
jeffhao10037c82012-01-23 15:06:23 -0800221 return false;
222 }
223 return true;
224}
225
Ian Rogers13735952014-10-08 12:43:28 -0700226bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700227 // Check that the list is available. The first 4B are the count.
228 if (!CheckListSize(*ptr, 1, 4U, label)) {
229 return false;
230 }
231
232 uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
233 if (count > 0) {
234 if (!CheckListSize(*ptr + 4, count, element_size, label)) {
235 return false;
236 }
237 }
238
239 *ptr += 4 + count * element_size;
240 return true;
241}
242
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700243bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
244 if (UNLIKELY(field >= limit)) {
245 ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
jeffhao10037c82012-01-23 15:06:23 -0800246 return false;
247 }
248 return true;
249}
250
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800251bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
252 uint32_t size,
253 size_t alignment,
254 const char* label) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700255 if (size == 0) {
256 if (offset != 0) {
257 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
258 return false;
259 }
260 }
261 if (size_ <= offset) {
262 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
263 return false;
264 }
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800265 if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
266 ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
267 return false;
268 }
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700269 return true;
270}
271
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100272bool DexFileVerifier::CheckSizeLimit(uint32_t size, uint32_t limit, const char* label) {
273 if (size > limit) {
274 ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label);
275 return false;
276 }
277 return true;
278}
279
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700280bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800281 // Check file size from the header.
282 uint32_t expected_size = header_->file_size_;
283 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700284 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800285 return false;
286 }
287
288 // Compute and verify the checksum in the header.
289 uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
290 const uint32_t non_sum = sizeof(header_->magic_) + sizeof(header_->checksum_);
Ian Rogers13735952014-10-08 12:43:28 -0700291 const uint8_t* non_sum_ptr = reinterpret_cast<const uint8_t*>(header_) + non_sum;
jeffhaof6174e82012-01-31 16:14:17 -0800292 adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
jeffhao10037c82012-01-23 15:06:23 -0800293 if (adler_checksum != header_->checksum_) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700294 if (verify_checksum_) {
295 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
296 return false;
297 } else {
298 LOG(WARNING) << StringPrintf(
299 "Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
300 }
jeffhao10037c82012-01-23 15:06:23 -0800301 }
302
303 // Check the contents of the header.
304 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700305 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800306 return false;
307 }
308
309 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700310 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800311 return false;
312 }
313
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700314 // Check that all offsets are inside the file.
315 bool result =
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800316 CheckValidOffsetAndSize(header_->link_off_,
317 header_->link_size_,
318 0 /* unaligned */,
319 "link") &&
320 CheckValidOffsetAndSize(header_->map_off_,
321 header_->map_off_,
322 4,
323 "map") &&
324 CheckValidOffsetAndSize(header_->string_ids_off_,
325 header_->string_ids_size_,
326 4,
327 "string-ids") &&
328 CheckValidOffsetAndSize(header_->type_ids_off_,
329 header_->type_ids_size_,
330 4,
331 "type-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100332 CheckSizeLimit(header_->type_ids_size_, DexFile::kDexNoIndex16, "type-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800333 CheckValidOffsetAndSize(header_->proto_ids_off_,
334 header_->proto_ids_size_,
335 4,
336 "proto-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100337 CheckSizeLimit(header_->proto_ids_size_, DexFile::kDexNoIndex16, "proto-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800338 CheckValidOffsetAndSize(header_->field_ids_off_,
339 header_->field_ids_size_,
340 4,
341 "field-ids") &&
342 CheckValidOffsetAndSize(header_->method_ids_off_,
343 header_->method_ids_size_,
344 4,
345 "method-ids") &&
346 CheckValidOffsetAndSize(header_->class_defs_off_,
347 header_->class_defs_size_,
348 4,
349 "class-defs") &&
350 CheckValidOffsetAndSize(header_->data_off_,
351 header_->data_size_,
352 0, // Unaligned, spec doesn't talk about it, even though size
353 // is supposed to be a multiple of 4.
354 "data");
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700355 return result;
jeffhao10037c82012-01-23 15:06:23 -0800356}
357
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700358bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700359 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
360 header_->map_off_);
361 // Check that map list content is available.
362 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
363 return false;
364 }
365
jeffhao10037c82012-01-23 15:06:23 -0800366 const DexFile::MapItem* item = map->list_;
367
368 uint32_t count = map->size_;
369 uint32_t last_offset = 0;
370 uint32_t data_item_count = 0;
371 uint32_t data_items_left = header_->data_size_;
372 uint32_t used_bits = 0;
373
374 // Sanity check the size of the map list.
375 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
376 return false;
377 }
378
379 // Check the items listed in the map.
380 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700381 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
382 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800383 return false;
384 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700385 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
386 ErrorStringPrintf("Map item after end of file: %x, size %x",
387 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800388 return false;
389 }
390
391 if (IsDataSectionType(item->type_)) {
392 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700393 if (UNLIKELY(icount > data_items_left)) {
394 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800395 return false;
396 }
397 data_items_left -= icount;
398 data_item_count += icount;
399 }
400
401 uint32_t bit = MapTypeToBitMask(item->type_);
402
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700403 if (UNLIKELY(bit == 0)) {
404 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800405 return false;
406 }
407
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700408 if (UNLIKELY((used_bits & bit) != 0)) {
409 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800410 return false;
411 }
412
413 used_bits |= bit;
414 last_offset = item->offset_;
415 item++;
416 }
417
418 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700419 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
420 ErrorStringPrintf("Map is missing header 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::kDexTypeMapList)) == 0)) {
424 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800425 return false;
426 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700427 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
428 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
429 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800430 return false;
431 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700432 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
433 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
434 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800435 return false;
436 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700437 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
438 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
439 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800440 return false;
441 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700442 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
443 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
444 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800445 return false;
446 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700447 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
448 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
449 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800450 return false;
451 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700452 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
453 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
454 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800455 return false;
456 }
jeffhao10037c82012-01-23 15:06:23 -0800457 return true;
458}
459
460uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
461 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700462 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700463 for (uint32_t i = 0; i < size; i++) {
464 result |= ((uint32_t) *(ptr_++)) << (i * 8);
465 }
jeffhao10037c82012-01-23 15:06:23 -0800466 }
jeffhao10037c82012-01-23 15:06:23 -0800467 return result;
468}
469
Andreas Gampebed6daf2016-09-02 18:12:00 -0700470
471#define DECODE_UNSIGNED_CHECKED_FROM_WITH_ERROR_VALUE(ptr, var, error_value) \
472 uint32_t var; \
Andreas Gampe44fd2352016-11-03 08:21:21 -0700473 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700474 return error_value; \
475 }
476
Andreas Gampe44fd2352016-11-03 08:21:21 -0700477#define DECODE_UNSIGNED_CHECKED_FROM(ptr, var) \
478 uint32_t var; \
479 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
480 ErrorStringPrintf("Read out of bounds"); \
481 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700482 }
483
Andreas Gampe44fd2352016-11-03 08:21:21 -0700484#define DECODE_SIGNED_CHECKED_FROM(ptr, var) \
485 int32_t var; \
486 if (!DecodeSignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
487 ErrorStringPrintf("Read out of bounds"); \
488 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700489 }
490
jeffhao10037c82012-01-23 15:06:23 -0800491bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700492 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700493 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800494
495 for (uint32_t i = 0; i < handlers_size; i++) {
496 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800497 size_t offset = ptr_ - handlers_base;
Andreas Gampebed6daf2016-09-02 18:12:00 -0700498 DECODE_SIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800499
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700500 if (UNLIKELY((size < -65536) || (size > 65536))) {
501 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800502 return false;
503 }
504
505 if (size <= 0) {
506 catch_all = true;
507 size = -size;
508 } else {
509 catch_all = false;
510 }
511
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800512 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800513
514 while (size-- > 0) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700515 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -0800516 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
517 return false;
518 }
519
Andreas Gampebed6daf2016-09-02 18:12:00 -0700520 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700521 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
522 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800523 return false;
524 }
525 }
526
527 if (catch_all) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700528 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700529 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
530 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800531 return false;
532 }
533 }
534 }
535
536 return true;
537}
538
Andreas Gampee6215c02015-08-31 18:54:38 -0700539bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
540 uint32_t access_flags,
541 uint32_t class_access_flags,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800542 dex::TypeIndex class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700543 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700544 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800545 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
546 return false;
547 }
548
Andreas Gampee6215c02015-08-31 18:54:38 -0700549 // Check that it's the right class.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800550 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700551 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
552 class_idx_;
553 if (class_type_index != my_class_index) {
554 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800555 my_class_index.index_,
556 class_type_index.index_);
Andreas Gampee6215c02015-08-31 18:54:38 -0700557 return false;
558 }
559
560 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800561 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700562 if (UNLIKELY(is_static != expect_static)) {
563 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800564 return false;
565 }
566
Andreas Gampee6215c02015-08-31 18:54:38 -0700567 // Check field access flags.
568 std::string error_msg;
Andreas Gampec9f0ba12016-02-09 09:21:04 -0800569 if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700570 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800571 return false;
572 }
573
574 return true;
575}
576
Andreas Gampee6215c02015-08-31 18:54:38 -0700577bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
578 uint32_t access_flags,
579 uint32_t class_access_flags,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800580 dex::TypeIndex class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700581 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700582 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700583 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700584 DCHECK(direct_method_indexes != nullptr);
585 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800586 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
587 return false;
588 }
589
Andreas Gampee6215c02015-08-31 18:54:38 -0700590 // Check that it's the right class.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800591 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700592 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
593 class_idx_;
594 if (class_type_index != my_class_index) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700595 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 " vs %" PRIu16,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800596 my_class_index.index_,
597 class_type_index.index_);
jeffhao10037c82012-01-23 15:06:23 -0800598 return false;
599 }
600
Andreas Gampee6215c02015-08-31 18:54:38 -0700601 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700602 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700603 direct_method_indexes->insert(idx);
604 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700605 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
606 return false;
607 }
608
Andreas Gampee6215c02015-08-31 18:54:38 -0700609 // Check method access flags.
610 bool has_code = (code_offset != 0);
611 std::string error_msg;
612 if (!CheckMethodAccessFlags(idx,
613 access_flags,
614 class_access_flags,
615 has_code,
616 expect_direct,
617 &error_msg)) {
618 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800619 return false;
620 }
621
622 return true;
623}
624
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800625bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800626 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700627 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800628 return false;
629 }
630 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700631 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800632 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800633 return false;
634 }
635 ptr_++;
636 offset++;
637 }
638 }
639 return true;
640}
641
642bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700643 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800644 return false;
645 }
646
647 uint8_t header_byte = *(ptr_++);
648 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
649 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
650
651 switch (value_type) {
652 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700653 if (UNLIKELY(value_arg != 0)) {
654 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800655 return false;
656 }
657 ptr_++;
658 break;
659 case DexFile::kDexAnnotationShort:
660 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700661 if (UNLIKELY(value_arg > 1)) {
662 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800663 return false;
664 }
665 ptr_ += value_arg + 1;
666 break;
667 case DexFile::kDexAnnotationInt:
668 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700669 if (UNLIKELY(value_arg > 3)) {
670 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800671 return false;
672 }
673 ptr_ += value_arg + 1;
674 break;
675 case DexFile::kDexAnnotationLong:
676 case DexFile::kDexAnnotationDouble:
677 ptr_ += value_arg + 1;
678 break;
679 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700680 if (UNLIKELY(value_arg > 3)) {
681 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800682 return false;
683 }
684 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
685 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
686 return false;
687 }
688 break;
689 }
690 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700691 if (UNLIKELY(value_arg > 3)) {
692 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800693 return false;
694 }
695 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
696 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
697 return false;
698 }
699 break;
700 }
701 case DexFile::kDexAnnotationField:
702 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700703 if (UNLIKELY(value_arg > 3)) {
704 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800705 return false;
706 }
707 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
708 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
709 return false;
710 }
711 break;
712 }
713 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700714 if (UNLIKELY(value_arg > 3)) {
715 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800716 return false;
717 }
718 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
719 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
720 return false;
721 }
722 break;
723 }
724 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700725 if (UNLIKELY(value_arg != 0)) {
726 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800727 return false;
728 }
729 if (!CheckEncodedArray()) {
730 return false;
731 }
732 break;
733 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700734 if (UNLIKELY(value_arg != 0)) {
735 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800736 return false;
737 }
738 if (!CheckEncodedAnnotation()) {
739 return false;
740 }
741 break;
742 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700743 if (UNLIKELY(value_arg != 0)) {
744 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800745 return false;
746 }
747 break;
748 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700749 if (UNLIKELY(value_arg > 1)) {
750 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800751 return false;
752 }
753 break;
754 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700755 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800756 return false;
757 }
758
759 return true;
760}
761
762bool DexFileVerifier::CheckEncodedArray() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700763 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800764
765 while (size--) {
766 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700767 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800768 return false;
769 }
770 }
771 return true;
772}
773
774bool DexFileVerifier::CheckEncodedAnnotation() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700775 DECODE_UNSIGNED_CHECKED_FROM(ptr_, anno_idx);
776 if (!CheckIndex(anno_idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -0800777 return false;
778 }
779
Andreas Gampebed6daf2016-09-02 18:12:00 -0700780 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800781 uint32_t last_idx = 0;
782
783 for (uint32_t i = 0; i < size; i++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700784 DECODE_UNSIGNED_CHECKED_FROM(ptr_, idx);
jeffhao10037c82012-01-23 15:06:23 -0800785 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
786 return false;
787 }
788
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700789 if (UNLIKELY(last_idx >= idx && i != 0)) {
790 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
791 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800792 return false;
793 }
794
795 if (!CheckEncodedValue()) {
796 return false;
797 }
798
799 last_idx = idx;
800 }
801 return true;
802}
803
Andreas Gampee6215c02015-08-31 18:54:38 -0700804bool DexFileVerifier::FindClassFlags(uint32_t index,
805 bool is_field,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800806 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700807 uint32_t* class_access_flags) {
808 DCHECK(class_type_index != nullptr);
809 DCHECK(class_access_flags != nullptr);
810
811 // First check if the index is valid.
812 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
813 return false;
814 }
815
816 // Next get the type index.
817 if (is_field) {
818 *class_type_index =
819 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
820 class_idx_;
821 } else {
822 *class_type_index =
823 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
824 class_idx_;
825 }
826
827 // Check if that is valid.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800828 if (class_type_index->index_ >= header_->type_ids_size_) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700829 return false;
830 }
831
832 // Now search for the class def. This is basically a specialized version of the DexFile code, as
833 // we should not trust that this is a valid DexFile just yet.
834 const DexFile::ClassDef* class_def_begin =
835 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
836 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
837 const DexFile::ClassDef* class_def = class_def_begin + i;
838 if (class_def->class_idx_ == *class_type_index) {
839 *class_access_flags = class_def->access_flags_;
840 return true;
841 }
842 }
843
844 // Didn't find the class-def, not defined here...
845 return false;
846}
847
848bool DexFileVerifier::CheckOrderAndGetClassFlags(bool is_field,
849 const char* type_descr,
850 uint32_t curr_index,
851 uint32_t prev_index,
852 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800853 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700854 uint32_t* class_access_flags) {
855 if (curr_index < prev_index) {
856 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
857 type_descr,
858 prev_index,
859 curr_index);
860 return false;
861 }
862
863 if (!*have_class) {
864 *have_class = FindClassFlags(curr_index, is_field, class_type_index, class_access_flags);
865 if (!*have_class) {
866 // Should have really found one.
867 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
868 type_descr,
869 curr_index);
870 return false;
871 }
872 }
873 return true;
874}
875
876template <bool kStatic>
877bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
878 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800879 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700880 uint32_t* class_access_flags) {
881 DCHECK(it != nullptr);
882 // These calls use the raw access flags to check whether the whole dex field is valid.
883 uint32_t prev_index = 0;
884 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
885 uint32_t curr_index = it->GetMemberIndex();
886 if (!CheckOrderAndGetClassFlags(true,
887 kStatic ? "static field" : "instance field",
888 curr_index,
889 prev_index,
890 have_class,
891 class_type_index,
892 class_access_flags)) {
893 return false;
894 }
895 prev_index = curr_index;
896
897 if (!CheckClassDataItemField(curr_index,
898 it->GetRawMemberAccessFlags(),
899 *class_access_flags,
900 *class_type_index,
901 kStatic)) {
902 return false;
903 }
904 }
905
906 return true;
907}
908
909template <bool kDirect>
910bool DexFileVerifier::CheckIntraClassDataItemMethods(
911 ClassDataItemIterator* it,
912 std::unordered_set<uint32_t>* direct_method_indexes,
913 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800914 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700915 uint32_t* class_access_flags) {
916 uint32_t prev_index = 0;
917 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
918 uint32_t curr_index = it->GetMemberIndex();
919 if (!CheckOrderAndGetClassFlags(false,
920 kDirect ? "direct method" : "virtual method",
921 curr_index,
922 prev_index,
923 have_class,
924 class_type_index,
925 class_access_flags)) {
926 return false;
927 }
928 prev_index = curr_index;
929
930 if (!CheckClassDataItemMethod(curr_index,
931 it->GetRawMemberAccessFlags(),
932 *class_access_flags,
933 *class_type_index,
934 it->GetMethodCodeItemOffset(),
935 direct_method_indexes,
936 kDirect)) {
937 return false;
938 }
939 }
940
941 return true;
942}
943
jeffhao10037c82012-01-23 15:06:23 -0800944bool DexFileVerifier::CheckIntraClassDataItem() {
945 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -0700946 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -0800947
Andreas Gampee6215c02015-08-31 18:54:38 -0700948 // This code is complicated by the fact that we don't directly know which class this belongs to.
949 // So we need to explicitly search with the first item we find (either field or method), and then,
950 // as the lookup is expensive, cache the result.
951 bool have_class = false;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800952 dex::TypeIndex class_type_index;
Andreas Gampee6215c02015-08-31 18:54:38 -0700953 uint32_t class_access_flags;
954
955 // Check fields.
956 if (!CheckIntraClassDataItemFields<true>(&it,
957 &have_class,
958 &class_type_index,
959 &class_access_flags)) {
960 return false;
jeffhao10037c82012-01-23 15:06:23 -0800961 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700962 if (!CheckIntraClassDataItemFields<false>(&it,
963 &have_class,
964 &class_type_index,
965 &class_access_flags)) {
966 return false;
jeffhao10037c82012-01-23 15:06:23 -0800967 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700968
969 // Check methods.
970 if (!CheckIntraClassDataItemMethods<true>(&it,
971 &direct_method_indexes,
972 &have_class,
973 &class_type_index,
974 &class_access_flags)) {
975 return false;
jeffhao10037c82012-01-23 15:06:23 -0800976 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700977 if (!CheckIntraClassDataItemMethods<false>(&it,
978 &direct_method_indexes,
979 &have_class,
980 &class_type_index,
981 &class_access_flags)) {
982 return false;
jeffhao10037c82012-01-23 15:06:23 -0800983 }
984
985 ptr_ = it.EndDataPointer();
986 return true;
987}
988
989bool DexFileVerifier::CheckIntraCodeItem() {
990 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700991 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -0800992 return false;
993 }
994
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700995 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
996 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
997 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800998 return false;
999 }
1000
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001001 if (UNLIKELY((code_item->outs_size_ > 5) &&
1002 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -08001003 /*
1004 * outs_size can be up to 5, even if registers_size is smaller, since the
1005 * short forms of method invocation allow repetitions of a register multiple
1006 * times within a single parameter list. However, longer parameter lists
1007 * need to be represented in-order in the register file.
1008 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001009 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
1010 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -08001011 return false;
1012 }
1013
1014 const uint16_t* insns = code_item->insns_;
1015 uint32_t insns_size = code_item->insns_size_in_code_units_;
1016 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
1017 return false;
1018 }
1019
1020 // Grab the end of the insns if there are no try_items.
1021 uint32_t try_items_size = code_item->tries_size_;
1022 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001023 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001024 return true;
1025 }
1026
1027 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001028 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001029 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001030 return false;
1031 }
1032
1033 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -08001034 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
1035 return false;
1036 }
1037
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001038 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
Andreas Gampebed6daf2016-09-02 18:12:00 -07001039 DECODE_UNSIGNED_CHECKED_FROM(ptr_, handlers_size);
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001040
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001041 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
1042 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -08001043 return false;
1044 }
1045
Ian Rogers700a4022014-05-19 16:49:03 -07001046 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -07001047 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -08001048 return false;
1049 }
1050
1051 uint32_t last_addr = 0;
1052 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001053 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1054 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001055 return false;
1056 }
1057
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001058 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1059 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001060 return false;
1061 }
1062
1063 uint32_t i;
1064 for (i = 0; i < handlers_size; i++) {
1065 if (try_items->handler_off_ == handler_offsets[i]) {
1066 break;
1067 }
1068 }
1069
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001070 if (UNLIKELY(i == handlers_size)) {
1071 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -08001072 return false;
1073 }
1074
1075 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001076 if (UNLIKELY(last_addr > insns_size)) {
1077 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -08001078 return false;
1079 }
1080
1081 try_items++;
1082 }
1083
1084 return true;
1085}
1086
1087bool DexFileVerifier::CheckIntraStringDataItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001088 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
Ian Rogers13735952014-10-08 12:43:28 -07001089 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001090
1091 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001092 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001093 if (UNLIKELY(ptr_ >= file_end)) {
1094 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001095 return false;
1096 }
1097
1098 uint8_t byte = *(ptr_++);
1099
1100 // Switch on the high 4 bits.
1101 switch (byte >> 4) {
1102 case 0x00:
1103 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001104 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001105 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001106 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001107 return false;
1108 }
1109 break;
1110 case 0x01:
1111 case 0x02:
1112 case 0x03:
1113 case 0x04:
1114 case 0x05:
1115 case 0x06:
1116 case 0x07:
1117 // No extra checks necessary for bit pattern 0xxx.
1118 break;
1119 case 0x08:
1120 case 0x09:
1121 case 0x0a:
1122 case 0x0b:
1123 case 0x0f:
1124 // Illegal bit patterns 10xx or 1111.
1125 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001126 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001127 return false;
1128 case 0x0c:
1129 case 0x0d: {
1130 // Bit pattern 110x has an additional byte.
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 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001137 if (UNLIKELY((value != 0) && (value < 0x80))) {
1138 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001139 return false;
1140 }
1141 break;
1142 }
1143 case 0x0e: {
1144 // Bit pattern 1110 has 2 additional bytes.
1145 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001146 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1147 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001148 return false;
1149 }
1150 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001151 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1152 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001153 return false;
1154 }
1155 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001156 if (UNLIKELY(value < 0x800)) {
1157 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001158 return false;
1159 }
1160 break;
1161 }
1162 }
1163 }
1164
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001165 if (UNLIKELY(*(ptr_++) != '\0')) {
1166 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001167 return false;
1168 }
1169
1170 return true;
1171}
1172
1173bool DexFileVerifier::CheckIntraDebugInfoItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001174 DECODE_UNSIGNED_CHECKED_FROM(ptr_, dummy);
1175 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameters_size);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001176 if (UNLIKELY(parameters_size > 65536)) {
1177 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001178 return false;
1179 }
1180
1181 for (uint32_t j = 0; j < parameters_size; j++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001182 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameter_name);
jeffhao10037c82012-01-23 15:06:23 -08001183 if (parameter_name != 0) {
1184 parameter_name--;
1185 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1186 return false;
1187 }
1188 }
1189 }
1190
1191 while (true) {
1192 uint8_t opcode = *(ptr_++);
1193 switch (opcode) {
1194 case DexFile::DBG_END_SEQUENCE: {
1195 return true;
1196 }
1197 case DexFile::DBG_ADVANCE_PC: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001198 DECODE_UNSIGNED_CHECKED_FROM(ptr_, advance_pc_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001199 break;
1200 }
1201 case DexFile::DBG_ADVANCE_LINE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001202 DECODE_SIGNED_CHECKED_FROM(ptr_, advance_line_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001203 break;
1204 }
1205 case DexFile::DBG_START_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001206 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001207 if (UNLIKELY(reg_num >= 65536)) {
1208 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001209 return false;
1210 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001211 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001212 if (name_idx != 0) {
1213 name_idx--;
1214 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1215 return false;
1216 }
1217 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001218 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001219 if (type_idx != 0) {
1220 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001221 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001222 return false;
1223 }
1224 }
1225 break;
1226 }
1227 case DexFile::DBG_END_LOCAL:
1228 case DexFile::DBG_RESTART_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001229 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001230 if (UNLIKELY(reg_num >= 65536)) {
1231 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001232 return false;
1233 }
1234 break;
1235 }
1236 case DexFile::DBG_START_LOCAL_EXTENDED: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001237 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001238 if (UNLIKELY(reg_num >= 65536)) {
1239 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001240 return false;
1241 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001242 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001243 if (name_idx != 0) {
1244 name_idx--;
1245 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1246 return false;
1247 }
1248 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001249 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001250 if (type_idx != 0) {
1251 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001252 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001253 return false;
1254 }
1255 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001256 DECODE_UNSIGNED_CHECKED_FROM(ptr_, sig_idx);
jeffhao10037c82012-01-23 15:06:23 -08001257 if (sig_idx != 0) {
1258 sig_idx--;
1259 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1260 return false;
1261 }
1262 }
1263 break;
1264 }
1265 case DexFile::DBG_SET_FILE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001266 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001267 if (name_idx != 0) {
1268 name_idx--;
1269 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1270 return false;
1271 }
1272 }
1273 break;
1274 }
1275 }
1276 }
1277}
1278
1279bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001280 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001281 return false;
1282 }
1283
1284 // Check visibility
1285 switch (*(ptr_++)) {
1286 case DexFile::kDexVisibilityBuild:
1287 case DexFile::kDexVisibilityRuntime:
1288 case DexFile::kDexVisibilitySystem:
1289 break;
1290 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001291 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001292 return false;
1293 }
1294
1295 if (!CheckEncodedAnnotation()) {
1296 return false;
1297 }
1298
1299 return true;
1300}
1301
1302bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1303 const DexFile::AnnotationsDirectoryItem* item =
1304 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001305 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001306 return false;
1307 }
1308
1309 // Field annotations follow immediately after the annotations directory.
1310 const DexFile::FieldAnnotationsItem* field_item =
1311 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1312 uint32_t field_count = item->fields_size_;
1313 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1314 return false;
1315 }
1316
1317 uint32_t last_idx = 0;
1318 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001319 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1320 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001321 return false;
1322 }
1323 last_idx = field_item->field_idx_;
1324 field_item++;
1325 }
1326
1327 // Method annotations follow immediately after field annotations.
1328 const DexFile::MethodAnnotationsItem* method_item =
1329 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1330 uint32_t method_count = item->methods_size_;
1331 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1332 return false;
1333 }
1334
1335 last_idx = 0;
1336 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001337 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1338 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1339 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001340 return false;
1341 }
1342 last_idx = method_item->method_idx_;
1343 method_item++;
1344 }
1345
1346 // Parameter annotations follow immediately after method annotations.
1347 const DexFile::ParameterAnnotationsItem* parameter_item =
1348 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1349 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001350 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001351 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001352 return false;
1353 }
1354
1355 last_idx = 0;
1356 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001357 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1358 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1359 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001360 return false;
1361 }
1362 last_idx = parameter_item->method_idx_;
1363 parameter_item++;
1364 }
1365
1366 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001367 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001368 return true;
1369}
1370
Andreas Gampeb061cc12014-09-02 10:22:20 -07001371bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
1372 uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001373 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001374 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001375 switch (type) {
1376 case DexFile::kDexTypeClassDataItem:
1377 case DexFile::kDexTypeStringDataItem:
1378 case DexFile::kDexTypeDebugInfoItem:
1379 case DexFile::kDexTypeAnnotationItem:
1380 case DexFile::kDexTypeEncodedArrayItem:
1381 alignment_mask = sizeof(uint8_t) - 1;
1382 break;
1383 default:
1384 alignment_mask = sizeof(uint32_t) - 1;
1385 break;
1386 }
1387
1388 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001389 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001390 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001391
1392 // Check the padding between items.
1393 if (!CheckPadding(offset, aligned_offset)) {
1394 return false;
1395 }
1396
1397 // Check depending on the section type.
1398 switch (type) {
1399 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001400 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001401 return false;
1402 }
1403 ptr_ += sizeof(DexFile::StringId);
1404 break;
1405 }
1406 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001407 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001408 return false;
1409 }
1410 ptr_ += sizeof(DexFile::TypeId);
1411 break;
1412 }
1413 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001414 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001415 return false;
1416 }
1417 ptr_ += sizeof(DexFile::ProtoId);
1418 break;
1419 }
1420 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001421 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001422 return false;
1423 }
1424 ptr_ += sizeof(DexFile::FieldId);
1425 break;
1426 }
1427 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001428 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001429 return false;
1430 }
1431 ptr_ += sizeof(DexFile::MethodId);
1432 break;
1433 }
1434 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001435 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001436 return false;
1437 }
1438 ptr_ += sizeof(DexFile::ClassDef);
1439 break;
1440 }
1441 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001442 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001443 return false;
1444 }
jeffhao10037c82012-01-23 15:06:23 -08001445 break;
1446 }
1447 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001448 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001449 return false;
1450 }
jeffhao10037c82012-01-23 15:06:23 -08001451 break;
1452 }
1453 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001454 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001455 return false;
1456 }
jeffhao10037c82012-01-23 15:06:23 -08001457 break;
1458 }
1459 case DexFile::kDexTypeClassDataItem: {
1460 if (!CheckIntraClassDataItem()) {
1461 return false;
1462 }
1463 break;
1464 }
1465 case DexFile::kDexTypeCodeItem: {
1466 if (!CheckIntraCodeItem()) {
1467 return false;
1468 }
1469 break;
1470 }
1471 case DexFile::kDexTypeStringDataItem: {
1472 if (!CheckIntraStringDataItem()) {
1473 return false;
1474 }
1475 break;
1476 }
1477 case DexFile::kDexTypeDebugInfoItem: {
1478 if (!CheckIntraDebugInfoItem()) {
1479 return false;
1480 }
1481 break;
1482 }
1483 case DexFile::kDexTypeAnnotationItem: {
1484 if (!CheckIntraAnnotationItem()) {
1485 return false;
1486 }
1487 break;
1488 }
1489 case DexFile::kDexTypeEncodedArrayItem: {
1490 if (!CheckEncodedArray()) {
1491 return false;
1492 }
1493 break;
1494 }
1495 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1496 if (!CheckIntraAnnotationsDirectoryItem()) {
1497 return false;
1498 }
1499 break;
1500 }
1501 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001502 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001503 return false;
1504 }
1505
1506 if (IsDataSectionType(type)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001507 if (aligned_offset == 0u) {
1508 ErrorStringPrintf("Item %d offset is 0", i);
1509 return false;
1510 }
1511 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1512 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001513 }
1514
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001515 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001516 if (UNLIKELY(aligned_offset > size_)) {
1517 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001518 return false;
1519 }
1520
1521 offset = aligned_offset;
1522 }
1523
1524 return true;
1525}
1526
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001527bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001528 uint32_t expected_offset;
1529 uint32_t expected_size;
1530
1531 // Get the expected offset and size from the header.
1532 switch (type) {
1533 case DexFile::kDexTypeStringIdItem:
1534 expected_offset = header_->string_ids_off_;
1535 expected_size = header_->string_ids_size_;
1536 break;
1537 case DexFile::kDexTypeTypeIdItem:
1538 expected_offset = header_->type_ids_off_;
1539 expected_size = header_->type_ids_size_;
1540 break;
1541 case DexFile::kDexTypeProtoIdItem:
1542 expected_offset = header_->proto_ids_off_;
1543 expected_size = header_->proto_ids_size_;
1544 break;
1545 case DexFile::kDexTypeFieldIdItem:
1546 expected_offset = header_->field_ids_off_;
1547 expected_size = header_->field_ids_size_;
1548 break;
1549 case DexFile::kDexTypeMethodIdItem:
1550 expected_offset = header_->method_ids_off_;
1551 expected_size = header_->method_ids_size_;
1552 break;
1553 case DexFile::kDexTypeClassDefItem:
1554 expected_offset = header_->class_defs_off_;
1555 expected_size = header_->class_defs_size_;
1556 break;
1557 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001558 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001559 return false;
1560 }
1561
1562 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001563 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001564 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001565 return false;
1566 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001567 if (UNLIKELY(count != expected_size)) {
1568 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001569 return false;
1570 }
1571
1572 return CheckIntraSectionIterate(offset, count, type);
1573}
1574
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001575bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count, uint16_t type) {
1576 size_t data_start = header_->data_off_;
1577 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001578
1579 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001580 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001581 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001582 return false;
1583 }
1584
1585 if (!CheckIntraSectionIterate(offset, count, type)) {
1586 return false;
1587 }
1588
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001589 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001590 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001591 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001592 return false;
1593 }
1594
1595 return true;
1596}
1597
1598bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001599 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001600 const DexFile::MapItem* item = map->list_;
1601
1602 uint32_t count = map->size_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001603 size_t offset = 0;
Ian Rogers30fab402012-01-23 15:43:46 -08001604 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001605
1606 // Check the items listed in the map.
1607 while (count--) {
1608 uint32_t section_offset = item->offset_;
1609 uint32_t section_count = item->size_;
1610 uint16_t type = item->type_;
1611
1612 // Check for padding and overlap between items.
1613 if (!CheckPadding(offset, section_offset)) {
1614 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001615 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001616 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001617 return false;
1618 }
1619
1620 // Check each item based on its type.
1621 switch (type) {
1622 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001623 if (UNLIKELY(section_count != 1)) {
1624 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001625 return false;
1626 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001627 if (UNLIKELY(section_offset != 0)) {
1628 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001629 return false;
1630 }
Ian Rogers30fab402012-01-23 15:43:46 -08001631 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001632 offset = header_->header_size_;
1633 break;
1634 case DexFile::kDexTypeStringIdItem:
1635 case DexFile::kDexTypeTypeIdItem:
1636 case DexFile::kDexTypeProtoIdItem:
1637 case DexFile::kDexTypeFieldIdItem:
1638 case DexFile::kDexTypeMethodIdItem:
1639 case DexFile::kDexTypeClassDefItem:
1640 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1641 return false;
1642 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001643 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001644 break;
1645 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001646 if (UNLIKELY(section_count != 1)) {
1647 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001648 return false;
1649 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001650 if (UNLIKELY(section_offset != header_->map_off_)) {
1651 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1652 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001653 return false;
1654 }
1655 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1656 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1657 break;
1658 case DexFile::kDexTypeTypeList:
1659 case DexFile::kDexTypeAnnotationSetRefList:
1660 case DexFile::kDexTypeAnnotationSetItem:
1661 case DexFile::kDexTypeClassDataItem:
1662 case DexFile::kDexTypeCodeItem:
1663 case DexFile::kDexTypeStringDataItem:
1664 case DexFile::kDexTypeDebugInfoItem:
1665 case DexFile::kDexTypeAnnotationItem:
1666 case DexFile::kDexTypeEncodedArrayItem:
1667 case DexFile::kDexTypeAnnotationsDirectoryItem:
1668 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1669 return false;
1670 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001671 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001672 break;
1673 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001674 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001675 return false;
1676 }
1677
1678 item++;
1679 }
1680
1681 return true;
1682}
1683
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001684bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001685 DCHECK_NE(offset, 0u);
1686 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001687 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001688 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001689 return false;
1690 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001691 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001692 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001693 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001694 return false;
1695 }
1696 return true;
1697}
1698
Andreas Gampea5b09a62016-11-17 15:21:22 -08001699dex::TypeIndex DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001700 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001701 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001702
1703 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001704 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001705 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001706 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001707 }
1708
1709 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001710 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001711 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001712 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001713 }
1714
Andreas Gampea5b09a62016-11-17 15:21:22 -08001715 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001716}
1717
Andreas Gampea5b09a62016-11-17 15:21:22 -08001718dex::TypeIndex DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr,
1719 bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001720 const DexFile::AnnotationsDirectoryItem* item =
1721 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001722 *success = true;
1723
jeffhao10037c82012-01-23 15:06:23 -08001724 if (item->fields_size_ != 0) {
1725 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001726 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001727 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001728 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001729 }
1730
1731 if (item->methods_size_ != 0) {
1732 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001733 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001734 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001735 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001736 }
1737
1738 if (item->parameters_size_ != 0) {
1739 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001740 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001741 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001742 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001743 }
1744
Andreas Gampea5b09a62016-11-17 15:21:22 -08001745 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001746}
1747
1748bool DexFileVerifier::CheckInterStringIdItem() {
1749 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1750
1751 // Check the map to make sure it has the right offset->type.
1752 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1753 return false;
1754 }
1755
1756 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001757 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001758 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1759 const char* prev_str = dex_file_->GetStringData(*prev_item);
1760 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001761 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1762 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001763 return false;
1764 }
1765 }
1766
1767 ptr_ += sizeof(DexFile::StringId);
1768 return true;
1769}
1770
1771bool DexFileVerifier::CheckInterTypeIdItem() {
1772 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001773
1774 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001775
1776 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001777 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1778 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001779 return false;
1780 }
1781
1782 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001783 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001784 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001785 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1786 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001787 prev_item->descriptor_idx_.index_,
1788 item->descriptor_idx_.index_);
jeffhao10037c82012-01-23 15:06:23 -08001789 return false;
1790 }
1791 }
1792
1793 ptr_ += sizeof(DexFile::TypeId);
1794 return true;
1795}
1796
1797bool DexFileVerifier::CheckInterProtoIdItem() {
1798 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001799
1800 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1801
jeffhao10037c82012-01-23 15:06:23 -08001802 if (item->parameters_off_ != 0 &&
1803 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1804 return false;
1805 }
1806
David Sehr28e74ed2016-11-21 12:52:12 -08001807 // Check that return type is representable as a uint16_t;
1808 if (UNLIKELY(!IsValidOrNoTypeId(item->return_type_idx_.index_, item->pad_))) {
1809 ErrorStringPrintf("proto with return type idx outside uint16_t range '%x:%x'",
1810 item->pad_, item->return_type_idx_.index_);
1811 return false;
1812 }
jeffhao10037c82012-01-23 15:06:23 -08001813 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001814 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1815 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001816 return false;
1817 }
1818 shorty++;
1819
1820 DexFileParameterIterator it(*dex_file_, *item);
1821 while (it.HasNext() && *shorty != '\0') {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001822 if (!CheckIndex(it.GetTypeIdx().index_,
1823 dex_file_->NumTypeIds(),
Andreas Gampebb836e12014-06-13 15:31:40 -07001824 "inter_proto_id_item shorty type_idx")) {
1825 return false;
1826 }
jeffhao10037c82012-01-23 15:06:23 -08001827 const char* descriptor = it.GetDescriptor();
1828 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1829 return false;
1830 }
1831 it.Next();
1832 shorty++;
1833 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001834 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1835 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001836 return false;
1837 }
1838
1839 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001840 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001841 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001842 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1843 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001844 return false;
1845 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1846 DexFileParameterIterator curr_it(*dex_file_, *item);
1847 DexFileParameterIterator prev_it(*dex_file_, *prev);
1848
1849 while (curr_it.HasNext() && prev_it.HasNext()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001850 dex::TypeIndex prev_idx = prev_it.GetTypeIdx();
1851 dex::TypeIndex curr_idx = curr_it.GetTypeIdx();
1852 DCHECK_NE(prev_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
1853 DCHECK_NE(curr_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
jeffhao10037c82012-01-23 15:06:23 -08001854
1855 if (prev_idx < curr_idx) {
1856 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001857 } else if (UNLIKELY(prev_idx > curr_idx)) {
1858 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001859 return false;
1860 }
1861
1862 prev_it.Next();
1863 curr_it.Next();
1864 }
Vladimir Marko0ca8add2016-05-03 17:17:50 +01001865 if (!curr_it.HasNext()) {
1866 // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
1867 // a ProtoId with a longer one. Both cases are forbidden by the specification.
1868 ErrorStringPrintf("Out-of-order proto_id arguments");
1869 return false;
1870 }
jeffhao10037c82012-01-23 15:06:23 -08001871 }
1872 }
1873
1874 ptr_ += sizeof(DexFile::ProtoId);
1875 return true;
1876}
1877
1878bool DexFileVerifier::CheckInterFieldIdItem() {
1879 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1880
1881 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001882 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1883 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1884 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001885 return false;
1886 }
1887
1888 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001889 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1890 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1891 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001892 return false;
1893 }
1894
1895 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001896 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001897 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1898 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001899 return false;
1900 }
1901
1902 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001903 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001904 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001905 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1906 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001907 return false;
1908 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001909 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1910 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001911 return false;
1912 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001913 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
1914 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001915 return false;
1916 }
1917 }
1918 }
1919 }
1920
1921 ptr_ += sizeof(DexFile::FieldId);
1922 return true;
1923}
1924
1925bool DexFileVerifier::CheckInterMethodIdItem() {
1926 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
1927
1928 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001929 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
1930 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
1931 class_descriptor[0] != '['))) {
1932 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001933 return false;
1934 }
1935
1936 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07001937 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001938 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1939 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001940 return false;
1941 }
1942
Andreas Gampedf10b322014-06-11 21:46:05 -07001943 // Check that the proto id is valid.
1944 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
1945 "inter_method_id_item proto_idx"))) {
1946 return false;
1947 }
1948
jeffhao10037c82012-01-23 15:06:23 -08001949 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001950 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001951 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001952 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1953 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001954 return false;
1955 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001956 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1957 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001958 return false;
1959 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001960 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
1961 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001962 return false;
1963 }
1964 }
1965 }
1966 }
1967
1968 ptr_ += sizeof(DexFile::MethodId);
1969 return true;
1970}
1971
1972bool DexFileVerifier::CheckInterClassDefItem() {
1973 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001974
David Sehr28e74ed2016-11-21 12:52:12 -08001975 // Check that class_idx_ is representable as a uint16_t;
1976 if (UNLIKELY(!IsValidTypeId(item->class_idx_.index_, item->pad1_))) {
1977 ErrorStringPrintf("class with type idx outside uint16_t range '%x:%x'", item->pad1_,
1978 item->class_idx_.index_);
1979 return false;
1980 }
1981 // Check that superclass_idx_ is representable as a uint16_t;
1982 if (UNLIKELY(!IsValidOrNoTypeId(item->superclass_idx_.index_, item->pad2_))) {
1983 ErrorStringPrintf("class with superclass type idx outside uint16_t range '%x:%x'", item->pad2_,
1984 item->superclass_idx_.index_);
1985 return false;
1986 }
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001987 // Check for duplicate class def.
1988 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001989 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_.index_);
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001990 return false;
1991 }
1992 defined_classes_.insert(item->class_idx_);
1993
Andreas Gampee09269c2014-06-06 18:45:35 -07001994 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
1995 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1996 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001997 return false;
1998 }
1999
Andreas Gampeacc2bb62014-07-17 19:26:50 -07002000 // Only allow non-runtime modifiers.
2001 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
2002 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
2003 return false;
2004 }
2005
jeffhao10037c82012-01-23 15:06:23 -08002006 if (item->interfaces_off_ != 0 &&
2007 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
2008 return false;
2009 }
2010 if (item->annotations_off_ != 0 &&
2011 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
2012 return false;
2013 }
2014 if (item->class_data_off_ != 0 &&
2015 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
2016 return false;
2017 }
2018 if (item->static_values_off_ != 0 &&
2019 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
2020 return false;
2021 }
2022
Andreas Gampea5b09a62016-11-17 15:21:22 -08002023 if (item->superclass_idx_.IsValid()) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002024 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2025 // Check that a class does not inherit from itself directly (by having
2026 // the same type idx as its super class).
2027 if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002028 ErrorStringPrintf("Class with same type idx as its superclass: '%d'",
2029 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002030 return false;
2031 }
2032
2033 // Check that a class is defined after its super class (if the
2034 // latter is defined in the same Dex file).
2035 const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
2036 if (superclass_def != nullptr) {
2037 // The superclass is defined in this Dex file.
2038 if (superclass_def > item) {
2039 // ClassDef item for super class appearing after the class' ClassDef item.
2040 ErrorStringPrintf("Invalid class definition ordering:"
2041 " class with type idx: '%d' defined before"
2042 " superclass with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002043 item->class_idx_.index_,
2044 item->superclass_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002045 return false;
2046 }
2047 }
2048 }
2049
Andreas Gampee09269c2014-06-06 18:45:35 -07002050 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
2051 "inter_class_def_item superclass_idx")
2052 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
2053 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002054 return false;
2055 }
2056 }
2057
Roland Levillain621b5ea2016-05-18 11:41:33 +01002058 // Check interfaces.
jeffhao10037c82012-01-23 15:06:23 -08002059 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002060 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002061 uint32_t size = interfaces->Size();
jeffhao10037c82012-01-23 15:06:23 -08002062 for (uint32_t i = 0; i < size; i++) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002063 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2064 // Check that a class does not implement itself directly (by having the
2065 // same type idx as one of its immediate implemented interfaces).
2066 if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2067 ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002068 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002069 return false;
2070 }
2071
2072 // Check that a class is defined after the interfaces it implements
2073 // (if they are defined in the same Dex file).
2074 const DexFile::ClassDef* interface_def =
2075 dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2076 if (interface_def != nullptr) {
2077 // The interface is defined in this Dex file.
2078 if (interface_def > item) {
2079 // ClassDef item for interface appearing after the class' ClassDef item.
2080 ErrorStringPrintf("Invalid class definition ordering:"
2081 " class with type idx: '%d' defined before"
2082 " implemented interface with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002083 item->class_idx_.index_,
2084 interfaces->GetTypeItem(i).type_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002085 return false;
2086 }
2087 }
2088 }
2089
2090 // Ensure that the interface refers to a class (not an array nor a primitive type).
Andreas Gampee09269c2014-06-06 18:45:35 -07002091 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2092 "inter_class_def_item interface type_idx")
2093 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2094 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002095 return false;
2096 }
2097 }
2098
2099 /*
2100 * Ensure that there are no duplicates. This is an O(N^2) test, but in
2101 * practice the number of interfaces implemented by any given class is low.
2102 */
2103 for (uint32_t i = 1; i < size; i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002104 dex::TypeIndex idx1 = interfaces->GetTypeItem(i).type_idx_;
jeffhao10037c82012-01-23 15:06:23 -08002105 for (uint32_t j =0; j < i; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002106 dex::TypeIndex idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002107 if (UNLIKELY(idx1 == idx2)) {
2108 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08002109 return false;
2110 }
2111 }
2112 }
2113 }
2114
2115 // Check that references in class_data_item are to the right class.
2116 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07002117 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002118 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002119 dex::TypeIndex data_definer = FindFirstClassDataDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002120 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002121 return false;
2122 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08002123 if (UNLIKELY((data_definer != item->class_idx_) &&
2124 (data_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002125 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08002126 return false;
2127 }
2128 }
2129
2130 // Check that references in annotations_directory_item are to right class.
2131 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002132 // annotations_off_ is supposed to be aligned by 4.
2133 if (!IsAlignedParam(item->annotations_off_, 4)) {
2134 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2135 return false;
2136 }
Ian Rogers13735952014-10-08 12:43:28 -07002137 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002138 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002139 dex::TypeIndex annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002140 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002141 return false;
2142 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002143 if (UNLIKELY((annotations_definer != item->class_idx_) &&
Andreas Gampea5b09a62016-11-17 15:21:22 -08002144 (annotations_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002145 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002146 return false;
2147 }
2148 }
2149
2150 ptr_ += sizeof(DexFile::ClassDef);
2151 return true;
2152}
2153
2154bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2155 const DexFile::AnnotationSetRefList* list =
2156 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2157 const DexFile::AnnotationSetRefItem* item = list->list_;
2158 uint32_t count = list->size_;
2159
2160 while (count--) {
2161 if (item->annotations_off_ != 0 &&
2162 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2163 return false;
2164 }
2165 item++;
2166 }
2167
Ian Rogers13735952014-10-08 12:43:28 -07002168 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002169 return true;
2170}
2171
2172bool DexFileVerifier::CheckInterAnnotationSetItem() {
2173 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2174 const uint32_t* offsets = set->entries_;
2175 uint32_t count = set->size_;
2176 uint32_t last_idx = 0;
2177
2178 for (uint32_t i = 0; i < count; i++) {
2179 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2180 return false;
2181 }
2182
2183 // Get the annotation from the offset and the type index for the annotation.
2184 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002185 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002186 const uint8_t* data = annotation->annotation_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002187 DECODE_UNSIGNED_CHECKED_FROM(data, idx);
jeffhao10037c82012-01-23 15:06:23 -08002188
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002189 if (UNLIKELY(last_idx >= idx && i != 0)) {
2190 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002191 return false;
2192 }
2193
2194 last_idx = idx;
2195 offsets++;
2196 }
2197
Ian Rogers13735952014-10-08 12:43:28 -07002198 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002199 return true;
2200}
2201
2202bool DexFileVerifier::CheckInterClassDataItem() {
2203 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002204 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002205 dex::TypeIndex defining_class = FindFirstClassDataDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002206 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002207 return false;
2208 }
jeffhao10037c82012-01-23 15:06:23 -08002209
2210 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002211 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002212 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002213 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002214 return false;
2215 }
2216 }
2217 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2218 uint32_t code_off = it.GetMethodCodeItemOffset();
2219 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2220 return false;
2221 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002222 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002223 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002224 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002225 return false;
2226 }
2227 }
2228
2229 ptr_ = it.EndDataPointer();
2230 return true;
2231}
2232
2233bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2234 const DexFile::AnnotationsDirectoryItem* item =
2235 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002236 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002237 dex::TypeIndex defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002238 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002239 return false;
2240 }
jeffhao10037c82012-01-23 15:06:23 -08002241
2242 if (item->class_annotations_off_ != 0 &&
2243 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2244 return false;
2245 }
2246
2247 // Field annotations follow immediately after the annotations directory.
2248 const DexFile::FieldAnnotationsItem* field_item =
2249 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2250 uint32_t field_count = item->fields_size_;
2251 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002252 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2253 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002254 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002255 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002256 return false;
2257 }
2258 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2259 return false;
2260 }
2261 field_item++;
2262 }
2263
2264 // Method annotations follow immediately after field annotations.
2265 const DexFile::MethodAnnotationsItem* method_item =
2266 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2267 uint32_t method_count = item->methods_size_;
2268 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002269 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002270 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002271 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002272 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002273 return false;
2274 }
2275 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2276 return false;
2277 }
2278 method_item++;
2279 }
2280
2281 // Parameter annotations follow immediately after method annotations.
2282 const DexFile::ParameterAnnotationsItem* parameter_item =
2283 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2284 uint32_t parameter_count = item->parameters_size_;
2285 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002286 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002287 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002288 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002289 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002290 return false;
2291 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002292 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2293 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002294 return false;
2295 }
2296 parameter_item++;
2297 }
2298
Ian Rogers13735952014-10-08 12:43:28 -07002299 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002300 return true;
2301}
2302
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002303bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002304 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002305 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002306 switch (type) {
2307 case DexFile::kDexTypeClassDataItem:
2308 alignment_mask = sizeof(uint8_t) - 1;
2309 break;
2310 default:
2311 alignment_mask = sizeof(uint32_t) - 1;
2312 break;
2313 }
2314
2315 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002316 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002317 for (uint32_t i = 0; i < count; i++) {
2318 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002319 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002320 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002321
2322 // Check depending on the section type.
2323 switch (type) {
2324 case DexFile::kDexTypeStringIdItem: {
2325 if (!CheckInterStringIdItem()) {
2326 return false;
2327 }
2328 break;
2329 }
2330 case DexFile::kDexTypeTypeIdItem: {
2331 if (!CheckInterTypeIdItem()) {
2332 return false;
2333 }
2334 break;
2335 }
2336 case DexFile::kDexTypeProtoIdItem: {
2337 if (!CheckInterProtoIdItem()) {
2338 return false;
2339 }
2340 break;
2341 }
2342 case DexFile::kDexTypeFieldIdItem: {
2343 if (!CheckInterFieldIdItem()) {
2344 return false;
2345 }
2346 break;
2347 }
2348 case DexFile::kDexTypeMethodIdItem: {
2349 if (!CheckInterMethodIdItem()) {
2350 return false;
2351 }
2352 break;
2353 }
2354 case DexFile::kDexTypeClassDefItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002355 // There shouldn't be more class definitions than type ids allow.
2356 // This check should be redundant, since there are checks that the
2357 // class_idx_ is within range and that there is only one definition
2358 // for a given type id.
2359 if (i > kTypeIdLimit) {
2360 ErrorStringPrintf("Too many class definition items");
2361 return false;
2362 }
jeffhao10037c82012-01-23 15:06:23 -08002363 if (!CheckInterClassDefItem()) {
2364 return false;
2365 }
2366 break;
2367 }
2368 case DexFile::kDexTypeAnnotationSetRefList: {
2369 if (!CheckInterAnnotationSetRefList()) {
2370 return false;
2371 }
2372 break;
2373 }
2374 case DexFile::kDexTypeAnnotationSetItem: {
2375 if (!CheckInterAnnotationSetItem()) {
2376 return false;
2377 }
2378 break;
2379 }
2380 case DexFile::kDexTypeClassDataItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002381 // There shouldn't be more class data than type ids allow.
2382 // This check should be redundant, since there are checks that the
2383 // class_idx_ is within range and that there is only one definition
2384 // for a given type id.
2385 if (i > kTypeIdLimit) {
2386 ErrorStringPrintf("Too many class data items");
2387 return false;
2388 }
jeffhao10037c82012-01-23 15:06:23 -08002389 if (!CheckInterClassDataItem()) {
2390 return false;
2391 }
2392 break;
2393 }
2394 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2395 if (!CheckInterAnnotationsDirectoryItem()) {
2396 return false;
2397 }
2398 break;
2399 }
2400 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002401 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002402 return false;
2403 }
2404
2405 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002406 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002407 }
2408
2409 return true;
2410}
2411
2412bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002413 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002414 const DexFile::MapItem* item = map->list_;
2415 uint32_t count = map->size_;
2416
2417 // Cross check the items listed in the map.
2418 while (count--) {
2419 uint32_t section_offset = item->offset_;
2420 uint32_t section_count = item->size_;
2421 uint16_t type = item->type_;
2422
2423 switch (type) {
2424 case DexFile::kDexTypeHeaderItem:
2425 case DexFile::kDexTypeMapList:
2426 case DexFile::kDexTypeTypeList:
2427 case DexFile::kDexTypeCodeItem:
2428 case DexFile::kDexTypeStringDataItem:
2429 case DexFile::kDexTypeDebugInfoItem:
2430 case DexFile::kDexTypeAnnotationItem:
2431 case DexFile::kDexTypeEncodedArrayItem:
2432 break;
2433 case DexFile::kDexTypeStringIdItem:
2434 case DexFile::kDexTypeTypeIdItem:
2435 case DexFile::kDexTypeProtoIdItem:
2436 case DexFile::kDexTypeFieldIdItem:
2437 case DexFile::kDexTypeMethodIdItem:
2438 case DexFile::kDexTypeClassDefItem:
2439 case DexFile::kDexTypeAnnotationSetRefList:
2440 case DexFile::kDexTypeAnnotationSetItem:
2441 case DexFile::kDexTypeClassDataItem:
2442 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2443 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2444 return false;
2445 }
2446 break;
2447 }
2448 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002449 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002450 return false;
2451 }
2452
2453 item++;
2454 }
2455
2456 return true;
2457}
2458
2459bool DexFileVerifier::Verify() {
2460 // Check the header.
2461 if (!CheckHeader()) {
2462 return false;
2463 }
2464
2465 // Check the map section.
2466 if (!CheckMap()) {
2467 return false;
2468 }
2469
2470 // Check structure within remaining sections.
2471 if (!CheckIntraSection()) {
2472 return false;
2473 }
2474
2475 // Check references from one section to another.
2476 if (!CheckInterSection()) {
2477 return false;
2478 }
2479
2480 return true;
2481}
2482
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002483void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2484 va_list ap;
2485 va_start(ap, fmt);
2486 DCHECK(failure_reason_.empty()) << failure_reason_;
2487 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2488 StringAppendV(&failure_reason_, fmt, ap);
2489 va_end(ap);
2490}
2491
Andreas Gampee6215c02015-08-31 18:54:38 -07002492// Fields and methods may have only one of public/protected/private.
2493static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2494 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2495 (((flags & kAccProtected) == 0) ? 0 : 1) +
2496 (((flags & kAccPrivate) == 0) ? 0 : 1);
2497 return count <= 1;
2498}
2499
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002500// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2501// functionality, as we're still verifying the dex file. begin and header correspond to the
2502// underscored variants in the DexFileVerifier.
2503
2504static std::string GetStringOrError(const uint8_t* const begin,
2505 const DexFile::Header* const header,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002506 dex::StringIndex string_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002507 // The `string_idx` is not guaranteed to be valid yet.
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002508 if (header->string_ids_size_ <= string_idx.index_) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002509 return "(error)";
2510 }
2511
2512 const DexFile::StringId* string_id =
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002513 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_)
2514 + string_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002515
2516 // Assume that the data is OK at this point. String data has been checked at this point.
2517
2518 const uint8_t* ptr = begin + string_id->string_data_off_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002519 uint32_t dummy;
2520 if (!DecodeUnsignedLeb128Checked(&ptr, begin + header->file_size_, &dummy)) {
2521 return "(error)";
2522 }
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002523 return reinterpret_cast<const char*>(ptr);
2524}
2525
2526static std::string GetClassOrError(const uint8_t* const begin,
2527 const DexFile::Header* const header,
Andreas Gampea5b09a62016-11-17 15:21:22 -08002528 dex::TypeIndex class_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002529 // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2530 // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2531 // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2532 // a valid defining class.
Andreas Gampea5b09a62016-11-17 15:21:22 -08002533 CHECK_LT(class_idx.index_, header->type_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002534
2535 const DexFile::TypeId* type_id =
Andreas Gampea5b09a62016-11-17 15:21:22 -08002536 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002537
2538 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2539
2540 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2541}
2542
2543static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2544 const DexFile::Header* const header,
2545 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002546 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2547 CHECK_LT(idx, header->field_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002548
2549 const DexFile::FieldId* field_id =
2550 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2551
2552 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2553
2554 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2555 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2556
2557 return class_name + "." + field_name;
2558}
2559
2560static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2561 const DexFile::Header* const header,
2562 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002563 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2564 CHECK_LT(idx, header->method_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002565
2566 const DexFile::MethodId* method_id =
2567 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2568
2569 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2570
2571 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2572 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2573
2574 return class_name + "." + method_name;
2575}
2576
2577bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2578 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002579 uint32_t class_access_flags,
2580 std::string* error_msg) {
2581 // Generally sort out >16-bit flags.
2582 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002583 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2584 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2585 field_access_flags,
2586 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002587 return false;
2588 }
2589
2590 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2591 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2592 kAccPrivate |
2593 kAccProtected |
2594 kAccStatic |
2595 kAccFinal |
2596 kAccVolatile |
2597 kAccTransient |
2598 kAccSynthetic |
2599 kAccEnum;
2600
2601 // Fields may have only one of public/protected/final.
2602 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002603 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2604 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2605 field_access_flags,
2606 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002607 return false;
2608 }
2609
2610 // Interfaces have a pretty restricted list.
2611 if ((class_access_flags & kAccInterface) != 0) {
2612 // Interface fields must be public final static.
2613 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2614 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002615 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2616 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2617 field_access_flags,
2618 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002619 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002620 return false;
2621 } else {
2622 // Allow in older versions, but warn.
2623 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2624 << *error_msg;
2625 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002626 }
2627 // Interface fields may be synthetic, but may not have other flags.
2628 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2629 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002630 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
2631 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2632 field_access_flags,
2633 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002634 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002635 return false;
2636 } else {
2637 // Allow in older versions, but warn.
2638 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2639 << *error_msg;
2640 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002641 }
2642 return true;
2643 }
2644
2645 // Volatile fields may not be final.
2646 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2647 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002648 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
2649 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002650 return false;
2651 }
2652
2653 return true;
2654}
2655
2656// Try to find the name of the method with the given index. We do not want to rely on DexFile
2657// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
2658// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
2659// (flagged by the return value), otherwise error_msg will contain an error string.
2660static bool FindMethodName(uint32_t method_index,
2661 const uint8_t* begin,
2662 const DexFile::Header* header,
2663 const char** str,
2664 std::string* error_msg) {
2665 if (method_index >= header->method_ids_size_) {
2666 *error_msg = "Method index not available for method flags verification";
2667 return false;
2668 }
2669 uint32_t string_idx =
2670 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002671 method_index)->name_idx_.index_;
Andreas Gampee6215c02015-08-31 18:54:38 -07002672 if (string_idx >= header->string_ids_size_) {
2673 *error_msg = "String index not available for method flags verification";
2674 return false;
2675 }
2676 uint32_t string_off =
2677 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
2678 string_data_off_;
2679 if (string_off >= header->file_size_) {
2680 *error_msg = "String offset out of bounds for method flags verification";
2681 return false;
2682 }
2683 const uint8_t* str_data_ptr = begin + string_off;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002684 uint32_t dummy;
2685 if (!DecodeUnsignedLeb128Checked(&str_data_ptr, begin + header->file_size_, &dummy)) {
2686 *error_msg = "String size out of bounds for method flags verification";
2687 return false;
2688 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002689 *str = reinterpret_cast<const char*>(str_data_ptr);
2690 return true;
2691}
2692
2693bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2694 uint32_t method_access_flags,
2695 uint32_t class_access_flags,
2696 bool has_code,
2697 bool expect_direct,
2698 std::string* error_msg) {
2699 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2700 constexpr uint32_t kAllMethodFlags =
2701 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2702 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002703 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
2704 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2705 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002706 return false;
2707 }
2708
2709 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2710 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2711 kAccPrivate |
2712 kAccProtected |
2713 kAccStatic |
2714 kAccFinal |
2715 kAccSynthetic |
2716 kAccSynchronized |
2717 kAccBridge |
2718 kAccVarargs |
2719 kAccNative |
2720 kAccAbstract |
2721 kAccStrict;
2722
2723 // Methods may have only one of public/protected/final.
2724 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002725 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
2726 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002727 method_access_flags);
2728 return false;
2729 }
2730
2731 // Try to find the name, to check for constructor properties.
2732 const char* str;
2733 if (!FindMethodName(method_index, begin_, header_, &str, error_msg)) {
2734 return false;
2735 }
2736 bool is_init_by_name = false;
2737 constexpr const char* kInitName = "<init>";
2738 size_t str_offset = (reinterpret_cast<const uint8_t*>(str) - begin_);
2739 if (header_->file_size_ - str_offset >= sizeof(kInitName)) {
2740 is_init_by_name = strcmp(kInitName, str) == 0;
2741 }
2742 bool is_clinit_by_name = false;
2743 constexpr const char* kClinitName = "<clinit>";
2744 if (header_->file_size_ - str_offset >= sizeof(kClinitName)) {
2745 is_clinit_by_name = strcmp(kClinitName, str) == 0;
2746 }
2747 bool is_constructor = is_init_by_name || is_clinit_by_name;
2748
2749 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2750 // the reverse for backwards compatibility reasons.
2751 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002752 *error_msg =
2753 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
2754 method_index,
2755 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002756 return false;
2757 }
2758 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2759 // instance constructor is called "<init>".
2760 if (is_constructor) {
2761 bool is_static = (method_access_flags & kAccStatic) != 0;
2762 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002763 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
2764 method_index,
2765 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002766 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2767 return false;
2768 } else {
2769 // Allow in older versions, but warn.
2770 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2771 << *error_msg;
2772 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002773 }
2774 }
2775 // Check that static and private methods, as well as constructors, are in the direct methods list,
2776 // and other methods in the virtual methods list.
2777 bool is_direct = (method_access_flags & (kAccStatic | kAccPrivate)) != 0 || is_constructor;
2778 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002779 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07002780 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002781 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002782 expect_direct);
2783 return false;
2784 }
2785
2786
2787 // From here on out it is easier to mask out the bits we're supposed to ignore.
2788 method_access_flags &= kMethodAccessFlags;
2789
Alex Lightd7c10c22016-03-31 10:03:07 -07002790 // Interfaces are special.
2791 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07002792 // Non-static interface methods must be public or private.
2793 uint32_t desired_flags = (kAccPublic | kAccStatic);
2794 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2795 desired_flags |= kAccPrivate;
2796 }
2797 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002798 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
2799 method_index,
2800 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002801 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002802 return false;
2803 } else {
2804 // Allow in older versions, but warn.
2805 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2806 << *error_msg;
2807 }
2808 }
2809 }
2810
Andreas Gampee6215c02015-08-31 18:54:38 -07002811 // If there aren't any instructions, make sure that's expected.
2812 if (!has_code) {
2813 // Only native or abstract methods may not have code.
2814 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002815 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07002816 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002817 method_index,
2818 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002819 return false;
2820 }
2821 // Constructors must always have code.
2822 if (is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002823 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
2824 method_index,
2825 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002826 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2827 return false;
2828 } else {
2829 // Allow in older versions, but warn.
2830 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2831 << *error_msg;
2832 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002833 }
2834 if ((method_access_flags & kAccAbstract) != 0) {
2835 // Abstract methods are not allowed to have the following flags.
2836 constexpr uint32_t kForbidden =
2837 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2838 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002839 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
2840 method_index,
2841 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2842 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002843 return false;
2844 }
Andreas Gampe97b11352015-12-10 16:23:41 -08002845 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07002846 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002847 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08002848 << " is abstract, but the declaring class is neither abstract nor an "
2849 << "interface in dex file "
2850 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07002851 }
2852 }
2853 // Interfaces are special.
2854 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002855 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07002856 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002857 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
2858 method_index,
2859 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002860 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002861 return false;
2862 } else {
2863 // Allow in older versions, but warn.
2864 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2865 << *error_msg;
2866 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002867 }
2868 // At this point, we know the method is public and abstract. This means that all the checks
2869 // for invalid combinations above applies. In addition, interface methods must not be
2870 // protected. This is caught by the check for only-one-of-public-protected-private.
2871 }
2872 return true;
2873 }
2874
2875 // When there's code, the method must not be native or abstract.
2876 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002877 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
2878 method_index,
2879 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002880 return false;
2881 }
2882
Andreas Gampee6215c02015-08-31 18:54:38 -07002883 // Instance constructors must not be synchronized and a few other flags.
2884 if (is_init_by_name) {
2885 static constexpr uint32_t kInitAllowed =
2886 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2887 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002888 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07002889 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002890 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002891 method_access_flags);
2892 return false;
2893 }
2894 }
2895
2896 return true;
2897}
2898
jeffhao10037c82012-01-23 15:06:23 -08002899} // namespace art