blob: 68e9f73927454d3a31837f8f93a26cd7405671a9 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
jeffhao10037c82012-01-23 15:06:23 -080016
17#include "dex_file_verifier.h"
18
Andreas Gampee6215c02015-08-31 18:54:38 -070019#include <inttypes.h>
Narayan Kamath92572be2013-11-28 14:06:24 +000020#include <zlib.h>
Andreas Gampee6215c02015-08-31 18:54:38 -070021
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Narayan Kamath92572be2013-11-28 14:06:24 +000023
Elliott Hughese222ee02012-12-13 14:41:43 -080024#include "base/stringprintf.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070025#include "dex_file-inl.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070026#include "experimental_flags.h"
jeffhao10037c82012-01-23 15:06:23 -080027#include "leb128.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070028#include "safe_map.h"
Ian Rogersa6724902013-09-23 09:23:37 -070029#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "utils.h"
jeffhao10037c82012-01-23 15:06:23 -080031
32namespace art {
33
34static uint32_t MapTypeToBitMask(uint32_t map_type) {
35 switch (map_type) {
36 case DexFile::kDexTypeHeaderItem: return 1 << 0;
37 case DexFile::kDexTypeStringIdItem: return 1 << 1;
38 case DexFile::kDexTypeTypeIdItem: return 1 << 2;
39 case DexFile::kDexTypeProtoIdItem: return 1 << 3;
40 case DexFile::kDexTypeFieldIdItem: return 1 << 4;
41 case DexFile::kDexTypeMethodIdItem: return 1 << 5;
42 case DexFile::kDexTypeClassDefItem: return 1 << 6;
43 case DexFile::kDexTypeMapList: return 1 << 7;
44 case DexFile::kDexTypeTypeList: return 1 << 8;
45 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9;
46 case DexFile::kDexTypeAnnotationSetItem: return 1 << 10;
47 case DexFile::kDexTypeClassDataItem: return 1 << 11;
48 case DexFile::kDexTypeCodeItem: return 1 << 12;
49 case DexFile::kDexTypeStringDataItem: return 1 << 13;
50 case DexFile::kDexTypeDebugInfoItem: return 1 << 14;
51 case DexFile::kDexTypeAnnotationItem: return 1 << 15;
52 case DexFile::kDexTypeEncodedArrayItem: return 1 << 16;
53 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17;
54 }
55 return 0;
56}
57
58static bool IsDataSectionType(uint32_t map_type) {
59 switch (map_type) {
60 case DexFile::kDexTypeHeaderItem:
61 case DexFile::kDexTypeStringIdItem:
62 case DexFile::kDexTypeTypeIdItem:
63 case DexFile::kDexTypeProtoIdItem:
64 case DexFile::kDexTypeFieldIdItem:
65 case DexFile::kDexTypeMethodIdItem:
66 case DexFile::kDexTypeClassDefItem:
67 return false;
68 }
69 return true;
70}
71
Andreas Gampee09269c2014-06-06 18:45:35 -070072const char* DexFileVerifier::CheckLoadStringByIdx(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070073 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070074 return nullptr;
75 }
76 return dex_file_->StringDataByIdx(idx);
77}
78
Andreas Gampea5b09a62016-11-17 15:21:22 -080079const char* DexFileVerifier::CheckLoadStringByTypeIdx(dex::TypeIndex type_idx,
80 const char* error_string) {
81 if (UNLIKELY(!CheckIndex(type_idx.index_, 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; \
Andreas Gampe44fd2352016-11-03 08:21:21 -0700460 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700461 return error_value; \
462 }
463
Andreas Gampe44fd2352016-11-03 08:21:21 -0700464#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; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700469 }
470
Andreas Gampe44fd2352016-11-03 08:21:21 -0700471#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; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700476 }
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 Gampea5b09a62016-11-17 15:21:22 -0800529 dex::TypeIndex 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.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800537 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700538 (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,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800542 my_class_index.index_,
543 class_type_index.index_);
Andreas Gampee6215c02015-08-31 18:54:38 -0700544 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 Gampea5b09a62016-11-17 15:21:22 -0800567 dex::TypeIndex 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.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800578 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700579 (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,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800583 my_class_index.index_,
584 class_type_index.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,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800793 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700794 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.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800815 if (class_type_index->index_ >= header_->type_ids_size_) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700816 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,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800840 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700841 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,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800866 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700867 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,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800901 dex::TypeIndex* class_type_index,
Andreas Gampee6215c02015-08-31 18:54:38 -0700902 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;
Andreas Gampea5b09a62016-11-17 15:21:22 -0800939 dex::TypeIndex class_type_index;
Andreas Gampee6215c02015-08-31 18:54:38 -0700940 uint32_t class_access_flags;
941
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
Andreas Gampea5b09a62016-11-17 15:21:22 -08001686dex::TypeIndex 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",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001692 *success = false; return dex::TypeIndex(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",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001698 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001699 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001700 }
1701
Andreas Gampea5b09a62016-11-17 15:21:22 -08001702 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001703}
1704
Andreas Gampea5b09a62016-11-17 15:21:22 -08001705dex::TypeIndex DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr,
1706 bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001707 const DexFile::AnnotationsDirectoryItem* item =
1708 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001709 *success = true;
1710
jeffhao10037c82012-01-23 15:06:23 -08001711 if (item->fields_size_ != 0) {
1712 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001713 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001714 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001715 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001716 }
1717
1718 if (item->methods_size_ != 0) {
1719 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001720 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001721 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001722 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001723 }
1724
1725 if (item->parameters_size_ != 0) {
1726 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001727 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001728 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001729 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001730 }
1731
Andreas Gampea5b09a62016-11-17 15:21:22 -08001732 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001733}
1734
1735bool DexFileVerifier::CheckInterStringIdItem() {
1736 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1737
1738 // Check the map to make sure it has the right offset->type.
1739 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1740 return false;
1741 }
1742
1743 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001744 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001745 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1746 const char* prev_str = dex_file_->GetStringData(*prev_item);
1747 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001748 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1749 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001750 return false;
1751 }
1752 }
1753
1754 ptr_ += sizeof(DexFile::StringId);
1755 return true;
1756}
1757
1758bool DexFileVerifier::CheckInterTypeIdItem() {
1759 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001760
1761 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001762
1763 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001764 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1765 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001766 return false;
1767 }
1768
1769 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001770 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001771 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001772 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1773 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
1774 prev_item->descriptor_idx_, item->descriptor_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001775 return false;
1776 }
1777 }
1778
1779 ptr_ += sizeof(DexFile::TypeId);
1780 return true;
1781}
1782
1783bool DexFileVerifier::CheckInterProtoIdItem() {
1784 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001785
1786 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1787
jeffhao10037c82012-01-23 15:06:23 -08001788 if (item->parameters_off_ != 0 &&
1789 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1790 return false;
1791 }
1792
1793 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001794 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1795 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001796 return false;
1797 }
1798 shorty++;
1799
1800 DexFileParameterIterator it(*dex_file_, *item);
1801 while (it.HasNext() && *shorty != '\0') {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001802 if (!CheckIndex(it.GetTypeIdx().index_,
1803 dex_file_->NumTypeIds(),
Andreas Gampebb836e12014-06-13 15:31:40 -07001804 "inter_proto_id_item shorty type_idx")) {
1805 return false;
1806 }
jeffhao10037c82012-01-23 15:06:23 -08001807 const char* descriptor = it.GetDescriptor();
1808 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1809 return false;
1810 }
1811 it.Next();
1812 shorty++;
1813 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001814 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1815 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001816 return false;
1817 }
1818
1819 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001820 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001821 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001822 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1823 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001824 return false;
1825 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1826 DexFileParameterIterator curr_it(*dex_file_, *item);
1827 DexFileParameterIterator prev_it(*dex_file_, *prev);
1828
1829 while (curr_it.HasNext() && prev_it.HasNext()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001830 dex::TypeIndex prev_idx = prev_it.GetTypeIdx();
1831 dex::TypeIndex curr_idx = curr_it.GetTypeIdx();
1832 DCHECK_NE(prev_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
1833 DCHECK_NE(curr_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
jeffhao10037c82012-01-23 15:06:23 -08001834
1835 if (prev_idx < curr_idx) {
1836 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001837 } else if (UNLIKELY(prev_idx > curr_idx)) {
1838 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001839 return false;
1840 }
1841
1842 prev_it.Next();
1843 curr_it.Next();
1844 }
Vladimir Marko0ca8add2016-05-03 17:17:50 +01001845 if (!curr_it.HasNext()) {
1846 // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
1847 // a ProtoId with a longer one. Both cases are forbidden by the specification.
1848 ErrorStringPrintf("Out-of-order proto_id arguments");
1849 return false;
1850 }
jeffhao10037c82012-01-23 15:06:23 -08001851 }
1852 }
1853
1854 ptr_ += sizeof(DexFile::ProtoId);
1855 return true;
1856}
1857
1858bool DexFileVerifier::CheckInterFieldIdItem() {
1859 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1860
1861 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001862 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1863 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1864 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001865 return false;
1866 }
1867
1868 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001869 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1870 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1871 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001872 return false;
1873 }
1874
1875 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001876 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001877 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1878 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001879 return false;
1880 }
1881
1882 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001883 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001884 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001885 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1886 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001887 return false;
1888 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001889 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1890 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001891 return false;
1892 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001893 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
1894 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001895 return false;
1896 }
1897 }
1898 }
1899 }
1900
1901 ptr_ += sizeof(DexFile::FieldId);
1902 return true;
1903}
1904
1905bool DexFileVerifier::CheckInterMethodIdItem() {
1906 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
1907
1908 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001909 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
1910 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
1911 class_descriptor[0] != '['))) {
1912 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001913 return false;
1914 }
1915
1916 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07001917 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001918 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1919 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001920 return false;
1921 }
1922
Andreas Gampedf10b322014-06-11 21:46:05 -07001923 // Check that the proto id is valid.
1924 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
1925 "inter_method_id_item proto_idx"))) {
1926 return false;
1927 }
1928
jeffhao10037c82012-01-23 15:06:23 -08001929 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001930 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001931 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001932 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1933 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001934 return false;
1935 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001936 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1937 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001938 return false;
1939 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001940 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
1941 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001942 return false;
1943 }
1944 }
1945 }
1946 }
1947
1948 ptr_ += sizeof(DexFile::MethodId);
1949 return true;
1950}
1951
1952bool DexFileVerifier::CheckInterClassDefItem() {
1953 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001954
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001955 // Check for duplicate class def.
1956 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001957 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_.index_);
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001958 return false;
1959 }
1960 defined_classes_.insert(item->class_idx_);
1961
Andreas Gampee09269c2014-06-06 18:45:35 -07001962 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
1963 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1964 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001965 return false;
1966 }
1967
Andreas Gampeacc2bb62014-07-17 19:26:50 -07001968 // Only allow non-runtime modifiers.
1969 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
1970 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
1971 return false;
1972 }
1973
jeffhao10037c82012-01-23 15:06:23 -08001974 if (item->interfaces_off_ != 0 &&
1975 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
1976 return false;
1977 }
1978 if (item->annotations_off_ != 0 &&
1979 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
1980 return false;
1981 }
1982 if (item->class_data_off_ != 0 &&
1983 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
1984 return false;
1985 }
1986 if (item->static_values_off_ != 0 &&
1987 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
1988 return false;
1989 }
1990
Andreas Gampea5b09a62016-11-17 15:21:22 -08001991 if (item->superclass_idx_.IsValid()) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01001992 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
1993 // Check that a class does not inherit from itself directly (by having
1994 // the same type idx as its super class).
1995 if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001996 ErrorStringPrintf("Class with same type idx as its superclass: '%d'",
1997 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01001998 return false;
1999 }
2000
2001 // Check that a class is defined after its super class (if the
2002 // latter is defined in the same Dex file).
2003 const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
2004 if (superclass_def != nullptr) {
2005 // The superclass is defined in this Dex file.
2006 if (superclass_def > item) {
2007 // ClassDef item for super class appearing after the class' ClassDef item.
2008 ErrorStringPrintf("Invalid class definition ordering:"
2009 " class with type idx: '%d' defined before"
2010 " superclass with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002011 item->class_idx_.index_,
2012 item->superclass_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002013 return false;
2014 }
2015 }
2016 }
2017
Andreas Gampee09269c2014-06-06 18:45:35 -07002018 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
2019 "inter_class_def_item superclass_idx")
2020 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
2021 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002022 return false;
2023 }
2024 }
2025
Roland Levillain621b5ea2016-05-18 11:41:33 +01002026 // Check interfaces.
jeffhao10037c82012-01-23 15:06:23 -08002027 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002028 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002029 uint32_t size = interfaces->Size();
jeffhao10037c82012-01-23 15:06:23 -08002030 for (uint32_t i = 0; i < size; i++) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002031 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2032 // Check that a class does not implement itself directly (by having the
2033 // same type idx as one of its immediate implemented interfaces).
2034 if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2035 ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002036 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002037 return false;
2038 }
2039
2040 // Check that a class is defined after the interfaces it implements
2041 // (if they are defined in the same Dex file).
2042 const DexFile::ClassDef* interface_def =
2043 dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2044 if (interface_def != nullptr) {
2045 // The interface is defined in this Dex file.
2046 if (interface_def > item) {
2047 // ClassDef item for interface appearing after the class' ClassDef item.
2048 ErrorStringPrintf("Invalid class definition ordering:"
2049 " class with type idx: '%d' defined before"
2050 " implemented interface with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002051 item->class_idx_.index_,
2052 interfaces->GetTypeItem(i).type_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002053 return false;
2054 }
2055 }
2056 }
2057
2058 // Ensure that the interface refers to a class (not an array nor a primitive type).
Andreas Gampee09269c2014-06-06 18:45:35 -07002059 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2060 "inter_class_def_item interface type_idx")
2061 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2062 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002063 return false;
2064 }
2065 }
2066
2067 /*
2068 * Ensure that there are no duplicates. This is an O(N^2) test, but in
2069 * practice the number of interfaces implemented by any given class is low.
2070 */
2071 for (uint32_t i = 1; i < size; i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002072 dex::TypeIndex idx1 = interfaces->GetTypeItem(i).type_idx_;
jeffhao10037c82012-01-23 15:06:23 -08002073 for (uint32_t j =0; j < i; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002074 dex::TypeIndex idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002075 if (UNLIKELY(idx1 == idx2)) {
2076 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08002077 return false;
2078 }
2079 }
2080 }
2081 }
2082
2083 // Check that references in class_data_item are to the right class.
2084 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07002085 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002086 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002087 dex::TypeIndex data_definer = FindFirstClassDataDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002088 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002089 return false;
2090 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08002091 if (UNLIKELY((data_definer != item->class_idx_) &&
2092 (data_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002093 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08002094 return false;
2095 }
2096 }
2097
2098 // Check that references in annotations_directory_item are to right class.
2099 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002100 // annotations_off_ is supposed to be aligned by 4.
2101 if (!IsAlignedParam(item->annotations_off_, 4)) {
2102 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2103 return false;
2104 }
Ian Rogers13735952014-10-08 12:43:28 -07002105 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002106 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002107 dex::TypeIndex annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002108 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002109 return false;
2110 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002111 if (UNLIKELY((annotations_definer != item->class_idx_) &&
Andreas Gampea5b09a62016-11-17 15:21:22 -08002112 (annotations_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002113 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002114 return false;
2115 }
2116 }
2117
2118 ptr_ += sizeof(DexFile::ClassDef);
2119 return true;
2120}
2121
2122bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2123 const DexFile::AnnotationSetRefList* list =
2124 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2125 const DexFile::AnnotationSetRefItem* item = list->list_;
2126 uint32_t count = list->size_;
2127
2128 while (count--) {
2129 if (item->annotations_off_ != 0 &&
2130 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2131 return false;
2132 }
2133 item++;
2134 }
2135
Ian Rogers13735952014-10-08 12:43:28 -07002136 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002137 return true;
2138}
2139
2140bool DexFileVerifier::CheckInterAnnotationSetItem() {
2141 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2142 const uint32_t* offsets = set->entries_;
2143 uint32_t count = set->size_;
2144 uint32_t last_idx = 0;
2145
2146 for (uint32_t i = 0; i < count; i++) {
2147 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2148 return false;
2149 }
2150
2151 // Get the annotation from the offset and the type index for the annotation.
2152 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002153 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002154 const uint8_t* data = annotation->annotation_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002155 DECODE_UNSIGNED_CHECKED_FROM(data, idx);
jeffhao10037c82012-01-23 15:06:23 -08002156
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002157 if (UNLIKELY(last_idx >= idx && i != 0)) {
2158 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002159 return false;
2160 }
2161
2162 last_idx = idx;
2163 offsets++;
2164 }
2165
Ian Rogers13735952014-10-08 12:43:28 -07002166 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002167 return true;
2168}
2169
2170bool DexFileVerifier::CheckInterClassDataItem() {
2171 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002172 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002173 dex::TypeIndex defining_class = FindFirstClassDataDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002174 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002175 return false;
2176 }
jeffhao10037c82012-01-23 15:06:23 -08002177
2178 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002179 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002180 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002181 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002182 return false;
2183 }
2184 }
2185 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2186 uint32_t code_off = it.GetMethodCodeItemOffset();
2187 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2188 return false;
2189 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002190 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002191 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002192 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002193 return false;
2194 }
2195 }
2196
2197 ptr_ = it.EndDataPointer();
2198 return true;
2199}
2200
2201bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2202 const DexFile::AnnotationsDirectoryItem* item =
2203 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002204 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002205 dex::TypeIndex defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002206 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002207 return false;
2208 }
jeffhao10037c82012-01-23 15:06:23 -08002209
2210 if (item->class_annotations_off_ != 0 &&
2211 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2212 return false;
2213 }
2214
2215 // Field annotations follow immediately after the annotations directory.
2216 const DexFile::FieldAnnotationsItem* field_item =
2217 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2218 uint32_t field_count = item->fields_size_;
2219 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002220 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2221 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002222 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002223 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002224 return false;
2225 }
2226 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2227 return false;
2228 }
2229 field_item++;
2230 }
2231
2232 // Method annotations follow immediately after field annotations.
2233 const DexFile::MethodAnnotationsItem* method_item =
2234 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2235 uint32_t method_count = item->methods_size_;
2236 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002237 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002238 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002239 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002240 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002241 return false;
2242 }
2243 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2244 return false;
2245 }
2246 method_item++;
2247 }
2248
2249 // Parameter annotations follow immediately after method annotations.
2250 const DexFile::ParameterAnnotationsItem* parameter_item =
2251 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2252 uint32_t parameter_count = item->parameters_size_;
2253 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002254 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002255 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002256 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002257 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002258 return false;
2259 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002260 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2261 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002262 return false;
2263 }
2264 parameter_item++;
2265 }
2266
Ian Rogers13735952014-10-08 12:43:28 -07002267 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002268 return true;
2269}
2270
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002271bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002272 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002273 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002274 switch (type) {
2275 case DexFile::kDexTypeClassDataItem:
2276 alignment_mask = sizeof(uint8_t) - 1;
2277 break;
2278 default:
2279 alignment_mask = sizeof(uint32_t) - 1;
2280 break;
2281 }
2282
2283 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002284 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002285 for (uint32_t i = 0; i < count; i++) {
2286 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002287 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002288 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002289
2290 // Check depending on the section type.
2291 switch (type) {
2292 case DexFile::kDexTypeStringIdItem: {
2293 if (!CheckInterStringIdItem()) {
2294 return false;
2295 }
2296 break;
2297 }
2298 case DexFile::kDexTypeTypeIdItem: {
2299 if (!CheckInterTypeIdItem()) {
2300 return false;
2301 }
2302 break;
2303 }
2304 case DexFile::kDexTypeProtoIdItem: {
2305 if (!CheckInterProtoIdItem()) {
2306 return false;
2307 }
2308 break;
2309 }
2310 case DexFile::kDexTypeFieldIdItem: {
2311 if (!CheckInterFieldIdItem()) {
2312 return false;
2313 }
2314 break;
2315 }
2316 case DexFile::kDexTypeMethodIdItem: {
2317 if (!CheckInterMethodIdItem()) {
2318 return false;
2319 }
2320 break;
2321 }
2322 case DexFile::kDexTypeClassDefItem: {
2323 if (!CheckInterClassDefItem()) {
2324 return false;
2325 }
2326 break;
2327 }
2328 case DexFile::kDexTypeAnnotationSetRefList: {
2329 if (!CheckInterAnnotationSetRefList()) {
2330 return false;
2331 }
2332 break;
2333 }
2334 case DexFile::kDexTypeAnnotationSetItem: {
2335 if (!CheckInterAnnotationSetItem()) {
2336 return false;
2337 }
2338 break;
2339 }
2340 case DexFile::kDexTypeClassDataItem: {
2341 if (!CheckInterClassDataItem()) {
2342 return false;
2343 }
2344 break;
2345 }
2346 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2347 if (!CheckInterAnnotationsDirectoryItem()) {
2348 return false;
2349 }
2350 break;
2351 }
2352 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002353 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002354 return false;
2355 }
2356
2357 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002358 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002359 }
2360
2361 return true;
2362}
2363
2364bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002365 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002366 const DexFile::MapItem* item = map->list_;
2367 uint32_t count = map->size_;
2368
2369 // Cross check the items listed in the map.
2370 while (count--) {
2371 uint32_t section_offset = item->offset_;
2372 uint32_t section_count = item->size_;
2373 uint16_t type = item->type_;
2374
2375 switch (type) {
2376 case DexFile::kDexTypeHeaderItem:
2377 case DexFile::kDexTypeMapList:
2378 case DexFile::kDexTypeTypeList:
2379 case DexFile::kDexTypeCodeItem:
2380 case DexFile::kDexTypeStringDataItem:
2381 case DexFile::kDexTypeDebugInfoItem:
2382 case DexFile::kDexTypeAnnotationItem:
2383 case DexFile::kDexTypeEncodedArrayItem:
2384 break;
2385 case DexFile::kDexTypeStringIdItem:
2386 case DexFile::kDexTypeTypeIdItem:
2387 case DexFile::kDexTypeProtoIdItem:
2388 case DexFile::kDexTypeFieldIdItem:
2389 case DexFile::kDexTypeMethodIdItem:
2390 case DexFile::kDexTypeClassDefItem:
2391 case DexFile::kDexTypeAnnotationSetRefList:
2392 case DexFile::kDexTypeAnnotationSetItem:
2393 case DexFile::kDexTypeClassDataItem:
2394 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2395 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2396 return false;
2397 }
2398 break;
2399 }
2400 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002401 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002402 return false;
2403 }
2404
2405 item++;
2406 }
2407
2408 return true;
2409}
2410
2411bool DexFileVerifier::Verify() {
2412 // Check the header.
2413 if (!CheckHeader()) {
2414 return false;
2415 }
2416
2417 // Check the map section.
2418 if (!CheckMap()) {
2419 return false;
2420 }
2421
2422 // Check structure within remaining sections.
2423 if (!CheckIntraSection()) {
2424 return false;
2425 }
2426
2427 // Check references from one section to another.
2428 if (!CheckInterSection()) {
2429 return false;
2430 }
2431
2432 return true;
2433}
2434
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002435void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2436 va_list ap;
2437 va_start(ap, fmt);
2438 DCHECK(failure_reason_.empty()) << failure_reason_;
2439 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2440 StringAppendV(&failure_reason_, fmt, ap);
2441 va_end(ap);
2442}
2443
Andreas Gampee6215c02015-08-31 18:54:38 -07002444// Fields and methods may have only one of public/protected/private.
2445static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2446 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2447 (((flags & kAccProtected) == 0) ? 0 : 1) +
2448 (((flags & kAccPrivate) == 0) ? 0 : 1);
2449 return count <= 1;
2450}
2451
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002452// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2453// functionality, as we're still verifying the dex file. begin and header correspond to the
2454// underscored variants in the DexFileVerifier.
2455
2456static std::string GetStringOrError(const uint8_t* const begin,
2457 const DexFile::Header* const header,
2458 uint32_t string_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002459 // The `string_idx` is not guaranteed to be valid yet.
2460 if (header->string_ids_size_ <= string_idx) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002461 return "(error)";
2462 }
2463
2464 const DexFile::StringId* string_id =
2465 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx;
2466
2467 // Assume that the data is OK at this point. String data has been checked at this point.
2468
2469 const uint8_t* ptr = begin + string_id->string_data_off_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002470 uint32_t dummy;
2471 if (!DecodeUnsignedLeb128Checked(&ptr, begin + header->file_size_, &dummy)) {
2472 return "(error)";
2473 }
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002474 return reinterpret_cast<const char*>(ptr);
2475}
2476
2477static std::string GetClassOrError(const uint8_t* const begin,
2478 const DexFile::Header* const header,
Andreas Gampea5b09a62016-11-17 15:21:22 -08002479 dex::TypeIndex class_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002480 // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2481 // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2482 // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2483 // a valid defining class.
Andreas Gampea5b09a62016-11-17 15:21:22 -08002484 CHECK_LT(class_idx.index_, header->type_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002485
2486 const DexFile::TypeId* type_id =
Andreas Gampea5b09a62016-11-17 15:21:22 -08002487 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002488
2489 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2490
2491 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2492}
2493
2494static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2495 const DexFile::Header* const header,
2496 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002497 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2498 CHECK_LT(idx, header->field_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002499
2500 const DexFile::FieldId* field_id =
2501 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2502
2503 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2504
2505 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2506 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2507
2508 return class_name + "." + field_name;
2509}
2510
2511static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2512 const DexFile::Header* const header,
2513 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002514 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2515 CHECK_LT(idx, header->method_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002516
2517 const DexFile::MethodId* method_id =
2518 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2519
2520 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2521
2522 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2523 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2524
2525 return class_name + "." + method_name;
2526}
2527
2528bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2529 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002530 uint32_t class_access_flags,
2531 std::string* error_msg) {
2532 // Generally sort out >16-bit flags.
2533 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002534 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2535 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2536 field_access_flags,
2537 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002538 return false;
2539 }
2540
2541 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2542 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2543 kAccPrivate |
2544 kAccProtected |
2545 kAccStatic |
2546 kAccFinal |
2547 kAccVolatile |
2548 kAccTransient |
2549 kAccSynthetic |
2550 kAccEnum;
2551
2552 // Fields may have only one of public/protected/final.
2553 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002554 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2555 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2556 field_access_flags,
2557 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002558 return false;
2559 }
2560
2561 // Interfaces have a pretty restricted list.
2562 if ((class_access_flags & kAccInterface) != 0) {
2563 // Interface fields must be public final static.
2564 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2565 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002566 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2567 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2568 field_access_flags,
2569 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002570 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002571 return false;
2572 } else {
2573 // Allow in older versions, but warn.
2574 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2575 << *error_msg;
2576 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002577 }
2578 // Interface fields may be synthetic, but may not have other flags.
2579 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2580 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002581 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
2582 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2583 field_access_flags,
2584 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002585 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002586 return false;
2587 } else {
2588 // Allow in older versions, but warn.
2589 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2590 << *error_msg;
2591 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002592 }
2593 return true;
2594 }
2595
2596 // Volatile fields may not be final.
2597 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2598 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002599 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
2600 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002601 return false;
2602 }
2603
2604 return true;
2605}
2606
2607// Try to find the name of the method with the given index. We do not want to rely on DexFile
2608// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
2609// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
2610// (flagged by the return value), otherwise error_msg will contain an error string.
2611static bool FindMethodName(uint32_t method_index,
2612 const uint8_t* begin,
2613 const DexFile::Header* header,
2614 const char** str,
2615 std::string* error_msg) {
2616 if (method_index >= header->method_ids_size_) {
2617 *error_msg = "Method index not available for method flags verification";
2618 return false;
2619 }
2620 uint32_t string_idx =
2621 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
2622 method_index)->name_idx_;
2623 if (string_idx >= header->string_ids_size_) {
2624 *error_msg = "String index not available for method flags verification";
2625 return false;
2626 }
2627 uint32_t string_off =
2628 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
2629 string_data_off_;
2630 if (string_off >= header->file_size_) {
2631 *error_msg = "String offset out of bounds for method flags verification";
2632 return false;
2633 }
2634 const uint8_t* str_data_ptr = begin + string_off;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002635 uint32_t dummy;
2636 if (!DecodeUnsignedLeb128Checked(&str_data_ptr, begin + header->file_size_, &dummy)) {
2637 *error_msg = "String size out of bounds for method flags verification";
2638 return false;
2639 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002640 *str = reinterpret_cast<const char*>(str_data_ptr);
2641 return true;
2642}
2643
2644bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2645 uint32_t method_access_flags,
2646 uint32_t class_access_flags,
2647 bool has_code,
2648 bool expect_direct,
2649 std::string* error_msg) {
2650 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2651 constexpr uint32_t kAllMethodFlags =
2652 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2653 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002654 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
2655 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2656 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002657 return false;
2658 }
2659
2660 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2661 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2662 kAccPrivate |
2663 kAccProtected |
2664 kAccStatic |
2665 kAccFinal |
2666 kAccSynthetic |
2667 kAccSynchronized |
2668 kAccBridge |
2669 kAccVarargs |
2670 kAccNative |
2671 kAccAbstract |
2672 kAccStrict;
2673
2674 // Methods may have only one of public/protected/final.
2675 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002676 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
2677 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002678 method_access_flags);
2679 return false;
2680 }
2681
2682 // Try to find the name, to check for constructor properties.
2683 const char* str;
2684 if (!FindMethodName(method_index, begin_, header_, &str, error_msg)) {
2685 return false;
2686 }
2687 bool is_init_by_name = false;
2688 constexpr const char* kInitName = "<init>";
2689 size_t str_offset = (reinterpret_cast<const uint8_t*>(str) - begin_);
2690 if (header_->file_size_ - str_offset >= sizeof(kInitName)) {
2691 is_init_by_name = strcmp(kInitName, str) == 0;
2692 }
2693 bool is_clinit_by_name = false;
2694 constexpr const char* kClinitName = "<clinit>";
2695 if (header_->file_size_ - str_offset >= sizeof(kClinitName)) {
2696 is_clinit_by_name = strcmp(kClinitName, str) == 0;
2697 }
2698 bool is_constructor = is_init_by_name || is_clinit_by_name;
2699
2700 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2701 // the reverse for backwards compatibility reasons.
2702 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002703 *error_msg =
2704 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
2705 method_index,
2706 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002707 return false;
2708 }
2709 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2710 // instance constructor is called "<init>".
2711 if (is_constructor) {
2712 bool is_static = (method_access_flags & kAccStatic) != 0;
2713 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002714 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
2715 method_index,
2716 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002717 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2718 return false;
2719 } else {
2720 // Allow in older versions, but warn.
2721 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2722 << *error_msg;
2723 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002724 }
2725 }
2726 // Check that static and private methods, as well as constructors, are in the direct methods list,
2727 // and other methods in the virtual methods list.
2728 bool is_direct = (method_access_flags & (kAccStatic | kAccPrivate)) != 0 || is_constructor;
2729 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002730 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07002731 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002732 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002733 expect_direct);
2734 return false;
2735 }
2736
2737
2738 // From here on out it is easier to mask out the bits we're supposed to ignore.
2739 method_access_flags &= kMethodAccessFlags;
2740
Alex Lightd7c10c22016-03-31 10:03:07 -07002741 // Interfaces are special.
2742 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07002743 // Non-static interface methods must be public or private.
2744 uint32_t desired_flags = (kAccPublic | kAccStatic);
2745 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2746 desired_flags |= kAccPrivate;
2747 }
2748 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002749 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
2750 method_index,
2751 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002752 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002753 return false;
2754 } else {
2755 // Allow in older versions, but warn.
2756 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2757 << *error_msg;
2758 }
2759 }
2760 }
2761
Andreas Gampee6215c02015-08-31 18:54:38 -07002762 // If there aren't any instructions, make sure that's expected.
2763 if (!has_code) {
2764 // Only native or abstract methods may not have code.
2765 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002766 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07002767 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002768 method_index,
2769 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002770 return false;
2771 }
2772 // Constructors must always have code.
2773 if (is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002774 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
2775 method_index,
2776 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002777 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2778 return false;
2779 } else {
2780 // Allow in older versions, but warn.
2781 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2782 << *error_msg;
2783 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002784 }
2785 if ((method_access_flags & kAccAbstract) != 0) {
2786 // Abstract methods are not allowed to have the following flags.
2787 constexpr uint32_t kForbidden =
2788 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2789 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002790 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
2791 method_index,
2792 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2793 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002794 return false;
2795 }
Andreas Gampe97b11352015-12-10 16:23:41 -08002796 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07002797 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002798 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08002799 << " is abstract, but the declaring class is neither abstract nor an "
2800 << "interface in dex file "
2801 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07002802 }
2803 }
2804 // Interfaces are special.
2805 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002806 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07002807 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002808 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
2809 method_index,
2810 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002811 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002812 return false;
2813 } else {
2814 // Allow in older versions, but warn.
2815 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2816 << *error_msg;
2817 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002818 }
2819 // At this point, we know the method is public and abstract. This means that all the checks
2820 // for invalid combinations above applies. In addition, interface methods must not be
2821 // protected. This is caught by the check for only-one-of-public-protected-private.
2822 }
2823 return true;
2824 }
2825
2826 // When there's code, the method must not be native or abstract.
2827 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002828 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
2829 method_index,
2830 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002831 return false;
2832 }
2833
Andreas Gampee6215c02015-08-31 18:54:38 -07002834 // Instance constructors must not be synchronized and a few other flags.
2835 if (is_init_by_name) {
2836 static constexpr uint32_t kInitAllowed =
2837 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2838 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002839 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07002840 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002841 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002842 method_access_flags);
2843 return false;
2844 }
2845 }
2846
2847 return true;
2848}
2849
jeffhao10037c82012-01-23 15:06:23 -08002850} // namespace art