blob: 5d70076d1e6994a780d78f13e1615f7a382ff8a9 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
jeffhao10037c82012-01-23 15:06:23 -080016
17#include "dex_file_verifier.h"
18
Andreas Gampee6215c02015-08-31 18:54:38 -070019#include <inttypes.h>
Narayan Kamath92572be2013-11-28 14:06:24 +000020#include <zlib.h>
Andreas Gampee6215c02015-08-31 18:54:38 -070021
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Narayan Kamath92572be2013-11-28 14:06:24 +000023
Elliott Hughese222ee02012-12-13 14:41:43 -080024#include "base/stringprintf.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070025#include "dex_file-inl.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070026#include "experimental_flags.h"
jeffhao10037c82012-01-23 15:06:23 -080027#include "leb128.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070028#include "runtime.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070029#include "safe_map.h"
Ian Rogersa6724902013-09-23 09:23:37 -070030#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "utils.h"
jeffhao10037c82012-01-23 15:06:23 -080032
33namespace art {
34
35static uint32_t MapTypeToBitMask(uint32_t map_type) {
36 switch (map_type) {
37 case DexFile::kDexTypeHeaderItem: return 1 << 0;
38 case DexFile::kDexTypeStringIdItem: return 1 << 1;
39 case DexFile::kDexTypeTypeIdItem: return 1 << 2;
40 case DexFile::kDexTypeProtoIdItem: return 1 << 3;
41 case DexFile::kDexTypeFieldIdItem: return 1 << 4;
42 case DexFile::kDexTypeMethodIdItem: return 1 << 5;
43 case DexFile::kDexTypeClassDefItem: return 1 << 6;
44 case DexFile::kDexTypeMapList: return 1 << 7;
45 case DexFile::kDexTypeTypeList: return 1 << 8;
46 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9;
47 case DexFile::kDexTypeAnnotationSetItem: return 1 << 10;
48 case DexFile::kDexTypeClassDataItem: return 1 << 11;
49 case DexFile::kDexTypeCodeItem: return 1 << 12;
50 case DexFile::kDexTypeStringDataItem: return 1 << 13;
51 case DexFile::kDexTypeDebugInfoItem: return 1 << 14;
52 case DexFile::kDexTypeAnnotationItem: return 1 << 15;
53 case DexFile::kDexTypeEncodedArrayItem: return 1 << 16;
54 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17;
55 }
56 return 0;
57}
58
59static bool IsDataSectionType(uint32_t map_type) {
60 switch (map_type) {
61 case DexFile::kDexTypeHeaderItem:
62 case DexFile::kDexTypeStringIdItem:
63 case DexFile::kDexTypeTypeIdItem:
64 case DexFile::kDexTypeProtoIdItem:
65 case DexFile::kDexTypeFieldIdItem:
66 case DexFile::kDexTypeMethodIdItem:
67 case DexFile::kDexTypeClassDefItem:
68 return false;
69 }
70 return true;
71}
72
Andreas Gampee09269c2014-06-06 18:45:35 -070073const char* DexFileVerifier::CheckLoadStringByIdx(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070074 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070075 return nullptr;
76 }
77 return dex_file_->StringDataByIdx(idx);
78}
79
80const char* DexFileVerifier::CheckLoadStringByTypeIdx(uint32_t type_idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070081 if (UNLIKELY(!CheckIndex(type_idx, dex_file_->NumTypeIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070082 return nullptr;
83 }
84 const DexFile::TypeId& type_id = dex_file_->GetTypeId(type_idx);
85 uint32_t idx = type_id.descriptor_idx_;
86 return CheckLoadStringByIdx(idx, error_string);
87}
88
89const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070090 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070091 return nullptr;
92 }
93 return &dex_file_->GetFieldId(idx);
94}
95
96const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070097 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070098 return nullptr;
99 }
100 return &dex_file_->GetMethodId(idx);
101}
102
103// Helper macro to load string and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700104#define LOAD_STRING(var, idx, error) \
105 const char* (var) = CheckLoadStringByIdx(idx, error); \
106 if (UNLIKELY((var) == nullptr)) { \
107 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700108 }
109
110// Helper macro to load string by type idx and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700111#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
112 const char* (var) = CheckLoadStringByTypeIdx(type_idx, error); \
113 if (UNLIKELY((var) == nullptr)) { \
114 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700115 }
116
117// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700118#define LOAD_METHOD(var, idx, error_string, error_stmt) \
119 const DexFile::MethodId* (var) = CheckLoadMethodId(idx, error_string); \
120 if (UNLIKELY((var) == nullptr)) { \
121 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700122 }
123
124// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700125#define LOAD_FIELD(var, idx, fmt, error_stmt) \
126 const DexFile::FieldId* (var) = CheckLoadFieldId(idx, fmt); \
127 if (UNLIKELY((var) == nullptr)) { \
128 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700129 }
130
Aart Bik37d6a3b2016-06-21 18:30:10 -0700131bool DexFileVerifier::Verify(const DexFile* dex_file,
132 const uint8_t* begin,
133 size_t size,
134 const char* location,
135 bool verify_checksum,
136 std::string* error_msg) {
137 std::unique_ptr<DexFileVerifier> verifier(
138 new DexFileVerifier(dex_file, begin, size, location, verify_checksum));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700139 if (!verifier->Verify()) {
140 *error_msg = verifier->FailureReason();
141 return false;
142 }
143 return true;
144}
145
146bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
147 bool is_return_type) {
jeffhao10037c82012-01-23 15:06:23 -0800148 switch (shorty_char) {
149 case 'V':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700150 if (UNLIKELY(!is_return_type)) {
151 ErrorStringPrintf("Invalid use of void");
jeffhao10037c82012-01-23 15:06:23 -0800152 return false;
153 }
Ian Rogersfc787ec2014-10-09 21:56:44 -0700154 FALLTHROUGH_INTENDED;
jeffhao10037c82012-01-23 15:06:23 -0800155 case 'B':
156 case 'C':
157 case 'D':
158 case 'F':
159 case 'I':
160 case 'J':
161 case 'S':
162 case 'Z':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700163 if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
164 ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
165 shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800166 return false;
167 }
168 break;
169 case 'L':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700170 if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
171 ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800172 return false;
173 }
174 break;
175 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700176 ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
jeffhao10037c82012-01-23 15:06:23 -0800177 return false;
178 }
179 return true;
180}
181
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700182bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700183 const char* label) {
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700184 // Check that size is not 0.
185 CHECK_NE(elem_size, 0U);
186
Ian Rogers13735952014-10-08 12:43:28 -0700187 const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
188 const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700189
190 // Check for overflow.
191 uintptr_t max = 0 - 1;
192 size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
193 size_t max_count = available_bytes_till_end_of_mem / elem_size;
194 if (max_count < count) {
195 ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
196 static_cast<size_t>(range_start - file_start),
197 count, elem_size);
198 return false;
199 }
200
Ian Rogers13735952014-10-08 12:43:28 -0700201 const uint8_t* range_end = range_start + count * elem_size;
202 const uint8_t* file_end = file_start + size_;
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700203 if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
204 // Note: these two tests are enough as we make sure above that there's no overflow.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800205 ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
Ian Rogerse3d55812014-06-11 13:00:44 -0700206 static_cast<size_t>(range_start - file_start),
207 static_cast<size_t>(range_end - file_start));
jeffhao10037c82012-01-23 15:06:23 -0800208 return false;
209 }
210 return true;
211}
212
Ian Rogers13735952014-10-08 12:43:28 -0700213bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700214 // Check that the list is available. The first 4B are the count.
215 if (!CheckListSize(*ptr, 1, 4U, label)) {
216 return false;
217 }
218
219 uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
220 if (count > 0) {
221 if (!CheckListSize(*ptr + 4, count, element_size, label)) {
222 return false;
223 }
224 }
225
226 *ptr += 4 + count * element_size;
227 return true;
228}
229
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700230bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
231 if (UNLIKELY(field >= limit)) {
232 ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
jeffhao10037c82012-01-23 15:06:23 -0800233 return false;
234 }
235 return true;
236}
237
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800238bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
239 uint32_t size,
240 size_t alignment,
241 const char* label) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700242 if (size == 0) {
243 if (offset != 0) {
244 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
245 return false;
246 }
247 }
248 if (size_ <= offset) {
249 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
250 return false;
251 }
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800252 if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
253 ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
254 return false;
255 }
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700256 return true;
257}
258
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100259bool DexFileVerifier::CheckSizeLimit(uint32_t size, uint32_t limit, const char* label) {
260 if (size > limit) {
261 ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label);
262 return false;
263 }
264 return true;
265}
266
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700267bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800268 // Check file size from the header.
269 uint32_t expected_size = header_->file_size_;
270 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700271 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800272 return false;
273 }
274
275 // Compute and verify the checksum in the header.
276 uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
277 const uint32_t non_sum = sizeof(header_->magic_) + sizeof(header_->checksum_);
Ian Rogers13735952014-10-08 12:43:28 -0700278 const uint8_t* non_sum_ptr = reinterpret_cast<const uint8_t*>(header_) + non_sum;
jeffhaof6174e82012-01-31 16:14:17 -0800279 adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
jeffhao10037c82012-01-23 15:06:23 -0800280 if (adler_checksum != header_->checksum_) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700281 if (verify_checksum_) {
282 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
283 return false;
284 } else {
285 LOG(WARNING) << StringPrintf(
286 "Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
287 }
jeffhao10037c82012-01-23 15:06:23 -0800288 }
289
290 // Check the contents of the header.
291 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700292 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800293 return false;
294 }
295
296 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700297 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800298 return false;
299 }
300
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700301 // Check that all offsets are inside the file.
302 bool result =
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800303 CheckValidOffsetAndSize(header_->link_off_,
304 header_->link_size_,
305 0 /* unaligned */,
306 "link") &&
307 CheckValidOffsetAndSize(header_->map_off_,
308 header_->map_off_,
309 4,
310 "map") &&
311 CheckValidOffsetAndSize(header_->string_ids_off_,
312 header_->string_ids_size_,
313 4,
314 "string-ids") &&
315 CheckValidOffsetAndSize(header_->type_ids_off_,
316 header_->type_ids_size_,
317 4,
318 "type-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100319 CheckSizeLimit(header_->type_ids_size_, DexFile::kDexNoIndex16, "type-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800320 CheckValidOffsetAndSize(header_->proto_ids_off_,
321 header_->proto_ids_size_,
322 4,
323 "proto-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100324 CheckSizeLimit(header_->proto_ids_size_, DexFile::kDexNoIndex16, "proto-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800325 CheckValidOffsetAndSize(header_->field_ids_off_,
326 header_->field_ids_size_,
327 4,
328 "field-ids") &&
329 CheckValidOffsetAndSize(header_->method_ids_off_,
330 header_->method_ids_size_,
331 4,
332 "method-ids") &&
333 CheckValidOffsetAndSize(header_->class_defs_off_,
334 header_->class_defs_size_,
335 4,
336 "class-defs") &&
337 CheckValidOffsetAndSize(header_->data_off_,
338 header_->data_size_,
339 0, // Unaligned, spec doesn't talk about it, even though size
340 // is supposed to be a multiple of 4.
341 "data");
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700342 return result;
jeffhao10037c82012-01-23 15:06:23 -0800343}
344
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700345bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700346 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
347 header_->map_off_);
348 // Check that map list content is available.
349 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
350 return false;
351 }
352
jeffhao10037c82012-01-23 15:06:23 -0800353 const DexFile::MapItem* item = map->list_;
354
355 uint32_t count = map->size_;
356 uint32_t last_offset = 0;
357 uint32_t data_item_count = 0;
358 uint32_t data_items_left = header_->data_size_;
359 uint32_t used_bits = 0;
360
361 // Sanity check the size of the map list.
362 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
363 return false;
364 }
365
366 // Check the items listed in the map.
367 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700368 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
369 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800370 return false;
371 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700372 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
373 ErrorStringPrintf("Map item after end of file: %x, size %x",
374 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800375 return false;
376 }
377
378 if (IsDataSectionType(item->type_)) {
379 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700380 if (UNLIKELY(icount > data_items_left)) {
381 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800382 return false;
383 }
384 data_items_left -= icount;
385 data_item_count += icount;
386 }
387
388 uint32_t bit = MapTypeToBitMask(item->type_);
389
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700390 if (UNLIKELY(bit == 0)) {
391 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800392 return false;
393 }
394
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700395 if (UNLIKELY((used_bits & bit) != 0)) {
396 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800397 return false;
398 }
399
400 used_bits |= bit;
401 last_offset = item->offset_;
402 item++;
403 }
404
405 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700406 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
407 ErrorStringPrintf("Map is missing header entry");
jeffhao10037c82012-01-23 15:06:23 -0800408 return false;
409 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700410 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
411 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800412 return false;
413 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700414 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
415 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
416 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800417 return false;
418 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700419 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
420 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
421 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800422 return false;
423 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700424 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
425 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
426 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800427 return false;
428 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700429 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
430 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
431 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800432 return false;
433 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700434 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
435 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
436 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800437 return false;
438 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700439 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
440 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
441 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800442 return false;
443 }
jeffhao10037c82012-01-23 15:06:23 -0800444 return true;
445}
446
447uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
448 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700449 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700450 for (uint32_t i = 0; i < size; i++) {
451 result |= ((uint32_t) *(ptr_++)) << (i * 8);
452 }
jeffhao10037c82012-01-23 15:06:23 -0800453 }
jeffhao10037c82012-01-23 15:06:23 -0800454 return result;
455}
456
Andreas Gampebed6daf2016-09-02 18:12:00 -0700457
458#define DECODE_UNSIGNED_CHECKED_FROM_WITH_ERROR_VALUE(ptr, var, error_value) \
459 uint32_t var; \
460 if (!DecodeUnsignedLeb128Checked(&ptr, begin_ + size_, &var)) { \
461 return error_value; \
462 }
463
464#define DECODE_UNSIGNED_CHECKED_FROM(ptr, var) \
465 uint32_t var; \
466 if (!DecodeUnsignedLeb128Checked(&ptr, begin_ + size_, &var)) { \
467 ErrorStringPrintf("Read out of bounds"); \
468 return false; \
469 }
470
471#define DECODE_SIGNED_CHECKED_FROM(ptr, var) \
472 int32_t var; \
473 if (!DecodeSignedLeb128Checked(&ptr, begin_ + size_, &var)) { \
474 ErrorStringPrintf("Read out of bounds"); \
475 return false; \
476 }
477
jeffhao10037c82012-01-23 15:06:23 -0800478bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700479 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700480 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800481
482 for (uint32_t i = 0; i < handlers_size; i++) {
483 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800484 size_t offset = ptr_ - handlers_base;
Andreas Gampebed6daf2016-09-02 18:12:00 -0700485 DECODE_SIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800486
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700487 if (UNLIKELY((size < -65536) || (size > 65536))) {
488 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800489 return false;
490 }
491
492 if (size <= 0) {
493 catch_all = true;
494 size = -size;
495 } else {
496 catch_all = false;
497 }
498
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800499 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800500
501 while (size-- > 0) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700502 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -0800503 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
504 return false;
505 }
506
Andreas Gampebed6daf2016-09-02 18:12:00 -0700507 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700508 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
509 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800510 return false;
511 }
512 }
513
514 if (catch_all) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700515 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700516 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
517 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800518 return false;
519 }
520 }
521 }
522
523 return true;
524}
525
Andreas Gampee6215c02015-08-31 18:54:38 -0700526bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
527 uint32_t access_flags,
528 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700529 uint16_t class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700530 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700531 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800532 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
533 return false;
534 }
535
Andreas Gampee6215c02015-08-31 18:54:38 -0700536 // Check that it's the right class.
537 uint16_t my_class_index =
538 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
539 class_idx_;
540 if (class_type_index != my_class_index) {
541 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
542 my_class_index,
543 class_type_index);
544 return false;
545 }
546
547 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800548 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700549 if (UNLIKELY(is_static != expect_static)) {
550 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800551 return false;
552 }
553
Andreas Gampee6215c02015-08-31 18:54:38 -0700554 // Check field access flags.
555 std::string error_msg;
Andreas Gampec9f0ba12016-02-09 09:21:04 -0800556 if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700557 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800558 return false;
559 }
560
561 return true;
562}
563
Andreas Gampee6215c02015-08-31 18:54:38 -0700564bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
565 uint32_t access_flags,
566 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700567 uint16_t class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700568 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700569 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700570 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700571 DCHECK(direct_method_indexes != nullptr);
572 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800573 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
574 return false;
575 }
576
Andreas Gampee6215c02015-08-31 18:54:38 -0700577 // Check that it's the right class.
578 uint16_t my_class_index =
579 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
580 class_idx_;
581 if (class_type_index != my_class_index) {
582 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 "vs %" PRIu16,
583 my_class_index,
584 class_type_index);
jeffhao10037c82012-01-23 15:06:23 -0800585 return false;
586 }
587
Andreas Gampee6215c02015-08-31 18:54:38 -0700588 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700589 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700590 direct_method_indexes->insert(idx);
591 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700592 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
593 return false;
594 }
595
Andreas Gampee6215c02015-08-31 18:54:38 -0700596 // Check method access flags.
597 bool has_code = (code_offset != 0);
598 std::string error_msg;
599 if (!CheckMethodAccessFlags(idx,
600 access_flags,
601 class_access_flags,
602 has_code,
603 expect_direct,
604 &error_msg)) {
605 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800606 return false;
607 }
608
609 return true;
610}
611
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800612bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800613 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700614 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800615 return false;
616 }
617 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700618 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800619 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800620 return false;
621 }
622 ptr_++;
623 offset++;
624 }
625 }
626 return true;
627}
628
629bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700630 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800631 return false;
632 }
633
634 uint8_t header_byte = *(ptr_++);
635 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
636 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
637
638 switch (value_type) {
639 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700640 if (UNLIKELY(value_arg != 0)) {
641 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800642 return false;
643 }
644 ptr_++;
645 break;
646 case DexFile::kDexAnnotationShort:
647 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700648 if (UNLIKELY(value_arg > 1)) {
649 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800650 return false;
651 }
652 ptr_ += value_arg + 1;
653 break;
654 case DexFile::kDexAnnotationInt:
655 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700656 if (UNLIKELY(value_arg > 3)) {
657 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800658 return false;
659 }
660 ptr_ += value_arg + 1;
661 break;
662 case DexFile::kDexAnnotationLong:
663 case DexFile::kDexAnnotationDouble:
664 ptr_ += value_arg + 1;
665 break;
666 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700667 if (UNLIKELY(value_arg > 3)) {
668 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800669 return false;
670 }
671 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
672 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
673 return false;
674 }
675 break;
676 }
677 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700678 if (UNLIKELY(value_arg > 3)) {
679 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800680 return false;
681 }
682 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
683 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
684 return false;
685 }
686 break;
687 }
688 case DexFile::kDexAnnotationField:
689 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700690 if (UNLIKELY(value_arg > 3)) {
691 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800692 return false;
693 }
694 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
695 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
696 return false;
697 }
698 break;
699 }
700 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700701 if (UNLIKELY(value_arg > 3)) {
702 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800703 return false;
704 }
705 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
706 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
707 return false;
708 }
709 break;
710 }
711 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700712 if (UNLIKELY(value_arg != 0)) {
713 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800714 return false;
715 }
716 if (!CheckEncodedArray()) {
717 return false;
718 }
719 break;
720 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700721 if (UNLIKELY(value_arg != 0)) {
722 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800723 return false;
724 }
725 if (!CheckEncodedAnnotation()) {
726 return false;
727 }
728 break;
729 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700730 if (UNLIKELY(value_arg != 0)) {
731 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800732 return false;
733 }
734 break;
735 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700736 if (UNLIKELY(value_arg > 1)) {
737 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800738 return false;
739 }
740 break;
741 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700742 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800743 return false;
744 }
745
746 return true;
747}
748
749bool DexFileVerifier::CheckEncodedArray() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700750 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800751
752 while (size--) {
753 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700754 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800755 return false;
756 }
757 }
758 return true;
759}
760
761bool DexFileVerifier::CheckEncodedAnnotation() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700762 DECODE_UNSIGNED_CHECKED_FROM(ptr_, anno_idx);
763 if (!CheckIndex(anno_idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -0800764 return false;
765 }
766
Andreas Gampebed6daf2016-09-02 18:12:00 -0700767 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800768 uint32_t last_idx = 0;
769
770 for (uint32_t i = 0; i < size; i++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700771 DECODE_UNSIGNED_CHECKED_FROM(ptr_, idx);
jeffhao10037c82012-01-23 15:06:23 -0800772 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
773 return false;
774 }
775
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700776 if (UNLIKELY(last_idx >= idx && i != 0)) {
777 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
778 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800779 return false;
780 }
781
782 if (!CheckEncodedValue()) {
783 return false;
784 }
785
786 last_idx = idx;
787 }
788 return true;
789}
790
Andreas Gampee6215c02015-08-31 18:54:38 -0700791bool DexFileVerifier::FindClassFlags(uint32_t index,
792 bool is_field,
793 uint16_t* class_type_index,
794 uint32_t* class_access_flags) {
795 DCHECK(class_type_index != nullptr);
796 DCHECK(class_access_flags != nullptr);
797
798 // First check if the index is valid.
799 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
800 return false;
801 }
802
803 // Next get the type index.
804 if (is_field) {
805 *class_type_index =
806 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
807 class_idx_;
808 } else {
809 *class_type_index =
810 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
811 class_idx_;
812 }
813
814 // Check if that is valid.
815 if (*class_type_index >= header_->type_ids_size_) {
816 return false;
817 }
818
819 // Now search for the class def. This is basically a specialized version of the DexFile code, as
820 // we should not trust that this is a valid DexFile just yet.
821 const DexFile::ClassDef* class_def_begin =
822 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
823 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
824 const DexFile::ClassDef* class_def = class_def_begin + i;
825 if (class_def->class_idx_ == *class_type_index) {
826 *class_access_flags = class_def->access_flags_;
827 return true;
828 }
829 }
830
831 // Didn't find the class-def, not defined here...
832 return false;
833}
834
835bool DexFileVerifier::CheckOrderAndGetClassFlags(bool is_field,
836 const char* type_descr,
837 uint32_t curr_index,
838 uint32_t prev_index,
839 bool* have_class,
840 uint16_t* class_type_index,
841 uint32_t* class_access_flags) {
842 if (curr_index < prev_index) {
843 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
844 type_descr,
845 prev_index,
846 curr_index);
847 return false;
848 }
849
850 if (!*have_class) {
851 *have_class = FindClassFlags(curr_index, is_field, class_type_index, class_access_flags);
852 if (!*have_class) {
853 // Should have really found one.
854 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
855 type_descr,
856 curr_index);
857 return false;
858 }
859 }
860 return true;
861}
862
863template <bool kStatic>
864bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
865 bool* have_class,
866 uint16_t* class_type_index,
867 uint32_t* class_access_flags) {
868 DCHECK(it != nullptr);
869 // These calls use the raw access flags to check whether the whole dex field is valid.
870 uint32_t prev_index = 0;
871 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
872 uint32_t curr_index = it->GetMemberIndex();
873 if (!CheckOrderAndGetClassFlags(true,
874 kStatic ? "static field" : "instance field",
875 curr_index,
876 prev_index,
877 have_class,
878 class_type_index,
879 class_access_flags)) {
880 return false;
881 }
882 prev_index = curr_index;
883
884 if (!CheckClassDataItemField(curr_index,
885 it->GetRawMemberAccessFlags(),
886 *class_access_flags,
887 *class_type_index,
888 kStatic)) {
889 return false;
890 }
891 }
892
893 return true;
894}
895
896template <bool kDirect>
897bool DexFileVerifier::CheckIntraClassDataItemMethods(
898 ClassDataItemIterator* it,
899 std::unordered_set<uint32_t>* direct_method_indexes,
900 bool* have_class,
901 uint16_t* class_type_index,
902 uint32_t* class_access_flags) {
903 uint32_t prev_index = 0;
904 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
905 uint32_t curr_index = it->GetMemberIndex();
906 if (!CheckOrderAndGetClassFlags(false,
907 kDirect ? "direct method" : "virtual method",
908 curr_index,
909 prev_index,
910 have_class,
911 class_type_index,
912 class_access_flags)) {
913 return false;
914 }
915 prev_index = curr_index;
916
917 if (!CheckClassDataItemMethod(curr_index,
918 it->GetRawMemberAccessFlags(),
919 *class_access_flags,
920 *class_type_index,
921 it->GetMethodCodeItemOffset(),
922 direct_method_indexes,
923 kDirect)) {
924 return false;
925 }
926 }
927
928 return true;
929}
930
jeffhao10037c82012-01-23 15:06:23 -0800931bool DexFileVerifier::CheckIntraClassDataItem() {
932 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -0700933 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -0800934
Andreas Gampee6215c02015-08-31 18:54:38 -0700935 // This code is complicated by the fact that we don't directly know which class this belongs to.
936 // So we need to explicitly search with the first item we find (either field or method), and then,
937 // as the lookup is expensive, cache the result.
938 bool have_class = false;
939 uint16_t class_type_index;
940 uint32_t class_access_flags;
941
942 // Check fields.
943 if (!CheckIntraClassDataItemFields<true>(&it,
944 &have_class,
945 &class_type_index,
946 &class_access_flags)) {
947 return false;
jeffhao10037c82012-01-23 15:06:23 -0800948 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700949 if (!CheckIntraClassDataItemFields<false>(&it,
950 &have_class,
951 &class_type_index,
952 &class_access_flags)) {
953 return false;
jeffhao10037c82012-01-23 15:06:23 -0800954 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700955
956 // Check methods.
957 if (!CheckIntraClassDataItemMethods<true>(&it,
958 &direct_method_indexes,
959 &have_class,
960 &class_type_index,
961 &class_access_flags)) {
962 return false;
jeffhao10037c82012-01-23 15:06:23 -0800963 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700964 if (!CheckIntraClassDataItemMethods<false>(&it,
965 &direct_method_indexes,
966 &have_class,
967 &class_type_index,
968 &class_access_flags)) {
969 return false;
jeffhao10037c82012-01-23 15:06:23 -0800970 }
971
972 ptr_ = it.EndDataPointer();
973 return true;
974}
975
976bool DexFileVerifier::CheckIntraCodeItem() {
977 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700978 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -0800979 return false;
980 }
981
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700982 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
983 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
984 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800985 return false;
986 }
987
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700988 if (UNLIKELY((code_item->outs_size_ > 5) &&
989 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -0800990 /*
991 * outs_size can be up to 5, even if registers_size is smaller, since the
992 * short forms of method invocation allow repetitions of a register multiple
993 * times within a single parameter list. However, longer parameter lists
994 * need to be represented in-order in the register file.
995 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700996 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
997 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800998 return false;
999 }
1000
1001 const uint16_t* insns = code_item->insns_;
1002 uint32_t insns_size = code_item->insns_size_in_code_units_;
1003 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
1004 return false;
1005 }
1006
1007 // Grab the end of the insns if there are no try_items.
1008 uint32_t try_items_size = code_item->tries_size_;
1009 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001010 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001011 return true;
1012 }
1013
1014 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001015 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001016 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001017 return false;
1018 }
1019
1020 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -08001021 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
1022 return false;
1023 }
1024
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001025 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
Andreas Gampebed6daf2016-09-02 18:12:00 -07001026 DECODE_UNSIGNED_CHECKED_FROM(ptr_, handlers_size);
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001027
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001028 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
1029 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -08001030 return false;
1031 }
1032
Ian Rogers700a4022014-05-19 16:49:03 -07001033 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -07001034 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -08001035 return false;
1036 }
1037
1038 uint32_t last_addr = 0;
1039 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001040 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1041 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001042 return false;
1043 }
1044
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001045 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1046 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001047 return false;
1048 }
1049
1050 uint32_t i;
1051 for (i = 0; i < handlers_size; i++) {
1052 if (try_items->handler_off_ == handler_offsets[i]) {
1053 break;
1054 }
1055 }
1056
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001057 if (UNLIKELY(i == handlers_size)) {
1058 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -08001059 return false;
1060 }
1061
1062 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001063 if (UNLIKELY(last_addr > insns_size)) {
1064 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -08001065 return false;
1066 }
1067
1068 try_items++;
1069 }
1070
1071 return true;
1072}
1073
1074bool DexFileVerifier::CheckIntraStringDataItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001075 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
Ian Rogers13735952014-10-08 12:43:28 -07001076 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001077
1078 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001079 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001080 if (UNLIKELY(ptr_ >= file_end)) {
1081 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001082 return false;
1083 }
1084
1085 uint8_t byte = *(ptr_++);
1086
1087 // Switch on the high 4 bits.
1088 switch (byte >> 4) {
1089 case 0x00:
1090 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001091 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001092 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001093 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001094 return false;
1095 }
1096 break;
1097 case 0x01:
1098 case 0x02:
1099 case 0x03:
1100 case 0x04:
1101 case 0x05:
1102 case 0x06:
1103 case 0x07:
1104 // No extra checks necessary for bit pattern 0xxx.
1105 break;
1106 case 0x08:
1107 case 0x09:
1108 case 0x0a:
1109 case 0x0b:
1110 case 0x0f:
1111 // Illegal bit patterns 10xx or 1111.
1112 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001113 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001114 return false;
1115 case 0x0c:
1116 case 0x0d: {
1117 // Bit pattern 110x has an additional byte.
1118 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001119 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1120 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001121 return false;
1122 }
1123 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001124 if (UNLIKELY((value != 0) && (value < 0x80))) {
1125 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001126 return false;
1127 }
1128 break;
1129 }
1130 case 0x0e: {
1131 // Bit pattern 1110 has 2 additional bytes.
1132 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001133 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1134 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001135 return false;
1136 }
1137 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001138 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1139 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001140 return false;
1141 }
1142 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001143 if (UNLIKELY(value < 0x800)) {
1144 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001145 return false;
1146 }
1147 break;
1148 }
1149 }
1150 }
1151
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001152 if (UNLIKELY(*(ptr_++) != '\0')) {
1153 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001154 return false;
1155 }
1156
1157 return true;
1158}
1159
1160bool DexFileVerifier::CheckIntraDebugInfoItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001161 DECODE_UNSIGNED_CHECKED_FROM(ptr_, dummy);
1162 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameters_size);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001163 if (UNLIKELY(parameters_size > 65536)) {
1164 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001165 return false;
1166 }
1167
1168 for (uint32_t j = 0; j < parameters_size; j++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001169 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameter_name);
jeffhao10037c82012-01-23 15:06:23 -08001170 if (parameter_name != 0) {
1171 parameter_name--;
1172 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1173 return false;
1174 }
1175 }
1176 }
1177
1178 while (true) {
1179 uint8_t opcode = *(ptr_++);
1180 switch (opcode) {
1181 case DexFile::DBG_END_SEQUENCE: {
1182 return true;
1183 }
1184 case DexFile::DBG_ADVANCE_PC: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001185 DECODE_UNSIGNED_CHECKED_FROM(ptr_, advance_pc_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001186 break;
1187 }
1188 case DexFile::DBG_ADVANCE_LINE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001189 DECODE_SIGNED_CHECKED_FROM(ptr_, advance_line_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001190 break;
1191 }
1192 case DexFile::DBG_START_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001193 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001194 if (UNLIKELY(reg_num >= 65536)) {
1195 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001196 return false;
1197 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001198 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001199 if (name_idx != 0) {
1200 name_idx--;
1201 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1202 return false;
1203 }
1204 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001205 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001206 if (type_idx != 0) {
1207 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001208 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001209 return false;
1210 }
1211 }
1212 break;
1213 }
1214 case DexFile::DBG_END_LOCAL:
1215 case DexFile::DBG_RESTART_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001216 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001217 if (UNLIKELY(reg_num >= 65536)) {
1218 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001219 return false;
1220 }
1221 break;
1222 }
1223 case DexFile::DBG_START_LOCAL_EXTENDED: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001224 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001225 if (UNLIKELY(reg_num >= 65536)) {
1226 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001227 return false;
1228 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001229 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001230 if (name_idx != 0) {
1231 name_idx--;
1232 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1233 return false;
1234 }
1235 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001236 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001237 if (type_idx != 0) {
1238 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001239 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001240 return false;
1241 }
1242 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001243 DECODE_UNSIGNED_CHECKED_FROM(ptr_, sig_idx);
jeffhao10037c82012-01-23 15:06:23 -08001244 if (sig_idx != 0) {
1245 sig_idx--;
1246 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1247 return false;
1248 }
1249 }
1250 break;
1251 }
1252 case DexFile::DBG_SET_FILE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001253 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001254 if (name_idx != 0) {
1255 name_idx--;
1256 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1257 return false;
1258 }
1259 }
1260 break;
1261 }
1262 }
1263 }
1264}
1265
1266bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001267 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001268 return false;
1269 }
1270
1271 // Check visibility
1272 switch (*(ptr_++)) {
1273 case DexFile::kDexVisibilityBuild:
1274 case DexFile::kDexVisibilityRuntime:
1275 case DexFile::kDexVisibilitySystem:
1276 break;
1277 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001278 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001279 return false;
1280 }
1281
1282 if (!CheckEncodedAnnotation()) {
1283 return false;
1284 }
1285
1286 return true;
1287}
1288
1289bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1290 const DexFile::AnnotationsDirectoryItem* item =
1291 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001292 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001293 return false;
1294 }
1295
1296 // Field annotations follow immediately after the annotations directory.
1297 const DexFile::FieldAnnotationsItem* field_item =
1298 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1299 uint32_t field_count = item->fields_size_;
1300 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1301 return false;
1302 }
1303
1304 uint32_t last_idx = 0;
1305 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001306 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1307 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001308 return false;
1309 }
1310 last_idx = field_item->field_idx_;
1311 field_item++;
1312 }
1313
1314 // Method annotations follow immediately after field annotations.
1315 const DexFile::MethodAnnotationsItem* method_item =
1316 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1317 uint32_t method_count = item->methods_size_;
1318 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1319 return false;
1320 }
1321
1322 last_idx = 0;
1323 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001324 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1325 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1326 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001327 return false;
1328 }
1329 last_idx = method_item->method_idx_;
1330 method_item++;
1331 }
1332
1333 // Parameter annotations follow immediately after method annotations.
1334 const DexFile::ParameterAnnotationsItem* parameter_item =
1335 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1336 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001337 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001338 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001339 return false;
1340 }
1341
1342 last_idx = 0;
1343 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001344 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1345 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1346 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001347 return false;
1348 }
1349 last_idx = parameter_item->method_idx_;
1350 parameter_item++;
1351 }
1352
1353 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001354 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001355 return true;
1356}
1357
Andreas Gampeb061cc12014-09-02 10:22:20 -07001358bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
1359 uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001360 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001361 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001362 switch (type) {
1363 case DexFile::kDexTypeClassDataItem:
1364 case DexFile::kDexTypeStringDataItem:
1365 case DexFile::kDexTypeDebugInfoItem:
1366 case DexFile::kDexTypeAnnotationItem:
1367 case DexFile::kDexTypeEncodedArrayItem:
1368 alignment_mask = sizeof(uint8_t) - 1;
1369 break;
1370 default:
1371 alignment_mask = sizeof(uint32_t) - 1;
1372 break;
1373 }
1374
1375 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001376 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001377 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001378
1379 // Check the padding between items.
1380 if (!CheckPadding(offset, aligned_offset)) {
1381 return false;
1382 }
1383
1384 // Check depending on the section type.
1385 switch (type) {
1386 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001387 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001388 return false;
1389 }
1390 ptr_ += sizeof(DexFile::StringId);
1391 break;
1392 }
1393 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001394 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001395 return false;
1396 }
1397 ptr_ += sizeof(DexFile::TypeId);
1398 break;
1399 }
1400 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001401 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001402 return false;
1403 }
1404 ptr_ += sizeof(DexFile::ProtoId);
1405 break;
1406 }
1407 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001408 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001409 return false;
1410 }
1411 ptr_ += sizeof(DexFile::FieldId);
1412 break;
1413 }
1414 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001415 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001416 return false;
1417 }
1418 ptr_ += sizeof(DexFile::MethodId);
1419 break;
1420 }
1421 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001422 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001423 return false;
1424 }
1425 ptr_ += sizeof(DexFile::ClassDef);
1426 break;
1427 }
1428 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001429 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001430 return false;
1431 }
jeffhao10037c82012-01-23 15:06:23 -08001432 break;
1433 }
1434 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001435 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001436 return false;
1437 }
jeffhao10037c82012-01-23 15:06:23 -08001438 break;
1439 }
1440 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001441 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001442 return false;
1443 }
jeffhao10037c82012-01-23 15:06:23 -08001444 break;
1445 }
1446 case DexFile::kDexTypeClassDataItem: {
1447 if (!CheckIntraClassDataItem()) {
1448 return false;
1449 }
1450 break;
1451 }
1452 case DexFile::kDexTypeCodeItem: {
1453 if (!CheckIntraCodeItem()) {
1454 return false;
1455 }
1456 break;
1457 }
1458 case DexFile::kDexTypeStringDataItem: {
1459 if (!CheckIntraStringDataItem()) {
1460 return false;
1461 }
1462 break;
1463 }
1464 case DexFile::kDexTypeDebugInfoItem: {
1465 if (!CheckIntraDebugInfoItem()) {
1466 return false;
1467 }
1468 break;
1469 }
1470 case DexFile::kDexTypeAnnotationItem: {
1471 if (!CheckIntraAnnotationItem()) {
1472 return false;
1473 }
1474 break;
1475 }
1476 case DexFile::kDexTypeEncodedArrayItem: {
1477 if (!CheckEncodedArray()) {
1478 return false;
1479 }
1480 break;
1481 }
1482 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1483 if (!CheckIntraAnnotationsDirectoryItem()) {
1484 return false;
1485 }
1486 break;
1487 }
1488 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001489 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001490 return false;
1491 }
1492
1493 if (IsDataSectionType(type)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001494 if (aligned_offset == 0u) {
1495 ErrorStringPrintf("Item %d offset is 0", i);
1496 return false;
1497 }
1498 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1499 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001500 }
1501
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001502 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001503 if (UNLIKELY(aligned_offset > size_)) {
1504 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001505 return false;
1506 }
1507
1508 offset = aligned_offset;
1509 }
1510
1511 return true;
1512}
1513
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001514bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001515 uint32_t expected_offset;
1516 uint32_t expected_size;
1517
1518 // Get the expected offset and size from the header.
1519 switch (type) {
1520 case DexFile::kDexTypeStringIdItem:
1521 expected_offset = header_->string_ids_off_;
1522 expected_size = header_->string_ids_size_;
1523 break;
1524 case DexFile::kDexTypeTypeIdItem:
1525 expected_offset = header_->type_ids_off_;
1526 expected_size = header_->type_ids_size_;
1527 break;
1528 case DexFile::kDexTypeProtoIdItem:
1529 expected_offset = header_->proto_ids_off_;
1530 expected_size = header_->proto_ids_size_;
1531 break;
1532 case DexFile::kDexTypeFieldIdItem:
1533 expected_offset = header_->field_ids_off_;
1534 expected_size = header_->field_ids_size_;
1535 break;
1536 case DexFile::kDexTypeMethodIdItem:
1537 expected_offset = header_->method_ids_off_;
1538 expected_size = header_->method_ids_size_;
1539 break;
1540 case DexFile::kDexTypeClassDefItem:
1541 expected_offset = header_->class_defs_off_;
1542 expected_size = header_->class_defs_size_;
1543 break;
1544 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001545 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001546 return false;
1547 }
1548
1549 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001550 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001551 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001552 return false;
1553 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001554 if (UNLIKELY(count != expected_size)) {
1555 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001556 return false;
1557 }
1558
1559 return CheckIntraSectionIterate(offset, count, type);
1560}
1561
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001562bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count, uint16_t type) {
1563 size_t data_start = header_->data_off_;
1564 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001565
1566 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001567 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001568 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001569 return false;
1570 }
1571
1572 if (!CheckIntraSectionIterate(offset, count, type)) {
1573 return false;
1574 }
1575
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001576 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001577 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001578 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001579 return false;
1580 }
1581
1582 return true;
1583}
1584
1585bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001586 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001587 const DexFile::MapItem* item = map->list_;
1588
1589 uint32_t count = map->size_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001590 size_t offset = 0;
Ian Rogers30fab402012-01-23 15:43:46 -08001591 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001592
1593 // Check the items listed in the map.
1594 while (count--) {
1595 uint32_t section_offset = item->offset_;
1596 uint32_t section_count = item->size_;
1597 uint16_t type = item->type_;
1598
1599 // Check for padding and overlap between items.
1600 if (!CheckPadding(offset, section_offset)) {
1601 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001602 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001603 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001604 return false;
1605 }
1606
1607 // Check each item based on its type.
1608 switch (type) {
1609 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001610 if (UNLIKELY(section_count != 1)) {
1611 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001612 return false;
1613 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001614 if (UNLIKELY(section_offset != 0)) {
1615 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001616 return false;
1617 }
Ian Rogers30fab402012-01-23 15:43:46 -08001618 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001619 offset = header_->header_size_;
1620 break;
1621 case DexFile::kDexTypeStringIdItem:
1622 case DexFile::kDexTypeTypeIdItem:
1623 case DexFile::kDexTypeProtoIdItem:
1624 case DexFile::kDexTypeFieldIdItem:
1625 case DexFile::kDexTypeMethodIdItem:
1626 case DexFile::kDexTypeClassDefItem:
1627 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1628 return false;
1629 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001630 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001631 break;
1632 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001633 if (UNLIKELY(section_count != 1)) {
1634 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001635 return false;
1636 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001637 if (UNLIKELY(section_offset != header_->map_off_)) {
1638 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1639 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001640 return false;
1641 }
1642 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1643 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1644 break;
1645 case DexFile::kDexTypeTypeList:
1646 case DexFile::kDexTypeAnnotationSetRefList:
1647 case DexFile::kDexTypeAnnotationSetItem:
1648 case DexFile::kDexTypeClassDataItem:
1649 case DexFile::kDexTypeCodeItem:
1650 case DexFile::kDexTypeStringDataItem:
1651 case DexFile::kDexTypeDebugInfoItem:
1652 case DexFile::kDexTypeAnnotationItem:
1653 case DexFile::kDexTypeEncodedArrayItem:
1654 case DexFile::kDexTypeAnnotationsDirectoryItem:
1655 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1656 return false;
1657 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001658 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001659 break;
1660 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001661 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001662 return false;
1663 }
1664
1665 item++;
1666 }
1667
1668 return true;
1669}
1670
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001671bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001672 DCHECK_NE(offset, 0u);
1673 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001674 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001675 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001676 return false;
1677 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001678 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001679 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001680 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001681 return false;
1682 }
1683 return true;
1684}
1685
Ian Rogers13735952014-10-08 12:43:28 -07001686uint16_t DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001687 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001688 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001689
1690 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001691 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
1692 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001693 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001694 }
1695
1696 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001697 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
1698 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001699 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001700 }
1701
1702 return DexFile::kDexNoIndex16;
1703}
1704
Ian Rogers13735952014-10-08 12:43:28 -07001705uint16_t DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001706 const DexFile::AnnotationsDirectoryItem* item =
1707 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001708 *success = true;
1709
jeffhao10037c82012-01-23 15:06:23 -08001710 if (item->fields_size_ != 0) {
1711 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001712 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
1713 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001714 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001715 }
1716
1717 if (item->methods_size_ != 0) {
1718 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001719 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001720 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001721 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001722 }
1723
1724 if (item->parameters_size_ != 0) {
1725 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001726 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001727 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001728 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001729 }
1730
1731 return DexFile::kDexNoIndex16;
1732}
1733
1734bool DexFileVerifier::CheckInterStringIdItem() {
1735 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1736
1737 // Check the map to make sure it has the right offset->type.
1738 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1739 return false;
1740 }
1741
1742 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001743 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001744 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1745 const char* prev_str = dex_file_->GetStringData(*prev_item);
1746 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001747 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1748 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001749 return false;
1750 }
1751 }
1752
1753 ptr_ += sizeof(DexFile::StringId);
1754 return true;
1755}
1756
1757bool DexFileVerifier::CheckInterTypeIdItem() {
1758 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001759
1760 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001761
1762 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001763 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1764 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001765 return false;
1766 }
1767
1768 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001769 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001770 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001771 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1772 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
1773 prev_item->descriptor_idx_, item->descriptor_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001774 return false;
1775 }
1776 }
1777
1778 ptr_ += sizeof(DexFile::TypeId);
1779 return true;
1780}
1781
1782bool DexFileVerifier::CheckInterProtoIdItem() {
1783 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001784
1785 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1786
jeffhao10037c82012-01-23 15:06:23 -08001787 if (item->parameters_off_ != 0 &&
1788 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1789 return false;
1790 }
1791
1792 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001793 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1794 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001795 return false;
1796 }
1797 shorty++;
1798
1799 DexFileParameterIterator it(*dex_file_, *item);
1800 while (it.HasNext() && *shorty != '\0') {
Andreas Gampebb836e12014-06-13 15:31:40 -07001801 if (!CheckIndex(it.GetTypeIdx(), dex_file_->NumTypeIds(),
1802 "inter_proto_id_item shorty type_idx")) {
1803 return false;
1804 }
jeffhao10037c82012-01-23 15:06:23 -08001805 const char* descriptor = it.GetDescriptor();
1806 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1807 return false;
1808 }
1809 it.Next();
1810 shorty++;
1811 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001812 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1813 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001814 return false;
1815 }
1816
1817 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001818 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001819 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001820 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1821 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001822 return false;
1823 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1824 DexFileParameterIterator curr_it(*dex_file_, *item);
1825 DexFileParameterIterator prev_it(*dex_file_, *prev);
1826
1827 while (curr_it.HasNext() && prev_it.HasNext()) {
1828 uint16_t prev_idx = prev_it.GetTypeIdx();
1829 uint16_t curr_idx = curr_it.GetTypeIdx();
Vladimir Marko0ca8add2016-05-03 17:17:50 +01001830 DCHECK_NE(prev_idx, DexFile::kDexNoIndex16);
1831 DCHECK_NE(curr_idx, DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001832
1833 if (prev_idx < curr_idx) {
1834 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001835 } else if (UNLIKELY(prev_idx > curr_idx)) {
1836 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001837 return false;
1838 }
1839
1840 prev_it.Next();
1841 curr_it.Next();
1842 }
Vladimir Marko0ca8add2016-05-03 17:17:50 +01001843 if (!curr_it.HasNext()) {
1844 // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
1845 // a ProtoId with a longer one. Both cases are forbidden by the specification.
1846 ErrorStringPrintf("Out-of-order proto_id arguments");
1847 return false;
1848 }
jeffhao10037c82012-01-23 15:06:23 -08001849 }
1850 }
1851
1852 ptr_ += sizeof(DexFile::ProtoId);
1853 return true;
1854}
1855
1856bool DexFileVerifier::CheckInterFieldIdItem() {
1857 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1858
1859 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001860 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1861 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1862 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001863 return false;
1864 }
1865
1866 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001867 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1868 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1869 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001870 return false;
1871 }
1872
1873 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001874 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001875 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1876 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001877 return false;
1878 }
1879
1880 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001881 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001882 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001883 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1884 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001885 return false;
1886 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001887 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1888 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001889 return false;
1890 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001891 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
1892 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001893 return false;
1894 }
1895 }
1896 }
1897 }
1898
1899 ptr_ += sizeof(DexFile::FieldId);
1900 return true;
1901}
1902
1903bool DexFileVerifier::CheckInterMethodIdItem() {
1904 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
1905
1906 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001907 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
1908 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
1909 class_descriptor[0] != '['))) {
1910 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001911 return false;
1912 }
1913
1914 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07001915 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001916 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1917 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001918 return false;
1919 }
1920
Andreas Gampedf10b322014-06-11 21:46:05 -07001921 // Check that the proto id is valid.
1922 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
1923 "inter_method_id_item proto_idx"))) {
1924 return false;
1925 }
1926
jeffhao10037c82012-01-23 15:06:23 -08001927 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001928 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001929 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001930 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1931 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001932 return false;
1933 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001934 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1935 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001936 return false;
1937 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001938 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
1939 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001940 return false;
1941 }
1942 }
1943 }
1944 }
1945
1946 ptr_ += sizeof(DexFile::MethodId);
1947 return true;
1948}
1949
1950bool DexFileVerifier::CheckInterClassDefItem() {
1951 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001952
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001953 // Check for duplicate class def.
1954 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
1955 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_);
1956 return false;
1957 }
1958 defined_classes_.insert(item->class_idx_);
1959
Andreas Gampee09269c2014-06-06 18:45:35 -07001960 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
1961 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1962 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001963 return false;
1964 }
1965
Andreas Gampeacc2bb62014-07-17 19:26:50 -07001966 // Only allow non-runtime modifiers.
1967 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
1968 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
1969 return false;
1970 }
1971
jeffhao10037c82012-01-23 15:06:23 -08001972 if (item->interfaces_off_ != 0 &&
1973 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
1974 return false;
1975 }
1976 if (item->annotations_off_ != 0 &&
1977 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
1978 return false;
1979 }
1980 if (item->class_data_off_ != 0 &&
1981 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
1982 return false;
1983 }
1984 if (item->static_values_off_ != 0 &&
1985 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
1986 return false;
1987 }
1988
1989 if (item->superclass_idx_ != DexFile::kDexNoIndex16) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01001990 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
1991 // Check that a class does not inherit from itself directly (by having
1992 // the same type idx as its super class).
1993 if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
1994 ErrorStringPrintf("Class with same type idx as its superclass: '%d'", item->class_idx_);
1995 return false;
1996 }
1997
1998 // Check that a class is defined after its super class (if the
1999 // latter is defined in the same Dex file).
2000 const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
2001 if (superclass_def != nullptr) {
2002 // The superclass is defined in this Dex file.
2003 if (superclass_def > item) {
2004 // ClassDef item for super class appearing after the class' ClassDef item.
2005 ErrorStringPrintf("Invalid class definition ordering:"
2006 " class with type idx: '%d' defined before"
2007 " superclass with type idx: '%d'",
2008 item->class_idx_,
2009 item->superclass_idx_);
2010 return false;
2011 }
2012 }
2013 }
2014
Andreas Gampee09269c2014-06-06 18:45:35 -07002015 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
2016 "inter_class_def_item superclass_idx")
2017 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
2018 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002019 return false;
2020 }
2021 }
2022
Roland Levillain621b5ea2016-05-18 11:41:33 +01002023 // Check interfaces.
jeffhao10037c82012-01-23 15:06:23 -08002024 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002025 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002026 uint32_t size = interfaces->Size();
jeffhao10037c82012-01-23 15:06:23 -08002027 for (uint32_t i = 0; i < size; i++) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002028 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2029 // Check that a class does not implement itself directly (by having the
2030 // same type idx as one of its immediate implemented interfaces).
2031 if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2032 ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
2033 item->class_idx_);
2034 return false;
2035 }
2036
2037 // Check that a class is defined after the interfaces it implements
2038 // (if they are defined in the same Dex file).
2039 const DexFile::ClassDef* interface_def =
2040 dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2041 if (interface_def != nullptr) {
2042 // The interface is defined in this Dex file.
2043 if (interface_def > item) {
2044 // ClassDef item for interface appearing after the class' ClassDef item.
2045 ErrorStringPrintf("Invalid class definition ordering:"
2046 " class with type idx: '%d' defined before"
2047 " implemented interface with type idx: '%d'",
2048 item->class_idx_,
2049 interfaces->GetTypeItem(i).type_idx_);
2050 return false;
2051 }
2052 }
2053 }
2054
2055 // Ensure that the interface refers to a class (not an array nor a primitive type).
Andreas Gampee09269c2014-06-06 18:45:35 -07002056 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2057 "inter_class_def_item interface type_idx")
2058 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2059 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002060 return false;
2061 }
2062 }
2063
2064 /*
2065 * Ensure that there are no duplicates. This is an O(N^2) test, but in
2066 * practice the number of interfaces implemented by any given class is low.
2067 */
2068 for (uint32_t i = 1; i < size; i++) {
2069 uint32_t idx1 = interfaces->GetTypeItem(i).type_idx_;
2070 for (uint32_t j =0; j < i; j++) {
2071 uint32_t idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002072 if (UNLIKELY(idx1 == idx2)) {
2073 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08002074 return false;
2075 }
2076 }
2077 }
2078 }
2079
2080 // Check that references in class_data_item are to the right class.
2081 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07002082 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002083 bool success;
2084 uint16_t data_definer = FindFirstClassDataDefiner(data, &success);
2085 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002086 return false;
2087 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002088 if (UNLIKELY((data_definer != item->class_idx_) && (data_definer != DexFile::kDexNoIndex16))) {
2089 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08002090 return false;
2091 }
2092 }
2093
2094 // Check that references in annotations_directory_item are to right class.
2095 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002096 // annotations_off_ is supposed to be aligned by 4.
2097 if (!IsAlignedParam(item->annotations_off_, 4)) {
2098 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2099 return false;
2100 }
Ian Rogers13735952014-10-08 12:43:28 -07002101 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002102 bool success;
2103 uint16_t annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
2104 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002105 return false;
2106 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002107 if (UNLIKELY((annotations_definer != item->class_idx_) &&
2108 (annotations_definer != DexFile::kDexNoIndex16))) {
2109 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002110 return false;
2111 }
2112 }
2113
2114 ptr_ += sizeof(DexFile::ClassDef);
2115 return true;
2116}
2117
2118bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2119 const DexFile::AnnotationSetRefList* list =
2120 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2121 const DexFile::AnnotationSetRefItem* item = list->list_;
2122 uint32_t count = list->size_;
2123
2124 while (count--) {
2125 if (item->annotations_off_ != 0 &&
2126 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2127 return false;
2128 }
2129 item++;
2130 }
2131
Ian Rogers13735952014-10-08 12:43:28 -07002132 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002133 return true;
2134}
2135
2136bool DexFileVerifier::CheckInterAnnotationSetItem() {
2137 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2138 const uint32_t* offsets = set->entries_;
2139 uint32_t count = set->size_;
2140 uint32_t last_idx = 0;
2141
2142 for (uint32_t i = 0; i < count; i++) {
2143 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2144 return false;
2145 }
2146
2147 // Get the annotation from the offset and the type index for the annotation.
2148 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002149 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002150 const uint8_t* data = annotation->annotation_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002151 DECODE_UNSIGNED_CHECKED_FROM(data, idx);
jeffhao10037c82012-01-23 15:06:23 -08002152
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002153 if (UNLIKELY(last_idx >= idx && i != 0)) {
2154 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002155 return false;
2156 }
2157
2158 last_idx = idx;
2159 offsets++;
2160 }
2161
Ian Rogers13735952014-10-08 12:43:28 -07002162 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002163 return true;
2164}
2165
2166bool DexFileVerifier::CheckInterClassDataItem() {
2167 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002168 bool success;
2169 uint16_t defining_class = FindFirstClassDataDefiner(ptr_, &success);
2170 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002171 return false;
2172 }
jeffhao10037c82012-01-23 15:06:23 -08002173
2174 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002175 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002176 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002177 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002178 return false;
2179 }
2180 }
2181 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2182 uint32_t code_off = it.GetMethodCodeItemOffset();
2183 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2184 return false;
2185 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002186 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002187 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002188 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002189 return false;
2190 }
2191 }
2192
2193 ptr_ = it.EndDataPointer();
2194 return true;
2195}
2196
2197bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2198 const DexFile::AnnotationsDirectoryItem* item =
2199 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002200 bool success;
2201 uint16_t defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
2202 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002203 return false;
2204 }
jeffhao10037c82012-01-23 15:06:23 -08002205
2206 if (item->class_annotations_off_ != 0 &&
2207 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2208 return false;
2209 }
2210
2211 // Field annotations follow immediately after the annotations directory.
2212 const DexFile::FieldAnnotationsItem* field_item =
2213 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2214 uint32_t field_count = item->fields_size_;
2215 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002216 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2217 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002218 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002219 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002220 return false;
2221 }
2222 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2223 return false;
2224 }
2225 field_item++;
2226 }
2227
2228 // Method annotations follow immediately after field annotations.
2229 const DexFile::MethodAnnotationsItem* method_item =
2230 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2231 uint32_t method_count = item->methods_size_;
2232 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002233 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002234 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002235 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002236 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002237 return false;
2238 }
2239 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2240 return false;
2241 }
2242 method_item++;
2243 }
2244
2245 // Parameter annotations follow immediately after method annotations.
2246 const DexFile::ParameterAnnotationsItem* parameter_item =
2247 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2248 uint32_t parameter_count = item->parameters_size_;
2249 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002250 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002251 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002252 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002253 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002254 return false;
2255 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002256 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2257 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002258 return false;
2259 }
2260 parameter_item++;
2261 }
2262
Ian Rogers13735952014-10-08 12:43:28 -07002263 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002264 return true;
2265}
2266
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002267bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002268 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002269 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002270 switch (type) {
2271 case DexFile::kDexTypeClassDataItem:
2272 alignment_mask = sizeof(uint8_t) - 1;
2273 break;
2274 default:
2275 alignment_mask = sizeof(uint32_t) - 1;
2276 break;
2277 }
2278
2279 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002280 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002281 for (uint32_t i = 0; i < count; i++) {
2282 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002283 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002284 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002285
2286 // Check depending on the section type.
2287 switch (type) {
2288 case DexFile::kDexTypeStringIdItem: {
2289 if (!CheckInterStringIdItem()) {
2290 return false;
2291 }
2292 break;
2293 }
2294 case DexFile::kDexTypeTypeIdItem: {
2295 if (!CheckInterTypeIdItem()) {
2296 return false;
2297 }
2298 break;
2299 }
2300 case DexFile::kDexTypeProtoIdItem: {
2301 if (!CheckInterProtoIdItem()) {
2302 return false;
2303 }
2304 break;
2305 }
2306 case DexFile::kDexTypeFieldIdItem: {
2307 if (!CheckInterFieldIdItem()) {
2308 return false;
2309 }
2310 break;
2311 }
2312 case DexFile::kDexTypeMethodIdItem: {
2313 if (!CheckInterMethodIdItem()) {
2314 return false;
2315 }
2316 break;
2317 }
2318 case DexFile::kDexTypeClassDefItem: {
2319 if (!CheckInterClassDefItem()) {
2320 return false;
2321 }
2322 break;
2323 }
2324 case DexFile::kDexTypeAnnotationSetRefList: {
2325 if (!CheckInterAnnotationSetRefList()) {
2326 return false;
2327 }
2328 break;
2329 }
2330 case DexFile::kDexTypeAnnotationSetItem: {
2331 if (!CheckInterAnnotationSetItem()) {
2332 return false;
2333 }
2334 break;
2335 }
2336 case DexFile::kDexTypeClassDataItem: {
2337 if (!CheckInterClassDataItem()) {
2338 return false;
2339 }
2340 break;
2341 }
2342 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2343 if (!CheckInterAnnotationsDirectoryItem()) {
2344 return false;
2345 }
2346 break;
2347 }
2348 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002349 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002350 return false;
2351 }
2352
2353 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002354 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002355 }
2356
2357 return true;
2358}
2359
2360bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002361 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002362 const DexFile::MapItem* item = map->list_;
2363 uint32_t count = map->size_;
2364
2365 // Cross check the items listed in the map.
2366 while (count--) {
2367 uint32_t section_offset = item->offset_;
2368 uint32_t section_count = item->size_;
2369 uint16_t type = item->type_;
2370
2371 switch (type) {
2372 case DexFile::kDexTypeHeaderItem:
2373 case DexFile::kDexTypeMapList:
2374 case DexFile::kDexTypeTypeList:
2375 case DexFile::kDexTypeCodeItem:
2376 case DexFile::kDexTypeStringDataItem:
2377 case DexFile::kDexTypeDebugInfoItem:
2378 case DexFile::kDexTypeAnnotationItem:
2379 case DexFile::kDexTypeEncodedArrayItem:
2380 break;
2381 case DexFile::kDexTypeStringIdItem:
2382 case DexFile::kDexTypeTypeIdItem:
2383 case DexFile::kDexTypeProtoIdItem:
2384 case DexFile::kDexTypeFieldIdItem:
2385 case DexFile::kDexTypeMethodIdItem:
2386 case DexFile::kDexTypeClassDefItem:
2387 case DexFile::kDexTypeAnnotationSetRefList:
2388 case DexFile::kDexTypeAnnotationSetItem:
2389 case DexFile::kDexTypeClassDataItem:
2390 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2391 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2392 return false;
2393 }
2394 break;
2395 }
2396 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002397 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002398 return false;
2399 }
2400
2401 item++;
2402 }
2403
2404 return true;
2405}
2406
2407bool DexFileVerifier::Verify() {
2408 // Check the header.
2409 if (!CheckHeader()) {
2410 return false;
2411 }
2412
2413 // Check the map section.
2414 if (!CheckMap()) {
2415 return false;
2416 }
2417
2418 // Check structure within remaining sections.
2419 if (!CheckIntraSection()) {
2420 return false;
2421 }
2422
2423 // Check references from one section to another.
2424 if (!CheckInterSection()) {
2425 return false;
2426 }
2427
2428 return true;
2429}
2430
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002431void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2432 va_list ap;
2433 va_start(ap, fmt);
2434 DCHECK(failure_reason_.empty()) << failure_reason_;
2435 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2436 StringAppendV(&failure_reason_, fmt, ap);
2437 va_end(ap);
2438}
2439
Andreas Gampee6215c02015-08-31 18:54:38 -07002440// Fields and methods may have only one of public/protected/private.
2441static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2442 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2443 (((flags & kAccProtected) == 0) ? 0 : 1) +
2444 (((flags & kAccPrivate) == 0) ? 0 : 1);
2445 return count <= 1;
2446}
2447
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002448// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2449// functionality, as we're still verifying the dex file. begin and header correspond to the
2450// underscored variants in the DexFileVerifier.
2451
2452static std::string GetStringOrError(const uint8_t* const begin,
2453 const DexFile::Header* const header,
2454 uint32_t string_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002455 // The `string_idx` is not guaranteed to be valid yet.
2456 if (header->string_ids_size_ <= string_idx) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002457 return "(error)";
2458 }
2459
2460 const DexFile::StringId* string_id =
2461 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx;
2462
2463 // Assume that the data is OK at this point. String data has been checked at this point.
2464
2465 const uint8_t* ptr = begin + string_id->string_data_off_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002466 uint32_t dummy;
2467 if (!DecodeUnsignedLeb128Checked(&ptr, begin + header->file_size_, &dummy)) {
2468 return "(error)";
2469 }
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002470 return reinterpret_cast<const char*>(ptr);
2471}
2472
2473static std::string GetClassOrError(const uint8_t* const begin,
2474 const DexFile::Header* const header,
2475 uint32_t class_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002476 // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2477 // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2478 // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2479 // a valid defining class.
2480 CHECK_LT(class_idx, header->type_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002481
2482 const DexFile::TypeId* type_id =
2483 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx;
2484
2485 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2486
2487 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2488}
2489
2490static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2491 const DexFile::Header* const header,
2492 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002493 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2494 CHECK_LT(idx, header->field_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002495
2496 const DexFile::FieldId* field_id =
2497 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2498
2499 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2500
2501 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2502 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2503
2504 return class_name + "." + field_name;
2505}
2506
2507static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2508 const DexFile::Header* const header,
2509 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002510 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2511 CHECK_LT(idx, header->method_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002512
2513 const DexFile::MethodId* method_id =
2514 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2515
2516 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2517
2518 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2519 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2520
2521 return class_name + "." + method_name;
2522}
2523
2524bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2525 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002526 uint32_t class_access_flags,
2527 std::string* error_msg) {
2528 // Generally sort out >16-bit flags.
2529 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002530 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2531 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2532 field_access_flags,
2533 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002534 return false;
2535 }
2536
2537 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2538 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2539 kAccPrivate |
2540 kAccProtected |
2541 kAccStatic |
2542 kAccFinal |
2543 kAccVolatile |
2544 kAccTransient |
2545 kAccSynthetic |
2546 kAccEnum;
2547
2548 // Fields may have only one of public/protected/final.
2549 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002550 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2551 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2552 field_access_flags,
2553 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002554 return false;
2555 }
2556
2557 // Interfaces have a pretty restricted list.
2558 if ((class_access_flags & kAccInterface) != 0) {
2559 // Interface fields must be public final static.
2560 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2561 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002562 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2563 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2564 field_access_flags,
2565 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002566 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002567 return false;
2568 } else {
2569 // Allow in older versions, but warn.
2570 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2571 << *error_msg;
2572 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002573 }
2574 // Interface fields may be synthetic, but may not have other flags.
2575 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2576 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002577 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
2578 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2579 field_access_flags,
2580 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002581 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002582 return false;
2583 } else {
2584 // Allow in older versions, but warn.
2585 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2586 << *error_msg;
2587 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002588 }
2589 return true;
2590 }
2591
2592 // Volatile fields may not be final.
2593 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2594 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002595 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
2596 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002597 return false;
2598 }
2599
2600 return true;
2601}
2602
2603// Try to find the name of the method with the given index. We do not want to rely on DexFile
2604// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
2605// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
2606// (flagged by the return value), otherwise error_msg will contain an error string.
2607static bool FindMethodName(uint32_t method_index,
2608 const uint8_t* begin,
2609 const DexFile::Header* header,
2610 const char** str,
2611 std::string* error_msg) {
2612 if (method_index >= header->method_ids_size_) {
2613 *error_msg = "Method index not available for method flags verification";
2614 return false;
2615 }
2616 uint32_t string_idx =
2617 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
2618 method_index)->name_idx_;
2619 if (string_idx >= header->string_ids_size_) {
2620 *error_msg = "String index not available for method flags verification";
2621 return false;
2622 }
2623 uint32_t string_off =
2624 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
2625 string_data_off_;
2626 if (string_off >= header->file_size_) {
2627 *error_msg = "String offset out of bounds for method flags verification";
2628 return false;
2629 }
2630 const uint8_t* str_data_ptr = begin + string_off;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002631 uint32_t dummy;
2632 if (!DecodeUnsignedLeb128Checked(&str_data_ptr, begin + header->file_size_, &dummy)) {
2633 *error_msg = "String size out of bounds for method flags verification";
2634 return false;
2635 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002636 *str = reinterpret_cast<const char*>(str_data_ptr);
2637 return true;
2638}
2639
2640bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2641 uint32_t method_access_flags,
2642 uint32_t class_access_flags,
2643 bool has_code,
2644 bool expect_direct,
2645 std::string* error_msg) {
2646 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2647 constexpr uint32_t kAllMethodFlags =
2648 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2649 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002650 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
2651 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2652 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002653 return false;
2654 }
2655
2656 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2657 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2658 kAccPrivate |
2659 kAccProtected |
2660 kAccStatic |
2661 kAccFinal |
2662 kAccSynthetic |
2663 kAccSynchronized |
2664 kAccBridge |
2665 kAccVarargs |
2666 kAccNative |
2667 kAccAbstract |
2668 kAccStrict;
2669
2670 // Methods may have only one of public/protected/final.
2671 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002672 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
2673 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002674 method_access_flags);
2675 return false;
2676 }
2677
2678 // Try to find the name, to check for constructor properties.
2679 const char* str;
2680 if (!FindMethodName(method_index, begin_, header_, &str, error_msg)) {
2681 return false;
2682 }
2683 bool is_init_by_name = false;
2684 constexpr const char* kInitName = "<init>";
2685 size_t str_offset = (reinterpret_cast<const uint8_t*>(str) - begin_);
2686 if (header_->file_size_ - str_offset >= sizeof(kInitName)) {
2687 is_init_by_name = strcmp(kInitName, str) == 0;
2688 }
2689 bool is_clinit_by_name = false;
2690 constexpr const char* kClinitName = "<clinit>";
2691 if (header_->file_size_ - str_offset >= sizeof(kClinitName)) {
2692 is_clinit_by_name = strcmp(kClinitName, str) == 0;
2693 }
2694 bool is_constructor = is_init_by_name || is_clinit_by_name;
2695
2696 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2697 // the reverse for backwards compatibility reasons.
2698 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002699 *error_msg =
2700 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
2701 method_index,
2702 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002703 return false;
2704 }
2705 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2706 // instance constructor is called "<init>".
2707 if (is_constructor) {
2708 bool is_static = (method_access_flags & kAccStatic) != 0;
2709 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002710 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
2711 method_index,
2712 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002713 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2714 return false;
2715 } else {
2716 // Allow in older versions, but warn.
2717 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2718 << *error_msg;
2719 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002720 }
2721 }
2722 // Check that static and private methods, as well as constructors, are in the direct methods list,
2723 // and other methods in the virtual methods list.
2724 bool is_direct = (method_access_flags & (kAccStatic | kAccPrivate)) != 0 || is_constructor;
2725 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002726 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07002727 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002728 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002729 expect_direct);
2730 return false;
2731 }
2732
2733
2734 // From here on out it is easier to mask out the bits we're supposed to ignore.
2735 method_access_flags &= kMethodAccessFlags;
2736
Alex Lightd7c10c22016-03-31 10:03:07 -07002737 // Interfaces are special.
2738 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07002739 // Non-static interface methods must be public or private.
2740 uint32_t desired_flags = (kAccPublic | kAccStatic);
2741 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2742 desired_flags |= kAccPrivate;
2743 }
2744 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002745 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
2746 method_index,
2747 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002748 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002749 return false;
2750 } else {
2751 // Allow in older versions, but warn.
2752 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2753 << *error_msg;
2754 }
2755 }
2756 }
2757
Andreas Gampee6215c02015-08-31 18:54:38 -07002758 // If there aren't any instructions, make sure that's expected.
2759 if (!has_code) {
2760 // Only native or abstract methods may not have code.
2761 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002762 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07002763 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002764 method_index,
2765 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002766 return false;
2767 }
2768 // Constructors must always have code.
2769 if (is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002770 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
2771 method_index,
2772 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002773 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2774 return false;
2775 } else {
2776 // Allow in older versions, but warn.
2777 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2778 << *error_msg;
2779 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002780 }
2781 if ((method_access_flags & kAccAbstract) != 0) {
2782 // Abstract methods are not allowed to have the following flags.
2783 constexpr uint32_t kForbidden =
2784 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2785 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002786 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
2787 method_index,
2788 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2789 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002790 return false;
2791 }
Andreas Gampe97b11352015-12-10 16:23:41 -08002792 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07002793 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002794 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08002795 << " is abstract, but the declaring class is neither abstract nor an "
2796 << "interface in dex file "
2797 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07002798 }
2799 }
2800 // Interfaces are special.
2801 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002802 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07002803 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002804 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
2805 method_index,
2806 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002807 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002808 return false;
2809 } else {
2810 // Allow in older versions, but warn.
2811 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2812 << *error_msg;
2813 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002814 }
2815 // At this point, we know the method is public and abstract. This means that all the checks
2816 // for invalid combinations above applies. In addition, interface methods must not be
2817 // protected. This is caught by the check for only-one-of-public-protected-private.
2818 }
2819 return true;
2820 }
2821
2822 // When there's code, the method must not be native or abstract.
2823 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002824 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
2825 method_index,
2826 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002827 return false;
2828 }
2829
Andreas Gampee6215c02015-08-31 18:54:38 -07002830 // Instance constructors must not be synchronized and a few other flags.
2831 if (is_init_by_name) {
2832 static constexpr uint32_t kInitAllowed =
2833 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2834 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002835 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07002836 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002837 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002838 method_access_flags);
2839 return false;
2840 }
2841 }
2842
2843 return true;
2844}
2845
jeffhao10037c82012-01-23 15:06:23 -08002846} // namespace art