blob: c5c4eda98f5213fa4480611e770efb4011bb73b1 [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>
Andreas Gampee6215c02015-08-31 18:54:38 -070020
David Sehr28e74ed2016-11-21 12:52:12 -080021#include <limits>
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Narayan Kamath92572be2013-11-28 14:06:24 +000023
Andreas Gampe46ee31b2016-12-14 10:11:49 -080024#include "android-base/stringprintf.h"
25
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070026#include "dex_file-inl.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070027#include "experimental_flags.h"
jeffhao10037c82012-01-23 15:06:23 -080028#include "leb128.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070029#include "safe_map.h"
Ian Rogersa6724902013-09-23 09:23:37 -070030#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "utils.h"
jeffhao10037c82012-01-23 15:06:23 -080032
33namespace art {
34
Andreas Gampe46ee31b2016-12-14 10:11:49 -080035using android::base::StringAppendV;
36using android::base::StringPrintf;
37
David Sehr28e74ed2016-11-21 12:52:12 -080038static constexpr uint32_t kTypeIdLimit = std::numeric_limits<uint16_t>::max();
39
40static bool IsValidOrNoTypeId(uint16_t low, uint16_t high) {
41 return (high == 0) || ((high == 0xffffU) && (low == 0xffffU));
42}
43
44static bool IsValidTypeId(uint16_t low ATTRIBUTE_UNUSED, uint16_t high) {
45 return (high == 0);
46}
47
Orion Hodson12f4ff42017-01-13 16:43:12 +000048static uint32_t MapTypeToBitMask(DexFile::MapItemType map_item_type) {
49 switch (map_item_type) {
jeffhao10037c82012-01-23 15:06:23 -080050 case DexFile::kDexTypeHeaderItem: return 1 << 0;
51 case DexFile::kDexTypeStringIdItem: return 1 << 1;
52 case DexFile::kDexTypeTypeIdItem: return 1 << 2;
53 case DexFile::kDexTypeProtoIdItem: return 1 << 3;
54 case DexFile::kDexTypeFieldIdItem: return 1 << 4;
55 case DexFile::kDexTypeMethodIdItem: return 1 << 5;
56 case DexFile::kDexTypeClassDefItem: return 1 << 6;
Orion Hodson12f4ff42017-01-13 16:43:12 +000057 case DexFile::kDexTypeCallSiteIdItem: return 1 << 7;
58 case DexFile::kDexTypeMethodHandleItem: return 1 << 8;
59 case DexFile::kDexTypeMapList: return 1 << 9;
60 case DexFile::kDexTypeTypeList: return 1 << 10;
61 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 11;
62 case DexFile::kDexTypeAnnotationSetItem: return 1 << 12;
63 case DexFile::kDexTypeClassDataItem: return 1 << 13;
64 case DexFile::kDexTypeCodeItem: return 1 << 14;
65 case DexFile::kDexTypeStringDataItem: return 1 << 15;
66 case DexFile::kDexTypeDebugInfoItem: return 1 << 16;
67 case DexFile::kDexTypeAnnotationItem: return 1 << 17;
68 case DexFile::kDexTypeEncodedArrayItem: return 1 << 18;
69 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 19;
jeffhao10037c82012-01-23 15:06:23 -080070 }
71 return 0;
72}
73
Orion Hodson12f4ff42017-01-13 16:43:12 +000074static bool IsDataSectionType(DexFile::MapItemType map_item_type) {
75 switch (map_item_type) {
jeffhao10037c82012-01-23 15:06:23 -080076 case DexFile::kDexTypeHeaderItem:
77 case DexFile::kDexTypeStringIdItem:
78 case DexFile::kDexTypeTypeIdItem:
79 case DexFile::kDexTypeProtoIdItem:
80 case DexFile::kDexTypeFieldIdItem:
81 case DexFile::kDexTypeMethodIdItem:
82 case DexFile::kDexTypeClassDefItem:
83 return false;
Orion Hodson12f4ff42017-01-13 16:43:12 +000084 case DexFile::kDexTypeCallSiteIdItem:
85 case DexFile::kDexTypeMethodHandleItem:
86 case DexFile::kDexTypeMapList:
87 case DexFile::kDexTypeTypeList:
88 case DexFile::kDexTypeAnnotationSetRefList:
89 case DexFile::kDexTypeAnnotationSetItem:
90 case DexFile::kDexTypeClassDataItem:
91 case DexFile::kDexTypeCodeItem:
92 case DexFile::kDexTypeStringDataItem:
93 case DexFile::kDexTypeDebugInfoItem:
94 case DexFile::kDexTypeAnnotationItem:
95 case DexFile::kDexTypeEncodedArrayItem:
96 case DexFile::kDexTypeAnnotationsDirectoryItem:
97 return true;
jeffhao10037c82012-01-23 15:06:23 -080098 }
99 return true;
100}
101
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800102const char* DexFileVerifier::CheckLoadStringByIdx(dex::StringIndex idx, const char* error_string) {
103 if (UNLIKELY(!CheckIndex(idx.index_, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700104 return nullptr;
105 }
106 return dex_file_->StringDataByIdx(idx);
107}
108
Orion Hodson6c4921b2016-09-21 15:41:06 +0100109// Try to find the name of the method with the given index. We do not want to rely on DexFile
110// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
111// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
112// (flagged by the return value), otherwise error_msg will contain an error string.
113static bool FindMethodName(uint32_t method_index,
114 const uint8_t* begin,
115 const DexFile::Header* header,
116 const char** str,
117 std::string* error_msg) {
118 if (method_index >= header->method_ids_size_) {
119 *error_msg = "Method index not available for method flags verification";
120 return false;
121 }
122 uint32_t string_idx =
123 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
124 method_index)->name_idx_.index_;
125 if (string_idx >= header->string_ids_size_) {
126 *error_msg = "String index not available for method flags verification";
127 return false;
128 }
129 uint32_t string_off =
130 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
131 string_data_off_;
132 if (string_off >= header->file_size_) {
133 *error_msg = "String offset out of bounds for method flags verification";
134 return false;
135 }
136 const uint8_t* str_data_ptr = begin + string_off;
137 uint32_t dummy;
138 if (!DecodeUnsignedLeb128Checked(&str_data_ptr, begin + header->file_size_, &dummy)) {
139 *error_msg = "String size out of bounds for method flags verification";
140 return false;
141 }
142 *str = reinterpret_cast<const char*>(str_data_ptr);
143 return true;
144}
145
146// Gets constructor flags based on the |method_name|. Returns true if
147// method_name is either <clinit> or <init> and sets
148// |constructor_flags_by_name| appropriately. Otherwise set
149// |constructor_flags_by_name| to zero and returns whether
150// |method_name| is valid.
151bool GetConstructorFlagsForMethodName(const char* method_name,
152 uint32_t* constructor_flags_by_name) {
153 if (method_name[0] != '<') {
154 *constructor_flags_by_name = 0;
155 return true;
156 }
157 if (strcmp(method_name + 1, "clinit>") == 0) {
158 *constructor_flags_by_name = kAccStatic | kAccConstructor;
159 return true;
160 }
161 if (strcmp(method_name + 1, "init>") == 0) {
162 *constructor_flags_by_name = kAccConstructor;
163 return true;
164 }
165 *constructor_flags_by_name = 0;
166 return false;
167}
168
Andreas Gampea5b09a62016-11-17 15:21:22 -0800169const char* DexFileVerifier::CheckLoadStringByTypeIdx(dex::TypeIndex type_idx,
170 const char* error_string) {
171 if (UNLIKELY(!CheckIndex(type_idx.index_, dex_file_->NumTypeIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700172 return nullptr;
173 }
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800174 return CheckLoadStringByIdx(dex_file_->GetTypeId(type_idx).descriptor_idx_, error_string);
Andreas Gampee09269c2014-06-06 18:45:35 -0700175}
176
177const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -0700178 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700179 return nullptr;
180 }
181 return &dex_file_->GetFieldId(idx);
182}
183
184const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -0700185 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -0700186 return nullptr;
187 }
188 return &dex_file_->GetMethodId(idx);
189}
190
Orion Hodson6c4921b2016-09-21 15:41:06 +0100191const DexFile::ProtoId* DexFileVerifier::CheckLoadProtoId(uint32_t idx, const char* err_string) {
192 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumProtoIds(), err_string))) {
193 return nullptr;
194 }
195 return &dex_file_->GetProtoId(idx);
196}
197
Andreas Gampee09269c2014-06-06 18:45:35 -0700198// Helper macro to load string and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700199#define LOAD_STRING(var, idx, error) \
200 const char* (var) = CheckLoadStringByIdx(idx, error); \
201 if (UNLIKELY((var) == nullptr)) { \
202 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700203 }
204
205// Helper macro to load string by type idx and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700206#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
207 const char* (var) = CheckLoadStringByTypeIdx(type_idx, error); \
208 if (UNLIKELY((var) == nullptr)) { \
209 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700210 }
211
212// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700213#define LOAD_METHOD(var, idx, error_string, error_stmt) \
214 const DexFile::MethodId* (var) = CheckLoadMethodId(idx, error_string); \
215 if (UNLIKELY((var) == nullptr)) { \
216 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700217 }
218
219// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700220#define LOAD_FIELD(var, idx, fmt, error_stmt) \
221 const DexFile::FieldId* (var) = CheckLoadFieldId(idx, fmt); \
222 if (UNLIKELY((var) == nullptr)) { \
223 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700224 }
225
Aart Bik37d6a3b2016-06-21 18:30:10 -0700226bool DexFileVerifier::Verify(const DexFile* dex_file,
227 const uint8_t* begin,
228 size_t size,
229 const char* location,
230 bool verify_checksum,
231 std::string* error_msg) {
232 std::unique_ptr<DexFileVerifier> verifier(
233 new DexFileVerifier(dex_file, begin, size, location, verify_checksum));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700234 if (!verifier->Verify()) {
235 *error_msg = verifier->FailureReason();
236 return false;
237 }
238 return true;
239}
240
241bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
242 bool is_return_type) {
jeffhao10037c82012-01-23 15:06:23 -0800243 switch (shorty_char) {
244 case 'V':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700245 if (UNLIKELY(!is_return_type)) {
246 ErrorStringPrintf("Invalid use of void");
jeffhao10037c82012-01-23 15:06:23 -0800247 return false;
248 }
Ian Rogersfc787ec2014-10-09 21:56:44 -0700249 FALLTHROUGH_INTENDED;
jeffhao10037c82012-01-23 15:06:23 -0800250 case 'B':
251 case 'C':
252 case 'D':
253 case 'F':
254 case 'I':
255 case 'J':
256 case 'S':
257 case 'Z':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700258 if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
259 ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
260 shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800261 return false;
262 }
263 break;
264 case 'L':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700265 if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
266 ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800267 return false;
268 }
269 break;
270 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700271 ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
jeffhao10037c82012-01-23 15:06:23 -0800272 return false;
273 }
274 return true;
275}
276
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700277bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700278 const char* label) {
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700279 // Check that size is not 0.
280 CHECK_NE(elem_size, 0U);
281
Ian Rogers13735952014-10-08 12:43:28 -0700282 const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
283 const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700284
285 // Check for overflow.
286 uintptr_t max = 0 - 1;
287 size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
288 size_t max_count = available_bytes_till_end_of_mem / elem_size;
289 if (max_count < count) {
290 ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
291 static_cast<size_t>(range_start - file_start),
292 count, elem_size);
293 return false;
294 }
295
Ian Rogers13735952014-10-08 12:43:28 -0700296 const uint8_t* range_end = range_start + count * elem_size;
297 const uint8_t* file_end = file_start + size_;
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700298 if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
299 // Note: these two tests are enough as we make sure above that there's no overflow.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800300 ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
Ian Rogerse3d55812014-06-11 13:00:44 -0700301 static_cast<size_t>(range_start - file_start),
302 static_cast<size_t>(range_end - file_start));
jeffhao10037c82012-01-23 15:06:23 -0800303 return false;
304 }
305 return true;
306}
307
Ian Rogers13735952014-10-08 12:43:28 -0700308bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700309 // Check that the list is available. The first 4B are the count.
310 if (!CheckListSize(*ptr, 1, 4U, label)) {
311 return false;
312 }
313
314 uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
315 if (count > 0) {
316 if (!CheckListSize(*ptr + 4, count, element_size, label)) {
317 return false;
318 }
319 }
320
321 *ptr += 4 + count * element_size;
322 return true;
323}
324
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700325bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
326 if (UNLIKELY(field >= limit)) {
327 ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
jeffhao10037c82012-01-23 15:06:23 -0800328 return false;
329 }
330 return true;
331}
332
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800333bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
334 uint32_t size,
335 size_t alignment,
336 const char* label) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700337 if (size == 0) {
338 if (offset != 0) {
339 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
340 return false;
341 }
342 }
343 if (size_ <= offset) {
344 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
345 return false;
346 }
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800347 if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
348 ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
349 return false;
350 }
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700351 return true;
352}
353
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100354bool DexFileVerifier::CheckSizeLimit(uint32_t size, uint32_t limit, const char* label) {
355 if (size > limit) {
356 ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label);
357 return false;
358 }
359 return true;
360}
361
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700362bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800363 // Check file size from the header.
364 uint32_t expected_size = header_->file_size_;
365 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700366 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800367 return false;
368 }
369
Alex Light40528472017-03-28 09:07:36 -0700370 uint32_t adler_checksum = dex_file_->CalculateChecksum();
jeffhao10037c82012-01-23 15:06:23 -0800371 // Compute and verify the checksum in the header.
jeffhao10037c82012-01-23 15:06:23 -0800372 if (adler_checksum != header_->checksum_) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700373 if (verify_checksum_) {
374 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
375 return false;
376 } else {
377 LOG(WARNING) << StringPrintf(
378 "Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
379 }
jeffhao10037c82012-01-23 15:06:23 -0800380 }
381
382 // Check the contents of the header.
383 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700384 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800385 return false;
386 }
387
388 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700389 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800390 return false;
391 }
392
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700393 // Check that all offsets are inside the file.
394 bool result =
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800395 CheckValidOffsetAndSize(header_->link_off_,
396 header_->link_size_,
397 0 /* unaligned */,
398 "link") &&
399 CheckValidOffsetAndSize(header_->map_off_,
400 header_->map_off_,
401 4,
402 "map") &&
403 CheckValidOffsetAndSize(header_->string_ids_off_,
404 header_->string_ids_size_,
405 4,
406 "string-ids") &&
407 CheckValidOffsetAndSize(header_->type_ids_off_,
408 header_->type_ids_size_,
409 4,
410 "type-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100411 CheckSizeLimit(header_->type_ids_size_, DexFile::kDexNoIndex16, "type-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800412 CheckValidOffsetAndSize(header_->proto_ids_off_,
413 header_->proto_ids_size_,
414 4,
415 "proto-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100416 CheckSizeLimit(header_->proto_ids_size_, DexFile::kDexNoIndex16, "proto-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800417 CheckValidOffsetAndSize(header_->field_ids_off_,
418 header_->field_ids_size_,
419 4,
420 "field-ids") &&
421 CheckValidOffsetAndSize(header_->method_ids_off_,
422 header_->method_ids_size_,
423 4,
424 "method-ids") &&
425 CheckValidOffsetAndSize(header_->class_defs_off_,
426 header_->class_defs_size_,
427 4,
428 "class-defs") &&
429 CheckValidOffsetAndSize(header_->data_off_,
430 header_->data_size_,
431 0, // Unaligned, spec doesn't talk about it, even though size
432 // is supposed to be a multiple of 4.
433 "data");
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700434 return result;
jeffhao10037c82012-01-23 15:06:23 -0800435}
436
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700437bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700438 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
439 header_->map_off_);
440 // Check that map list content is available.
441 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
442 return false;
443 }
444
jeffhao10037c82012-01-23 15:06:23 -0800445 const DexFile::MapItem* item = map->list_;
446
447 uint32_t count = map->size_;
448 uint32_t last_offset = 0;
449 uint32_t data_item_count = 0;
450 uint32_t data_items_left = header_->data_size_;
451 uint32_t used_bits = 0;
452
453 // Sanity check the size of the map list.
454 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
455 return false;
456 }
457
458 // Check the items listed in the map.
459 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700460 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
461 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800462 return false;
463 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700464 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
465 ErrorStringPrintf("Map item after end of file: %x, size %x",
466 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800467 return false;
468 }
469
Orion Hodson12f4ff42017-01-13 16:43:12 +0000470 DexFile::MapItemType item_type = static_cast<DexFile::MapItemType>(item->type_);
471 if (IsDataSectionType(item_type)) {
jeffhao10037c82012-01-23 15:06:23 -0800472 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700473 if (UNLIKELY(icount > data_items_left)) {
474 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800475 return false;
476 }
477 data_items_left -= icount;
478 data_item_count += icount;
479 }
480
Orion Hodson12f4ff42017-01-13 16:43:12 +0000481 uint32_t bit = MapTypeToBitMask(item_type);
jeffhao10037c82012-01-23 15:06:23 -0800482
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700483 if (UNLIKELY(bit == 0)) {
484 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800485 return false;
486 }
487
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700488 if (UNLIKELY((used_bits & bit) != 0)) {
489 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800490 return false;
491 }
492
493 used_bits |= bit;
494 last_offset = item->offset_;
495 item++;
496 }
497
498 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700499 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
500 ErrorStringPrintf("Map is missing header entry");
jeffhao10037c82012-01-23 15:06:23 -0800501 return false;
502 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700503 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
504 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800505 return false;
506 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700507 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
508 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
509 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800510 return false;
511 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700512 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
513 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
514 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800515 return false;
516 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700517 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
518 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
519 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800520 return false;
521 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700522 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
523 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
524 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800525 return false;
526 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700527 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
528 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
529 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800530 return false;
531 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700532 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
533 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
534 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800535 return false;
536 }
jeffhao10037c82012-01-23 15:06:23 -0800537 return true;
538}
539
540uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
541 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700542 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700543 for (uint32_t i = 0; i < size; i++) {
544 result |= ((uint32_t) *(ptr_++)) << (i * 8);
545 }
jeffhao10037c82012-01-23 15:06:23 -0800546 }
jeffhao10037c82012-01-23 15:06:23 -0800547 return result;
548}
549
Andreas Gampebed6daf2016-09-02 18:12:00 -0700550
551#define DECODE_UNSIGNED_CHECKED_FROM_WITH_ERROR_VALUE(ptr, var, error_value) \
552 uint32_t var; \
Andreas Gampe44fd2352016-11-03 08:21:21 -0700553 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700554 return error_value; \
555 }
556
Andreas Gampe44fd2352016-11-03 08:21:21 -0700557#define DECODE_UNSIGNED_CHECKED_FROM(ptr, var) \
558 uint32_t var; \
559 if (!DecodeUnsignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
560 ErrorStringPrintf("Read out of bounds"); \
561 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700562 }
563
Andreas Gampe44fd2352016-11-03 08:21:21 -0700564#define DECODE_SIGNED_CHECKED_FROM(ptr, var) \
565 int32_t var; \
566 if (!DecodeSignedLeb128Checked(&(ptr), begin_ + size_, &(var))) { \
567 ErrorStringPrintf("Read out of bounds"); \
568 return false; \
Andreas Gampebed6daf2016-09-02 18:12:00 -0700569 }
570
jeffhao10037c82012-01-23 15:06:23 -0800571bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700572 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700573 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800574
575 for (uint32_t i = 0; i < handlers_size; i++) {
576 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800577 size_t offset = ptr_ - handlers_base;
Andreas Gampebed6daf2016-09-02 18:12:00 -0700578 DECODE_SIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800579
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700580 if (UNLIKELY((size < -65536) || (size > 65536))) {
581 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800582 return false;
583 }
584
585 if (size <= 0) {
586 catch_all = true;
587 size = -size;
588 } else {
589 catch_all = false;
590 }
591
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800592 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800593
594 while (size-- > 0) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700595 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -0800596 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
597 return false;
598 }
599
Andreas Gampebed6daf2016-09-02 18:12:00 -0700600 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700601 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
602 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800603 return false;
604 }
605 }
606
607 if (catch_all) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700608 DECODE_UNSIGNED_CHECKED_FROM(ptr_, addr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700609 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
610 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800611 return false;
612 }
613 }
614 }
615
616 return true;
617}
618
Andreas Gampee6215c02015-08-31 18:54:38 -0700619bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
620 uint32_t access_flags,
621 uint32_t class_access_flags,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800622 dex::TypeIndex class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700623 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700624 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800625 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
626 return false;
627 }
628
Andreas Gampee6215c02015-08-31 18:54:38 -0700629 // Check that it's the right class.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800630 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700631 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
632 class_idx_;
633 if (class_type_index != my_class_index) {
634 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800635 my_class_index.index_,
636 class_type_index.index_);
Andreas Gampee6215c02015-08-31 18:54:38 -0700637 return false;
638 }
639
640 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800641 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700642 if (UNLIKELY(is_static != expect_static)) {
643 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800644 return false;
645 }
646
Andreas Gampee6215c02015-08-31 18:54:38 -0700647 // Check field access flags.
648 std::string error_msg;
Andreas Gampec9f0ba12016-02-09 09:21:04 -0800649 if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700650 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800651 return false;
652 }
653
654 return true;
655}
656
Andreas Gampee6215c02015-08-31 18:54:38 -0700657bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
658 uint32_t access_flags,
659 uint32_t class_access_flags,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800660 dex::TypeIndex class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700661 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700662 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700663 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700664 DCHECK(direct_method_indexes != nullptr);
665 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800666 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
667 return false;
668 }
669
Andreas Gampee6215c02015-08-31 18:54:38 -0700670 // Check that it's the right class.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800671 dex::TypeIndex my_class_index =
Andreas Gampee6215c02015-08-31 18:54:38 -0700672 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
673 class_idx_;
674 if (class_type_index != my_class_index) {
Jeff Hao608f2ce2016-10-19 11:17:11 -0700675 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 " vs %" PRIu16,
Andreas Gampea5b09a62016-11-17 15:21:22 -0800676 my_class_index.index_,
677 class_type_index.index_);
jeffhao10037c82012-01-23 15:06:23 -0800678 return false;
679 }
680
Andreas Gampee6215c02015-08-31 18:54:38 -0700681 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700682 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700683 direct_method_indexes->insert(idx);
684 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700685 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
686 return false;
687 }
688
Andreas Gampee6215c02015-08-31 18:54:38 -0700689 std::string error_msg;
Orion Hodson6c4921b2016-09-21 15:41:06 +0100690 const char* method_name;
691 if (!FindMethodName(idx, begin_, header_, &method_name, &error_msg)) {
692 ErrorStringPrintf("%s", error_msg.c_str());
693 return false;
694 }
695
696 uint32_t constructor_flags_by_name = 0;
697 if (!GetConstructorFlagsForMethodName(method_name, &constructor_flags_by_name)) {
698 ErrorStringPrintf("Bad method name: %s", method_name);
699 return false;
700 }
701
702 bool has_code = (code_offset != 0);
Andreas Gampee6215c02015-08-31 18:54:38 -0700703 if (!CheckMethodAccessFlags(idx,
704 access_flags,
705 class_access_flags,
Orion Hodson6c4921b2016-09-21 15:41:06 +0100706 constructor_flags_by_name,
Andreas Gampee6215c02015-08-31 18:54:38 -0700707 has_code,
708 expect_direct,
709 &error_msg)) {
710 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800711 return false;
712 }
713
Orion Hodson6c4921b2016-09-21 15:41:06 +0100714 if (constructor_flags_by_name != 0) {
715 if (!CheckConstructorProperties(idx, constructor_flags_by_name)) {
716 DCHECK(FailureReasonIsSet());
717 return false;
718 }
719 }
720
jeffhao10037c82012-01-23 15:06:23 -0800721 return true;
722}
723
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800724bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800725 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700726 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800727 return false;
728 }
729 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700730 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800731 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800732 return false;
733 }
734 ptr_++;
735 offset++;
736 }
737 }
738 return true;
739}
740
741bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700742 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800743 return false;
744 }
745
746 uint8_t header_byte = *(ptr_++);
747 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
748 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
749
750 switch (value_type) {
751 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700752 if (UNLIKELY(value_arg != 0)) {
753 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800754 return false;
755 }
756 ptr_++;
757 break;
758 case DexFile::kDexAnnotationShort:
759 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700760 if (UNLIKELY(value_arg > 1)) {
761 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800762 return false;
763 }
764 ptr_ += value_arg + 1;
765 break;
766 case DexFile::kDexAnnotationInt:
767 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700768 if (UNLIKELY(value_arg > 3)) {
769 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800770 return false;
771 }
772 ptr_ += value_arg + 1;
773 break;
774 case DexFile::kDexAnnotationLong:
775 case DexFile::kDexAnnotationDouble:
776 ptr_ += value_arg + 1;
777 break;
778 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700779 if (UNLIKELY(value_arg > 3)) {
780 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800781 return false;
782 }
783 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
784 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
785 return false;
786 }
787 break;
788 }
789 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700790 if (UNLIKELY(value_arg > 3)) {
791 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800792 return false;
793 }
794 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
795 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
796 return false;
797 }
798 break;
799 }
800 case DexFile::kDexAnnotationField:
801 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700802 if (UNLIKELY(value_arg > 3)) {
803 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800804 return false;
805 }
806 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
807 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
808 return false;
809 }
810 break;
811 }
812 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700813 if (UNLIKELY(value_arg > 3)) {
814 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800815 return false;
816 }
817 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
818 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
819 return false;
820 }
821 break;
822 }
823 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700824 if (UNLIKELY(value_arg != 0)) {
825 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800826 return false;
827 }
828 if (!CheckEncodedArray()) {
829 return false;
830 }
831 break;
832 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700833 if (UNLIKELY(value_arg != 0)) {
834 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800835 return false;
836 }
837 if (!CheckEncodedAnnotation()) {
838 return false;
839 }
840 break;
841 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700842 if (UNLIKELY(value_arg != 0)) {
843 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800844 return false;
845 }
846 break;
847 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700848 if (UNLIKELY(value_arg > 1)) {
849 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800850 return false;
851 }
852 break;
Orion Hodson12f4ff42017-01-13 16:43:12 +0000853 case DexFile::kDexAnnotationMethodType: {
854 if (UNLIKELY(value_arg > 3)) {
855 ErrorStringPrintf("Bad encoded_value method type size %x", value_arg);
856 return false;
857 }
858 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
859 if (!CheckIndex(idx, header_->proto_ids_size_, "method_type value")) {
860 return false;
861 }
862 break;
863 }
864 case DexFile::kDexAnnotationMethodHandle: {
865 if (UNLIKELY(value_arg > 3)) {
866 ErrorStringPrintf("Bad encoded_value method handle size %x", value_arg);
867 return false;
868 }
869 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
870 if (!CheckIndex(idx, dex_file_->NumMethodHandles(), "method_handle value")) {
871 return false;
872 }
873 break;
874 }
jeffhao10037c82012-01-23 15:06:23 -0800875 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700876 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800877 return false;
878 }
879
880 return true;
881}
882
883bool DexFileVerifier::CheckEncodedArray() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700884 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800885
886 while (size--) {
887 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700888 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800889 return false;
890 }
891 }
892 return true;
893}
894
895bool DexFileVerifier::CheckEncodedAnnotation() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700896 DECODE_UNSIGNED_CHECKED_FROM(ptr_, anno_idx);
897 if (!CheckIndex(anno_idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -0800898 return false;
899 }
900
Andreas Gampebed6daf2016-09-02 18:12:00 -0700901 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800902 uint32_t last_idx = 0;
903
904 for (uint32_t i = 0; i < size; i++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700905 DECODE_UNSIGNED_CHECKED_FROM(ptr_, idx);
jeffhao10037c82012-01-23 15:06:23 -0800906 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
907 return false;
908 }
909
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700910 if (UNLIKELY(last_idx >= idx && i != 0)) {
911 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
912 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800913 return false;
914 }
915
916 if (!CheckEncodedValue()) {
917 return false;
918 }
919
920 last_idx = idx;
921 }
922 return true;
923}
924
Jeff Hao326c1a22017-05-04 14:12:56 -0700925bool DexFileVerifier::FindClassIndexAndDef(uint32_t index,
926 bool is_field,
927 dex::TypeIndex* class_type_index,
928 const DexFile::ClassDef** output_class_def) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700929 DCHECK(class_type_index != nullptr);
Jeff Hao326c1a22017-05-04 14:12:56 -0700930 DCHECK(output_class_def != nullptr);
Andreas Gampee6215c02015-08-31 18:54:38 -0700931
932 // First check if the index is valid.
933 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
934 return false;
935 }
936
937 // Next get the type index.
938 if (is_field) {
939 *class_type_index =
940 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
941 class_idx_;
942 } else {
943 *class_type_index =
944 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
945 class_idx_;
946 }
947
948 // Check if that is valid.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800949 if (class_type_index->index_ >= header_->type_ids_size_) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700950 return false;
951 }
952
953 // Now search for the class def. This is basically a specialized version of the DexFile code, as
954 // we should not trust that this is a valid DexFile just yet.
955 const DexFile::ClassDef* class_def_begin =
956 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
957 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
958 const DexFile::ClassDef* class_def = class_def_begin + i;
959 if (class_def->class_idx_ == *class_type_index) {
Jeff Hao326c1a22017-05-04 14:12:56 -0700960 *output_class_def = class_def;
Andreas Gampee6215c02015-08-31 18:54:38 -0700961 return true;
962 }
963 }
964
965 // Didn't find the class-def, not defined here...
966 return false;
967}
968
Jeff Hao326c1a22017-05-04 14:12:56 -0700969bool DexFileVerifier::CheckOrderAndGetClassDef(bool is_field,
970 const char* type_descr,
971 uint32_t curr_index,
972 uint32_t prev_index,
973 bool* have_class,
974 dex::TypeIndex* class_type_index,
975 const DexFile::ClassDef** class_def) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700976 if (curr_index < prev_index) {
977 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
978 type_descr,
979 prev_index,
980 curr_index);
981 return false;
982 }
983
984 if (!*have_class) {
Jeff Hao326c1a22017-05-04 14:12:56 -0700985 *have_class = FindClassIndexAndDef(curr_index, is_field, class_type_index, class_def);
Andreas Gampee6215c02015-08-31 18:54:38 -0700986 if (!*have_class) {
987 // Should have really found one.
988 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
989 type_descr,
990 curr_index);
991 return false;
992 }
993 }
994 return true;
995}
996
Jeff Hao326c1a22017-05-04 14:12:56 -0700997bool DexFileVerifier::CheckStaticFieldTypes(const DexFile::ClassDef* class_def) {
998 if (class_def == nullptr) {
999 return true;
1000 }
1001
1002 ClassDataItemIterator field_it(*dex_file_, ptr_);
1003 EncodedStaticFieldValueIterator array_it(*dex_file_, *class_def);
1004
1005 for (; field_it.HasNextStaticField() && array_it.HasNext(); field_it.Next(), array_it.Next()) {
1006 uint32_t index = field_it.GetMemberIndex();
1007 const DexFile::TypeId& type_id = dex_file_->GetTypeId(dex_file_->GetFieldId(index).type_idx_);
1008 const char* field_type_name =
1009 dex_file_->GetStringData(dex_file_->GetStringId(type_id.descriptor_idx_));
1010 Primitive::Type field_type = Primitive::GetType(field_type_name[0]);
1011 EncodedArrayValueIterator::ValueType array_type = array_it.GetValueType();
1012 // Ensure this matches RuntimeEncodedStaticFieldValueIterator.
1013 switch (array_type) {
1014 case EncodedArrayValueIterator::ValueType::kBoolean:
1015 if (field_type != Primitive::kPrimBoolean) {
1016 ErrorStringPrintf("unexpected static field initial value type: 'Z' vs '%c'",
1017 field_type_name[0]);
1018 return false;
1019 }
1020 break;
1021 case EncodedArrayValueIterator::ValueType::kByte:
1022 if (field_type != Primitive::kPrimByte) {
1023 ErrorStringPrintf("unexpected static field initial value type: 'B' vs '%c'",
1024 field_type_name[0]);
1025 return false;
1026 }
1027 break;
1028 case EncodedArrayValueIterator::ValueType::kShort:
1029 if (field_type != Primitive::kPrimShort) {
1030 ErrorStringPrintf("unexpected static field initial value type: 'S' vs '%c'",
1031 field_type_name[0]);
1032 return false;
1033 }
1034 break;
1035 case EncodedArrayValueIterator::ValueType::kChar:
1036 if (field_type != Primitive::kPrimChar) {
1037 ErrorStringPrintf("unexpected static field initial value type: 'C' vs '%c'",
1038 field_type_name[0]);
1039 return false;
1040 }
1041 break;
1042 case EncodedArrayValueIterator::ValueType::kInt:
1043 if (field_type != Primitive::kPrimInt) {
1044 ErrorStringPrintf("unexpected static field initial value type: 'I' vs '%c'",
1045 field_type_name[0]);
1046 return false;
1047 }
1048 break;
1049 case EncodedArrayValueIterator::ValueType::kLong:
1050 if (field_type != Primitive::kPrimLong) {
1051 ErrorStringPrintf("unexpected static field initial value type: 'J' vs '%c'",
1052 field_type_name[0]);
1053 return false;
1054 }
1055 break;
1056 case EncodedArrayValueIterator::ValueType::kFloat:
1057 if (field_type != Primitive::kPrimFloat) {
1058 ErrorStringPrintf("unexpected static field initial value type: 'F' vs '%c'",
1059 field_type_name[0]);
1060 return false;
1061 }
1062 break;
1063 case EncodedArrayValueIterator::ValueType::kDouble:
1064 if (field_type != Primitive::kPrimDouble) {
1065 ErrorStringPrintf("unexpected static field initial value type: 'D' vs '%c'",
1066 field_type_name[0]);
1067 return false;
1068 }
1069 break;
1070 case EncodedArrayValueIterator::ValueType::kNull:
1071 case EncodedArrayValueIterator::ValueType::kString:
1072 case EncodedArrayValueIterator::ValueType::kType:
1073 if (field_type != Primitive::kPrimNot) {
1074 ErrorStringPrintf("unexpected static field initial value type: 'L' vs '%c'",
1075 field_type_name[0]);
1076 return false;
1077 }
1078 break;
1079 default:
1080 ErrorStringPrintf("unexpected static field initial value type: %x", array_type);
1081 return false;
1082 }
1083 }
1084
1085 if (array_it.HasNext()) {
1086 ErrorStringPrintf("too many static field initial values");
1087 return false;
1088 }
1089 return true;
1090}
1091
Andreas Gampee6215c02015-08-31 18:54:38 -07001092template <bool kStatic>
1093bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
1094 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -08001095 dex::TypeIndex* class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001096 const DexFile::ClassDef** class_def) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001097 DCHECK(it != nullptr);
1098 // These calls use the raw access flags to check whether the whole dex field is valid.
1099 uint32_t prev_index = 0;
1100 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
1101 uint32_t curr_index = it->GetMemberIndex();
Jeff Hao326c1a22017-05-04 14:12:56 -07001102 if (!CheckOrderAndGetClassDef(true,
1103 kStatic ? "static field" : "instance field",
1104 curr_index,
1105 prev_index,
1106 have_class,
1107 class_type_index,
1108 class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001109 return false;
1110 }
Jeff Hao326c1a22017-05-04 14:12:56 -07001111 DCHECK(class_def != nullptr);
Andreas Gampee6215c02015-08-31 18:54:38 -07001112 if (!CheckClassDataItemField(curr_index,
1113 it->GetRawMemberAccessFlags(),
Jeff Hao326c1a22017-05-04 14:12:56 -07001114 (*class_def)->access_flags_,
Andreas Gampee6215c02015-08-31 18:54:38 -07001115 *class_type_index,
1116 kStatic)) {
1117 return false;
1118 }
Jeff Hao326c1a22017-05-04 14:12:56 -07001119
1120 prev_index = curr_index;
Andreas Gampee6215c02015-08-31 18:54:38 -07001121 }
1122
1123 return true;
1124}
1125
1126template <bool kDirect>
1127bool DexFileVerifier::CheckIntraClassDataItemMethods(
1128 ClassDataItemIterator* it,
1129 std::unordered_set<uint32_t>* direct_method_indexes,
1130 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -08001131 dex::TypeIndex* class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001132 const DexFile::ClassDef** class_def) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001133 uint32_t prev_index = 0;
1134 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
1135 uint32_t curr_index = it->GetMemberIndex();
Jeff Hao326c1a22017-05-04 14:12:56 -07001136 if (!CheckOrderAndGetClassDef(false,
1137 kDirect ? "direct method" : "virtual method",
1138 curr_index,
1139 prev_index,
1140 have_class,
1141 class_type_index,
1142 class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001143 return false;
1144 }
Jeff Hao326c1a22017-05-04 14:12:56 -07001145 DCHECK(class_def != nullptr);
Andreas Gampee6215c02015-08-31 18:54:38 -07001146 if (!CheckClassDataItemMethod(curr_index,
1147 it->GetRawMemberAccessFlags(),
Jeff Hao326c1a22017-05-04 14:12:56 -07001148 (*class_def)->access_flags_,
Andreas Gampee6215c02015-08-31 18:54:38 -07001149 *class_type_index,
1150 it->GetMethodCodeItemOffset(),
1151 direct_method_indexes,
1152 kDirect)) {
1153 return false;
1154 }
Jeff Hao326c1a22017-05-04 14:12:56 -07001155
1156 prev_index = curr_index;
Andreas Gampee6215c02015-08-31 18:54:38 -07001157 }
1158
1159 return true;
1160}
1161
jeffhao10037c82012-01-23 15:06:23 -08001162bool DexFileVerifier::CheckIntraClassDataItem() {
1163 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -07001164 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -08001165
Andreas Gampee6215c02015-08-31 18:54:38 -07001166 // This code is complicated by the fact that we don't directly know which class this belongs to.
1167 // So we need to explicitly search with the first item we find (either field or method), and then,
1168 // as the lookup is expensive, cache the result.
1169 bool have_class = false;
Andreas Gampea5b09a62016-11-17 15:21:22 -08001170 dex::TypeIndex class_type_index;
Jeff Hao326c1a22017-05-04 14:12:56 -07001171 const DexFile::ClassDef* class_def = nullptr;
Andreas Gampee6215c02015-08-31 18:54:38 -07001172
1173 // Check fields.
1174 if (!CheckIntraClassDataItemFields<true>(&it,
1175 &have_class,
1176 &class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001177 &class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001178 return false;
jeffhao10037c82012-01-23 15:06:23 -08001179 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001180 if (!CheckIntraClassDataItemFields<false>(&it,
1181 &have_class,
1182 &class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001183 &class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001184 return false;
jeffhao10037c82012-01-23 15:06:23 -08001185 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001186
1187 // Check methods.
1188 if (!CheckIntraClassDataItemMethods<true>(&it,
1189 &direct_method_indexes,
1190 &have_class,
1191 &class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001192 &class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001193 return false;
jeffhao10037c82012-01-23 15:06:23 -08001194 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001195 if (!CheckIntraClassDataItemMethods<false>(&it,
1196 &direct_method_indexes,
1197 &have_class,
1198 &class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001199 &class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001200 return false;
jeffhao10037c82012-01-23 15:06:23 -08001201 }
1202
Jeff Hao326c1a22017-05-04 14:12:56 -07001203 const uint8_t* end_ptr = it.EndDataPointer();
1204
1205 // Check static field types against initial static values in encoded array.
1206 if (!CheckStaticFieldTypes(class_def)) {
1207 return false;
1208 }
1209
1210 ptr_ = end_ptr;
jeffhao10037c82012-01-23 15:06:23 -08001211 return true;
1212}
1213
1214bool DexFileVerifier::CheckIntraCodeItem() {
1215 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001216 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -08001217 return false;
1218 }
1219
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001220 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
1221 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
1222 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -08001223 return false;
1224 }
1225
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001226 if (UNLIKELY((code_item->outs_size_ > 5) &&
1227 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -08001228 /*
1229 * outs_size can be up to 5, even if registers_size is smaller, since the
1230 * short forms of method invocation allow repetitions of a register multiple
1231 * times within a single parameter list. However, longer parameter lists
1232 * need to be represented in-order in the register file.
1233 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001234 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
1235 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -08001236 return false;
1237 }
1238
1239 const uint16_t* insns = code_item->insns_;
1240 uint32_t insns_size = code_item->insns_size_in_code_units_;
1241 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
1242 return false;
1243 }
1244
1245 // Grab the end of the insns if there are no try_items.
1246 uint32_t try_items_size = code_item->tries_size_;
1247 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001248 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001249 return true;
1250 }
1251
1252 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001253 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001254 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001255 return false;
1256 }
1257
1258 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -08001259 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
1260 return false;
1261 }
1262
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001263 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
Andreas Gampebed6daf2016-09-02 18:12:00 -07001264 DECODE_UNSIGNED_CHECKED_FROM(ptr_, handlers_size);
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001265
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001266 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
1267 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -08001268 return false;
1269 }
1270
Ian Rogers700a4022014-05-19 16:49:03 -07001271 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -07001272 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -08001273 return false;
1274 }
1275
1276 uint32_t last_addr = 0;
1277 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001278 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1279 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001280 return false;
1281 }
1282
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001283 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1284 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001285 return false;
1286 }
1287
1288 uint32_t i;
1289 for (i = 0; i < handlers_size; i++) {
1290 if (try_items->handler_off_ == handler_offsets[i]) {
1291 break;
1292 }
1293 }
1294
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001295 if (UNLIKELY(i == handlers_size)) {
1296 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -08001297 return false;
1298 }
1299
1300 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001301 if (UNLIKELY(last_addr > insns_size)) {
1302 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -08001303 return false;
1304 }
1305
1306 try_items++;
1307 }
1308
1309 return true;
1310}
1311
1312bool DexFileVerifier::CheckIntraStringDataItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001313 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
Ian Rogers13735952014-10-08 12:43:28 -07001314 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001315
1316 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001317 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001318 if (UNLIKELY(ptr_ >= file_end)) {
1319 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001320 return false;
1321 }
1322
1323 uint8_t byte = *(ptr_++);
1324
1325 // Switch on the high 4 bits.
1326 switch (byte >> 4) {
1327 case 0x00:
1328 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001329 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001330 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001331 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001332 return false;
1333 }
1334 break;
1335 case 0x01:
1336 case 0x02:
1337 case 0x03:
1338 case 0x04:
1339 case 0x05:
1340 case 0x06:
1341 case 0x07:
1342 // No extra checks necessary for bit pattern 0xxx.
1343 break;
1344 case 0x08:
1345 case 0x09:
1346 case 0x0a:
1347 case 0x0b:
1348 case 0x0f:
1349 // Illegal bit patterns 10xx or 1111.
1350 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001351 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001352 return false;
1353 case 0x0c:
1354 case 0x0d: {
1355 // Bit pattern 110x has an additional byte.
1356 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001357 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1358 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001359 return false;
1360 }
1361 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001362 if (UNLIKELY((value != 0) && (value < 0x80))) {
1363 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001364 return false;
1365 }
1366 break;
1367 }
1368 case 0x0e: {
1369 // Bit pattern 1110 has 2 additional bytes.
1370 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001371 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1372 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001373 return false;
1374 }
1375 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001376 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1377 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001378 return false;
1379 }
1380 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001381 if (UNLIKELY(value < 0x800)) {
1382 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001383 return false;
1384 }
1385 break;
1386 }
1387 }
1388 }
1389
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001390 if (UNLIKELY(*(ptr_++) != '\0')) {
1391 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001392 return false;
1393 }
1394
1395 return true;
1396}
1397
1398bool DexFileVerifier::CheckIntraDebugInfoItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001399 DECODE_UNSIGNED_CHECKED_FROM(ptr_, dummy);
1400 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameters_size);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001401 if (UNLIKELY(parameters_size > 65536)) {
1402 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001403 return false;
1404 }
1405
1406 for (uint32_t j = 0; j < parameters_size; j++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001407 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameter_name);
jeffhao10037c82012-01-23 15:06:23 -08001408 if (parameter_name != 0) {
1409 parameter_name--;
1410 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1411 return false;
1412 }
1413 }
1414 }
1415
1416 while (true) {
1417 uint8_t opcode = *(ptr_++);
1418 switch (opcode) {
1419 case DexFile::DBG_END_SEQUENCE: {
1420 return true;
1421 }
1422 case DexFile::DBG_ADVANCE_PC: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001423 DECODE_UNSIGNED_CHECKED_FROM(ptr_, advance_pc_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001424 break;
1425 }
1426 case DexFile::DBG_ADVANCE_LINE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001427 DECODE_SIGNED_CHECKED_FROM(ptr_, advance_line_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001428 break;
1429 }
1430 case DexFile::DBG_START_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001431 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001432 if (UNLIKELY(reg_num >= 65536)) {
1433 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001434 return false;
1435 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001436 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001437 if (name_idx != 0) {
1438 name_idx--;
1439 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1440 return false;
1441 }
1442 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001443 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001444 if (type_idx != 0) {
1445 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001446 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001447 return false;
1448 }
1449 }
1450 break;
1451 }
1452 case DexFile::DBG_END_LOCAL:
1453 case DexFile::DBG_RESTART_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001454 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001455 if (UNLIKELY(reg_num >= 65536)) {
1456 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001457 return false;
1458 }
1459 break;
1460 }
1461 case DexFile::DBG_START_LOCAL_EXTENDED: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001462 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001463 if (UNLIKELY(reg_num >= 65536)) {
1464 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001465 return false;
1466 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001467 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001468 if (name_idx != 0) {
1469 name_idx--;
1470 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1471 return false;
1472 }
1473 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001474 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001475 if (type_idx != 0) {
1476 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001477 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001478 return false;
1479 }
1480 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001481 DECODE_UNSIGNED_CHECKED_FROM(ptr_, sig_idx);
jeffhao10037c82012-01-23 15:06:23 -08001482 if (sig_idx != 0) {
1483 sig_idx--;
1484 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1485 return false;
1486 }
1487 }
1488 break;
1489 }
1490 case DexFile::DBG_SET_FILE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001491 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001492 if (name_idx != 0) {
1493 name_idx--;
1494 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1495 return false;
1496 }
1497 }
1498 break;
1499 }
1500 }
1501 }
1502}
1503
1504bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001505 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001506 return false;
1507 }
1508
1509 // Check visibility
1510 switch (*(ptr_++)) {
1511 case DexFile::kDexVisibilityBuild:
1512 case DexFile::kDexVisibilityRuntime:
1513 case DexFile::kDexVisibilitySystem:
1514 break;
1515 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001516 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001517 return false;
1518 }
1519
1520 if (!CheckEncodedAnnotation()) {
1521 return false;
1522 }
1523
1524 return true;
1525}
1526
1527bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1528 const DexFile::AnnotationsDirectoryItem* item =
1529 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001530 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001531 return false;
1532 }
1533
1534 // Field annotations follow immediately after the annotations directory.
1535 const DexFile::FieldAnnotationsItem* field_item =
1536 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1537 uint32_t field_count = item->fields_size_;
1538 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1539 return false;
1540 }
1541
1542 uint32_t last_idx = 0;
1543 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001544 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1545 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001546 return false;
1547 }
1548 last_idx = field_item->field_idx_;
1549 field_item++;
1550 }
1551
1552 // Method annotations follow immediately after field annotations.
1553 const DexFile::MethodAnnotationsItem* method_item =
1554 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1555 uint32_t method_count = item->methods_size_;
1556 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1557 return false;
1558 }
1559
1560 last_idx = 0;
1561 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001562 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1563 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1564 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001565 return false;
1566 }
1567 last_idx = method_item->method_idx_;
1568 method_item++;
1569 }
1570
1571 // Parameter annotations follow immediately after method annotations.
1572 const DexFile::ParameterAnnotationsItem* parameter_item =
1573 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1574 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001575 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001576 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001577 return false;
1578 }
1579
1580 last_idx = 0;
1581 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001582 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1583 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1584 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001585 return false;
1586 }
1587 last_idx = parameter_item->method_idx_;
1588 parameter_item++;
1589 }
1590
1591 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001592 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001593 return true;
1594}
1595
Andreas Gampeb061cc12014-09-02 10:22:20 -07001596bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
Orion Hodson12f4ff42017-01-13 16:43:12 +00001597 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -08001598 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001599 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001600 switch (type) {
1601 case DexFile::kDexTypeClassDataItem:
1602 case DexFile::kDexTypeStringDataItem:
1603 case DexFile::kDexTypeDebugInfoItem:
1604 case DexFile::kDexTypeAnnotationItem:
1605 case DexFile::kDexTypeEncodedArrayItem:
1606 alignment_mask = sizeof(uint8_t) - 1;
1607 break;
1608 default:
1609 alignment_mask = sizeof(uint32_t) - 1;
1610 break;
1611 }
1612
1613 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001614 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001615 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001616
1617 // Check the padding between items.
1618 if (!CheckPadding(offset, aligned_offset)) {
1619 return false;
1620 }
1621
1622 // Check depending on the section type.
Orion Hodson12f4ff42017-01-13 16:43:12 +00001623 const uint8_t* start_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08001624 switch (type) {
1625 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001626 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001627 return false;
1628 }
1629 ptr_ += sizeof(DexFile::StringId);
1630 break;
1631 }
1632 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001633 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001634 return false;
1635 }
1636 ptr_ += sizeof(DexFile::TypeId);
1637 break;
1638 }
1639 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001640 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001641 return false;
1642 }
1643 ptr_ += sizeof(DexFile::ProtoId);
1644 break;
1645 }
1646 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001647 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001648 return false;
1649 }
1650 ptr_ += sizeof(DexFile::FieldId);
1651 break;
1652 }
1653 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001654 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001655 return false;
1656 }
1657 ptr_ += sizeof(DexFile::MethodId);
1658 break;
1659 }
1660 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001661 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001662 return false;
1663 }
1664 ptr_ += sizeof(DexFile::ClassDef);
1665 break;
1666 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00001667 case DexFile::kDexTypeCallSiteIdItem: {
1668 if (!CheckListSize(ptr_, 1, sizeof(DexFile::CallSiteIdItem), "call_site_ids")) {
1669 return false;
1670 }
1671 ptr_ += sizeof(DexFile::CallSiteIdItem);
1672 break;
1673 }
1674 case DexFile::kDexTypeMethodHandleItem: {
1675 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodHandleItem), "method_handles")) {
1676 return false;
1677 }
1678 ptr_ += sizeof(DexFile::MethodHandleItem);
1679 break;
1680 }
jeffhao10037c82012-01-23 15:06:23 -08001681 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001682 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001683 return false;
1684 }
jeffhao10037c82012-01-23 15:06:23 -08001685 break;
1686 }
1687 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001688 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001689 return false;
1690 }
jeffhao10037c82012-01-23 15:06:23 -08001691 break;
1692 }
1693 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001694 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001695 return false;
1696 }
jeffhao10037c82012-01-23 15:06:23 -08001697 break;
1698 }
1699 case DexFile::kDexTypeClassDataItem: {
1700 if (!CheckIntraClassDataItem()) {
1701 return false;
1702 }
1703 break;
1704 }
1705 case DexFile::kDexTypeCodeItem: {
1706 if (!CheckIntraCodeItem()) {
1707 return false;
1708 }
1709 break;
1710 }
1711 case DexFile::kDexTypeStringDataItem: {
1712 if (!CheckIntraStringDataItem()) {
1713 return false;
1714 }
1715 break;
1716 }
1717 case DexFile::kDexTypeDebugInfoItem: {
1718 if (!CheckIntraDebugInfoItem()) {
1719 return false;
1720 }
1721 break;
1722 }
1723 case DexFile::kDexTypeAnnotationItem: {
1724 if (!CheckIntraAnnotationItem()) {
1725 return false;
1726 }
1727 break;
1728 }
1729 case DexFile::kDexTypeEncodedArrayItem: {
1730 if (!CheckEncodedArray()) {
1731 return false;
1732 }
1733 break;
1734 }
1735 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1736 if (!CheckIntraAnnotationsDirectoryItem()) {
1737 return false;
1738 }
1739 break;
1740 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00001741 case DexFile::kDexTypeHeaderItem:
1742 case DexFile::kDexTypeMapList:
1743 break;
1744 }
1745
1746 if (start_ptr == ptr_) {
1747 ErrorStringPrintf("Unknown map item type %x", type);
1748 return false;
jeffhao10037c82012-01-23 15:06:23 -08001749 }
1750
1751 if (IsDataSectionType(type)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001752 if (aligned_offset == 0u) {
1753 ErrorStringPrintf("Item %d offset is 0", i);
1754 return false;
1755 }
1756 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1757 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001758 }
1759
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001760 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001761 if (UNLIKELY(aligned_offset > size_)) {
1762 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001763 return false;
1764 }
1765
1766 offset = aligned_offset;
1767 }
1768
1769 return true;
1770}
1771
Orion Hodson12f4ff42017-01-13 16:43:12 +00001772bool DexFileVerifier::CheckIntraIdSection(size_t offset,
1773 uint32_t count,
1774 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -08001775 uint32_t expected_offset;
1776 uint32_t expected_size;
1777
1778 // Get the expected offset and size from the header.
1779 switch (type) {
1780 case DexFile::kDexTypeStringIdItem:
1781 expected_offset = header_->string_ids_off_;
1782 expected_size = header_->string_ids_size_;
1783 break;
1784 case DexFile::kDexTypeTypeIdItem:
1785 expected_offset = header_->type_ids_off_;
1786 expected_size = header_->type_ids_size_;
1787 break;
1788 case DexFile::kDexTypeProtoIdItem:
1789 expected_offset = header_->proto_ids_off_;
1790 expected_size = header_->proto_ids_size_;
1791 break;
1792 case DexFile::kDexTypeFieldIdItem:
1793 expected_offset = header_->field_ids_off_;
1794 expected_size = header_->field_ids_size_;
1795 break;
1796 case DexFile::kDexTypeMethodIdItem:
1797 expected_offset = header_->method_ids_off_;
1798 expected_size = header_->method_ids_size_;
1799 break;
1800 case DexFile::kDexTypeClassDefItem:
1801 expected_offset = header_->class_defs_off_;
1802 expected_size = header_->class_defs_size_;
1803 break;
1804 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001805 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001806 return false;
1807 }
1808
1809 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001810 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001811 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001812 return false;
1813 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001814 if (UNLIKELY(count != expected_size)) {
1815 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001816 return false;
1817 }
1818
1819 return CheckIntraSectionIterate(offset, count, type);
1820}
1821
Orion Hodson12f4ff42017-01-13 16:43:12 +00001822bool DexFileVerifier::CheckIntraDataSection(size_t offset,
1823 uint32_t count,
1824 DexFile::MapItemType type) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001825 size_t data_start = header_->data_off_;
1826 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001827
1828 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001829 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001830 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001831 return false;
1832 }
1833
1834 if (!CheckIntraSectionIterate(offset, count, type)) {
1835 return false;
1836 }
1837
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001838 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001839 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001840 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001841 return false;
1842 }
1843
1844 return true;
1845}
1846
1847bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001848 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001849 const DexFile::MapItem* item = map->list_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001850 size_t offset = 0;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001851 uint32_t count = map->size_;
Ian Rogers30fab402012-01-23 15:43:46 -08001852 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001853
1854 // Check the items listed in the map.
1855 while (count--) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00001856 const size_t current_offset = offset;
jeffhao10037c82012-01-23 15:06:23 -08001857 uint32_t section_offset = item->offset_;
1858 uint32_t section_count = item->size_;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001859 DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
jeffhao10037c82012-01-23 15:06:23 -08001860
1861 // Check for padding and overlap between items.
1862 if (!CheckPadding(offset, section_offset)) {
1863 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001864 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001865 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001866 return false;
1867 }
1868
1869 // Check each item based on its type.
1870 switch (type) {
1871 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001872 if (UNLIKELY(section_count != 1)) {
1873 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001874 return false;
1875 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001876 if (UNLIKELY(section_offset != 0)) {
1877 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001878 return false;
1879 }
Ian Rogers30fab402012-01-23 15:43:46 -08001880 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001881 offset = header_->header_size_;
1882 break;
1883 case DexFile::kDexTypeStringIdItem:
1884 case DexFile::kDexTypeTypeIdItem:
1885 case DexFile::kDexTypeProtoIdItem:
1886 case DexFile::kDexTypeFieldIdItem:
1887 case DexFile::kDexTypeMethodIdItem:
1888 case DexFile::kDexTypeClassDefItem:
1889 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1890 return false;
1891 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001892 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001893 break;
1894 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001895 if (UNLIKELY(section_count != 1)) {
1896 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001897 return false;
1898 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001899 if (UNLIKELY(section_offset != header_->map_off_)) {
1900 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1901 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001902 return false;
1903 }
1904 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1905 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1906 break;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001907 case DexFile::kDexTypeMethodHandleItem:
1908 case DexFile::kDexTypeCallSiteIdItem:
1909 CheckIntraSectionIterate(section_offset, section_count, type);
1910 offset = ptr_ - begin_;
1911 break;
jeffhao10037c82012-01-23 15:06:23 -08001912 case DexFile::kDexTypeTypeList:
1913 case DexFile::kDexTypeAnnotationSetRefList:
1914 case DexFile::kDexTypeAnnotationSetItem:
1915 case DexFile::kDexTypeClassDataItem:
1916 case DexFile::kDexTypeCodeItem:
1917 case DexFile::kDexTypeStringDataItem:
1918 case DexFile::kDexTypeDebugInfoItem:
1919 case DexFile::kDexTypeAnnotationItem:
1920 case DexFile::kDexTypeEncodedArrayItem:
1921 case DexFile::kDexTypeAnnotationsDirectoryItem:
1922 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1923 return false;
1924 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001925 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001926 break;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001927 }
1928
1929 if (offset == current_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001930 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001931 return false;
1932 }
1933
1934 item++;
1935 }
1936
1937 return true;
1938}
1939
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001940bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001941 DCHECK_NE(offset, 0u);
1942 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001943 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001944 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001945 return false;
1946 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001947 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001948 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001949 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001950 return false;
1951 }
1952 return true;
1953}
1954
Andreas Gampea5b09a62016-11-17 15:21:22 -08001955dex::TypeIndex DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001956 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001957 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001958
1959 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001960 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001961 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001962 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001963 }
1964
1965 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001966 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001967 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001968 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001969 }
1970
Andreas Gampea5b09a62016-11-17 15:21:22 -08001971 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001972}
1973
Andreas Gampea5b09a62016-11-17 15:21:22 -08001974dex::TypeIndex DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr,
1975 bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001976 const DexFile::AnnotationsDirectoryItem* item =
1977 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001978 *success = true;
1979
jeffhao10037c82012-01-23 15:06:23 -08001980 if (item->fields_size_ != 0) {
1981 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001982 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001983 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001984 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001985 }
1986
1987 if (item->methods_size_ != 0) {
1988 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001989 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001990 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001991 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001992 }
1993
1994 if (item->parameters_size_ != 0) {
1995 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001996 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001997 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001998 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001999 }
2000
Andreas Gampea5b09a62016-11-17 15:21:22 -08002001 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08002002}
2003
2004bool DexFileVerifier::CheckInterStringIdItem() {
2005 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
2006
2007 // Check the map to make sure it has the right offset->type.
2008 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
2009 return false;
2010 }
2011
2012 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002013 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002014 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
2015 const char* prev_str = dex_file_->GetStringData(*prev_item);
2016 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002017 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
2018 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08002019 return false;
2020 }
2021 }
2022
2023 ptr_ += sizeof(DexFile::StringId);
2024 return true;
2025}
2026
2027bool DexFileVerifier::CheckInterTypeIdItem() {
2028 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07002029
2030 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08002031
2032 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002033 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
2034 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002035 return false;
2036 }
2037
2038 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002039 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002040 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002041 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
2042 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002043 prev_item->descriptor_idx_.index_,
2044 item->descriptor_idx_.index_);
jeffhao10037c82012-01-23 15:06:23 -08002045 return false;
2046 }
2047 }
2048
2049 ptr_ += sizeof(DexFile::TypeId);
2050 return true;
2051}
2052
2053bool DexFileVerifier::CheckInterProtoIdItem() {
2054 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07002055
2056 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
2057
jeffhao10037c82012-01-23 15:06:23 -08002058 if (item->parameters_off_ != 0 &&
2059 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
2060 return false;
2061 }
2062
David Sehr28e74ed2016-11-21 12:52:12 -08002063 // Check that return type is representable as a uint16_t;
2064 if (UNLIKELY(!IsValidOrNoTypeId(item->return_type_idx_.index_, item->pad_))) {
2065 ErrorStringPrintf("proto with return type idx outside uint16_t range '%x:%x'",
2066 item->pad_, item->return_type_idx_.index_);
2067 return false;
2068 }
jeffhao10037c82012-01-23 15:06:23 -08002069 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07002070 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
2071 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08002072 return false;
2073 }
2074 shorty++;
2075
2076 DexFileParameterIterator it(*dex_file_, *item);
2077 while (it.HasNext() && *shorty != '\0') {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002078 if (!CheckIndex(it.GetTypeIdx().index_,
2079 dex_file_->NumTypeIds(),
Andreas Gampebb836e12014-06-13 15:31:40 -07002080 "inter_proto_id_item shorty type_idx")) {
2081 return false;
2082 }
jeffhao10037c82012-01-23 15:06:23 -08002083 const char* descriptor = it.GetDescriptor();
2084 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
2085 return false;
2086 }
2087 it.Next();
2088 shorty++;
2089 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002090 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
2091 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08002092 return false;
2093 }
2094
2095 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002096 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002097 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002098 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
2099 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08002100 return false;
2101 } else if (prev->return_type_idx_ == item->return_type_idx_) {
2102 DexFileParameterIterator curr_it(*dex_file_, *item);
2103 DexFileParameterIterator prev_it(*dex_file_, *prev);
2104
2105 while (curr_it.HasNext() && prev_it.HasNext()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002106 dex::TypeIndex prev_idx = prev_it.GetTypeIdx();
2107 dex::TypeIndex curr_idx = curr_it.GetTypeIdx();
2108 DCHECK_NE(prev_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
2109 DCHECK_NE(curr_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
jeffhao10037c82012-01-23 15:06:23 -08002110
2111 if (prev_idx < curr_idx) {
2112 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002113 } else if (UNLIKELY(prev_idx > curr_idx)) {
2114 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08002115 return false;
2116 }
2117
2118 prev_it.Next();
2119 curr_it.Next();
2120 }
Vladimir Marko0ca8add2016-05-03 17:17:50 +01002121 if (!curr_it.HasNext()) {
2122 // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
2123 // a ProtoId with a longer one. Both cases are forbidden by the specification.
2124 ErrorStringPrintf("Out-of-order proto_id arguments");
2125 return false;
2126 }
jeffhao10037c82012-01-23 15:06:23 -08002127 }
2128 }
2129
2130 ptr_ += sizeof(DexFile::ProtoId);
2131 return true;
2132}
2133
2134bool DexFileVerifier::CheckInterFieldIdItem() {
2135 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
2136
2137 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07002138 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
2139 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
2140 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002141 return false;
2142 }
2143
2144 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07002145 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
2146 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
2147 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002148 return false;
2149 }
2150
2151 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07002152 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002153 if (UNLIKELY(!IsValidMemberName(descriptor))) {
2154 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002155 return false;
2156 }
2157
2158 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002159 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002160 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002161 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
2162 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002163 return false;
2164 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002165 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
2166 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002167 return false;
2168 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002169 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
2170 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002171 return false;
2172 }
2173 }
2174 }
2175 }
2176
2177 ptr_ += sizeof(DexFile::FieldId);
2178 return true;
2179}
2180
2181bool DexFileVerifier::CheckInterMethodIdItem() {
2182 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
2183
2184 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07002185 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
2186 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
2187 class_descriptor[0] != '['))) {
2188 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002189 return false;
2190 }
2191
2192 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07002193 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002194 if (UNLIKELY(!IsValidMemberName(descriptor))) {
2195 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002196 return false;
2197 }
2198
Andreas Gampedf10b322014-06-11 21:46:05 -07002199 // Check that the proto id is valid.
2200 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
2201 "inter_method_id_item proto_idx"))) {
2202 return false;
2203 }
2204
jeffhao10037c82012-01-23 15:06:23 -08002205 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002206 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002207 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002208 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
2209 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002210 return false;
2211 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002212 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
2213 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002214 return false;
2215 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002216 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
2217 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002218 return false;
2219 }
2220 }
2221 }
2222 }
2223
2224 ptr_ += sizeof(DexFile::MethodId);
2225 return true;
2226}
2227
2228bool DexFileVerifier::CheckInterClassDefItem() {
2229 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08002230
David Sehr28e74ed2016-11-21 12:52:12 -08002231 // Check that class_idx_ is representable as a uint16_t;
2232 if (UNLIKELY(!IsValidTypeId(item->class_idx_.index_, item->pad1_))) {
2233 ErrorStringPrintf("class with type idx outside uint16_t range '%x:%x'", item->pad1_,
2234 item->class_idx_.index_);
2235 return false;
2236 }
2237 // Check that superclass_idx_ is representable as a uint16_t;
2238 if (UNLIKELY(!IsValidOrNoTypeId(item->superclass_idx_.index_, item->pad2_))) {
2239 ErrorStringPrintf("class with superclass type idx outside uint16_t range '%x:%x'", item->pad2_,
2240 item->superclass_idx_.index_);
2241 return false;
2242 }
Andreas Gampe0ba238d2014-07-29 01:22:07 -07002243 // Check for duplicate class def.
2244 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002245 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_.index_);
Andreas Gampe0ba238d2014-07-29 01:22:07 -07002246 return false;
2247 }
2248 defined_classes_.insert(item->class_idx_);
2249
Andreas Gampee09269c2014-06-06 18:45:35 -07002250 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
2251 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
2252 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002253 return false;
2254 }
2255
Andreas Gampeacc2bb62014-07-17 19:26:50 -07002256 // Only allow non-runtime modifiers.
2257 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
2258 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
2259 return false;
2260 }
2261
jeffhao10037c82012-01-23 15:06:23 -08002262 if (item->interfaces_off_ != 0 &&
2263 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
2264 return false;
2265 }
2266 if (item->annotations_off_ != 0 &&
2267 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
2268 return false;
2269 }
2270 if (item->class_data_off_ != 0 &&
2271 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
2272 return false;
2273 }
2274 if (item->static_values_off_ != 0 &&
2275 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
2276 return false;
2277 }
2278
Andreas Gampea5b09a62016-11-17 15:21:22 -08002279 if (item->superclass_idx_.IsValid()) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002280 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2281 // Check that a class does not inherit from itself directly (by having
2282 // the same type idx as its super class).
2283 if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002284 ErrorStringPrintf("Class with same type idx as its superclass: '%d'",
2285 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002286 return false;
2287 }
2288
2289 // Check that a class is defined after its super class (if the
2290 // latter is defined in the same Dex file).
2291 const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
2292 if (superclass_def != nullptr) {
2293 // The superclass is defined in this Dex file.
2294 if (superclass_def > item) {
2295 // ClassDef item for super class appearing after the class' ClassDef item.
2296 ErrorStringPrintf("Invalid class definition ordering:"
2297 " class with type idx: '%d' defined before"
2298 " superclass with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002299 item->class_idx_.index_,
2300 item->superclass_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002301 return false;
2302 }
2303 }
2304 }
2305
Andreas Gampee09269c2014-06-06 18:45:35 -07002306 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
2307 "inter_class_def_item superclass_idx")
2308 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
2309 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002310 return false;
2311 }
2312 }
2313
Roland Levillain621b5ea2016-05-18 11:41:33 +01002314 // Check interfaces.
jeffhao10037c82012-01-23 15:06:23 -08002315 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002316 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002317 uint32_t size = interfaces->Size();
jeffhao10037c82012-01-23 15:06:23 -08002318 for (uint32_t i = 0; i < size; i++) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002319 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2320 // Check that a class does not implement itself directly (by having the
2321 // same type idx as one of its immediate implemented interfaces).
2322 if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2323 ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002324 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002325 return false;
2326 }
2327
2328 // Check that a class is defined after the interfaces it implements
2329 // (if they are defined in the same Dex file).
2330 const DexFile::ClassDef* interface_def =
2331 dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2332 if (interface_def != nullptr) {
2333 // The interface is defined in this Dex file.
2334 if (interface_def > item) {
2335 // ClassDef item for interface appearing after the class' ClassDef item.
2336 ErrorStringPrintf("Invalid class definition ordering:"
2337 " class with type idx: '%d' defined before"
2338 " implemented interface with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002339 item->class_idx_.index_,
2340 interfaces->GetTypeItem(i).type_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002341 return false;
2342 }
2343 }
2344 }
2345
2346 // Ensure that the interface refers to a class (not an array nor a primitive type).
Andreas Gampee09269c2014-06-06 18:45:35 -07002347 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2348 "inter_class_def_item interface type_idx")
2349 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2350 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002351 return false;
2352 }
2353 }
2354
2355 /*
2356 * Ensure that there are no duplicates. This is an O(N^2) test, but in
2357 * practice the number of interfaces implemented by any given class is low.
2358 */
2359 for (uint32_t i = 1; i < size; i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002360 dex::TypeIndex idx1 = interfaces->GetTypeItem(i).type_idx_;
jeffhao10037c82012-01-23 15:06:23 -08002361 for (uint32_t j =0; j < i; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002362 dex::TypeIndex idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002363 if (UNLIKELY(idx1 == idx2)) {
2364 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08002365 return false;
2366 }
2367 }
2368 }
2369 }
2370
2371 // Check that references in class_data_item are to the right class.
2372 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07002373 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002374 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002375 dex::TypeIndex data_definer = FindFirstClassDataDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002376 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002377 return false;
2378 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08002379 if (UNLIKELY((data_definer != item->class_idx_) &&
2380 (data_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002381 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08002382 return false;
2383 }
2384 }
2385
2386 // Check that references in annotations_directory_item are to right class.
2387 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002388 // annotations_off_ is supposed to be aligned by 4.
2389 if (!IsAlignedParam(item->annotations_off_, 4)) {
2390 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2391 return false;
2392 }
Ian Rogers13735952014-10-08 12:43:28 -07002393 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002394 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002395 dex::TypeIndex annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002396 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002397 return false;
2398 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002399 if (UNLIKELY((annotations_definer != item->class_idx_) &&
Andreas Gampea5b09a62016-11-17 15:21:22 -08002400 (annotations_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002401 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002402 return false;
2403 }
2404 }
2405
2406 ptr_ += sizeof(DexFile::ClassDef);
2407 return true;
2408}
2409
Orion Hodson12f4ff42017-01-13 16:43:12 +00002410bool DexFileVerifier::CheckInterCallSiteIdItem() {
2411 const DexFile::CallSiteIdItem* item = reinterpret_cast<const DexFile::CallSiteIdItem*>(ptr_);
2412
2413 // Check call site referenced by item is in encoded array section.
2414 if (!CheckOffsetToTypeMap(item->data_off_, DexFile::kDexTypeEncodedArrayItem)) {
2415 ErrorStringPrintf("Invalid offset in CallSideIdItem");
2416 return false;
2417 }
2418
2419 CallSiteArrayValueIterator it(*dex_file_, *item);
2420
2421 // Check Method Handle
2422 if (!it.HasNext() || it.GetValueType() != EncodedArrayValueIterator::ValueType::kMethodHandle) {
2423 ErrorStringPrintf("CallSiteArray missing method handle");
2424 return false;
2425 }
2426
2427 uint32_t handle_index = static_cast<uint32_t>(it.GetJavaValue().i);
2428 if (handle_index >= dex_file_->NumMethodHandles()) {
2429 ErrorStringPrintf("CallSite has bad method handle id: %x", handle_index);
2430 return false;
2431 }
2432
2433 // Check target method name.
2434 it.Next();
2435 if (!it.HasNext() ||
2436 it.GetValueType() != EncodedArrayValueIterator::ValueType::kString) {
2437 ErrorStringPrintf("CallSiteArray missing target method name");
2438 return false;
2439 }
2440
2441 uint32_t name_index = static_cast<uint32_t>(it.GetJavaValue().i);
2442 if (name_index >= dex_file_->NumStringIds()) {
2443 ErrorStringPrintf("CallSite has bad method name id: %x", name_index);
2444 return false;
2445 }
2446
2447 // Check method type.
2448 it.Next();
2449 if (!it.HasNext() ||
2450 it.GetValueType() != EncodedArrayValueIterator::ValueType::kMethodType) {
2451 ErrorStringPrintf("CallSiteArray missing method type");
2452 return false;
2453 }
2454
2455 uint32_t proto_index = static_cast<uint32_t>(it.GetJavaValue().i);
2456 if (proto_index >= dex_file_->NumProtoIds()) {
2457 ErrorStringPrintf("CallSite has bad method type: %x", proto_index);
2458 return false;
2459 }
2460
2461 ptr_ += sizeof(DexFile::CallSiteIdItem);
2462 return true;
2463}
2464
2465bool DexFileVerifier::CheckInterMethodHandleItem() {
2466 const DexFile::MethodHandleItem* item = reinterpret_cast<const DexFile::MethodHandleItem*>(ptr_);
2467
2468 DexFile::MethodHandleType method_handle_type =
2469 static_cast<DexFile::MethodHandleType>(item->method_handle_type_);
2470 if (method_handle_type > DexFile::MethodHandleType::kLast) {
2471 ErrorStringPrintf("Bad method handle type %x", item->method_handle_type_);
2472 return false;
2473 }
2474
2475 uint32_t index = item->field_or_method_idx_;
2476 switch (method_handle_type) {
Orion Hodsonc069a302017-01-18 09:23:12 +00002477 case DexFile::MethodHandleType::kStaticPut:
2478 case DexFile::MethodHandleType::kStaticGet:
2479 case DexFile::MethodHandleType::kInstancePut:
2480 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson12f4ff42017-01-13 16:43:12 +00002481 LOAD_FIELD(field, index, "method_handle_item field_idx", return false);
2482 break;
2483 }
2484 case DexFile::MethodHandleType::kInvokeStatic:
2485 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodson631827d2017-04-10 14:53:47 +01002486 case DexFile::MethodHandleType::kInvokeConstructor:
2487 case DexFile::MethodHandleType::kInvokeDirect:
2488 case DexFile::MethodHandleType::kInvokeInterface: {
Orion Hodson12f4ff42017-01-13 16:43:12 +00002489 LOAD_METHOD(method, index, "method_handle_item method_idx", return false);
2490 break;
2491 }
2492 }
2493
2494 ptr_ += sizeof(DexFile::MethodHandleItem);
2495 return true;
2496}
2497
jeffhao10037c82012-01-23 15:06:23 -08002498bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2499 const DexFile::AnnotationSetRefList* list =
2500 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2501 const DexFile::AnnotationSetRefItem* item = list->list_;
2502 uint32_t count = list->size_;
2503
2504 while (count--) {
2505 if (item->annotations_off_ != 0 &&
2506 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2507 return false;
2508 }
2509 item++;
2510 }
2511
Ian Rogers13735952014-10-08 12:43:28 -07002512 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002513 return true;
2514}
2515
2516bool DexFileVerifier::CheckInterAnnotationSetItem() {
2517 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2518 const uint32_t* offsets = set->entries_;
2519 uint32_t count = set->size_;
2520 uint32_t last_idx = 0;
2521
2522 for (uint32_t i = 0; i < count; i++) {
2523 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2524 return false;
2525 }
2526
2527 // Get the annotation from the offset and the type index for the annotation.
2528 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002529 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002530 const uint8_t* data = annotation->annotation_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002531 DECODE_UNSIGNED_CHECKED_FROM(data, idx);
jeffhao10037c82012-01-23 15:06:23 -08002532
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002533 if (UNLIKELY(last_idx >= idx && i != 0)) {
2534 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002535 return false;
2536 }
2537
2538 last_idx = idx;
2539 offsets++;
2540 }
2541
Ian Rogers13735952014-10-08 12:43:28 -07002542 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002543 return true;
2544}
2545
2546bool DexFileVerifier::CheckInterClassDataItem() {
2547 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002548 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002549 dex::TypeIndex defining_class = FindFirstClassDataDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002550 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002551 return false;
2552 }
jeffhao10037c82012-01-23 15:06:23 -08002553
2554 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002555 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002556 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002557 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002558 return false;
2559 }
2560 }
2561 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2562 uint32_t code_off = it.GetMethodCodeItemOffset();
2563 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2564 return false;
2565 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002566 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002567 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002568 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002569 return false;
2570 }
2571 }
2572
2573 ptr_ = it.EndDataPointer();
2574 return true;
2575}
2576
2577bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2578 const DexFile::AnnotationsDirectoryItem* item =
2579 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002580 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002581 dex::TypeIndex defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002582 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002583 return false;
2584 }
jeffhao10037c82012-01-23 15:06:23 -08002585
2586 if (item->class_annotations_off_ != 0 &&
2587 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2588 return false;
2589 }
2590
2591 // Field annotations follow immediately after the annotations directory.
2592 const DexFile::FieldAnnotationsItem* field_item =
2593 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2594 uint32_t field_count = item->fields_size_;
2595 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002596 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2597 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002598 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002599 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002600 return false;
2601 }
2602 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2603 return false;
2604 }
2605 field_item++;
2606 }
2607
2608 // Method annotations follow immediately after field annotations.
2609 const DexFile::MethodAnnotationsItem* method_item =
2610 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2611 uint32_t method_count = item->methods_size_;
2612 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002613 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002614 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002615 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002616 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002617 return false;
2618 }
2619 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2620 return false;
2621 }
2622 method_item++;
2623 }
2624
2625 // Parameter annotations follow immediately after method annotations.
2626 const DexFile::ParameterAnnotationsItem* parameter_item =
2627 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2628 uint32_t parameter_count = item->parameters_size_;
2629 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002630 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002631 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002632 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002633 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002634 return false;
2635 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002636 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2637 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002638 return false;
2639 }
2640 parameter_item++;
2641 }
2642
Ian Rogers13735952014-10-08 12:43:28 -07002643 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002644 return true;
2645}
2646
Orion Hodson12f4ff42017-01-13 16:43:12 +00002647bool DexFileVerifier::CheckInterSectionIterate(size_t offset,
2648 uint32_t count,
2649 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -08002650 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002651 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002652 switch (type) {
2653 case DexFile::kDexTypeClassDataItem:
2654 alignment_mask = sizeof(uint8_t) - 1;
2655 break;
2656 default:
2657 alignment_mask = sizeof(uint32_t) - 1;
2658 break;
2659 }
2660
2661 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002662 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002663 for (uint32_t i = 0; i < count; i++) {
2664 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002665 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002666 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002667
Orion Hodson12f4ff42017-01-13 16:43:12 +00002668 if (MapTypeToBitMask(type) == 0) {
2669 ErrorStringPrintf("Unknown map item type %x", type);
2670 return false;
2671 }
2672
jeffhao10037c82012-01-23 15:06:23 -08002673 // Check depending on the section type.
2674 switch (type) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00002675 case DexFile::kDexTypeHeaderItem:
2676 case DexFile::kDexTypeMapList:
2677 case DexFile::kDexTypeTypeList:
2678 case DexFile::kDexTypeCodeItem:
2679 case DexFile::kDexTypeStringDataItem:
2680 case DexFile::kDexTypeDebugInfoItem:
2681 case DexFile::kDexTypeAnnotationItem:
2682 case DexFile::kDexTypeEncodedArrayItem:
2683 break;
jeffhao10037c82012-01-23 15:06:23 -08002684 case DexFile::kDexTypeStringIdItem: {
2685 if (!CheckInterStringIdItem()) {
2686 return false;
2687 }
2688 break;
2689 }
2690 case DexFile::kDexTypeTypeIdItem: {
2691 if (!CheckInterTypeIdItem()) {
2692 return false;
2693 }
2694 break;
2695 }
2696 case DexFile::kDexTypeProtoIdItem: {
2697 if (!CheckInterProtoIdItem()) {
2698 return false;
2699 }
2700 break;
2701 }
2702 case DexFile::kDexTypeFieldIdItem: {
2703 if (!CheckInterFieldIdItem()) {
2704 return false;
2705 }
2706 break;
2707 }
2708 case DexFile::kDexTypeMethodIdItem: {
2709 if (!CheckInterMethodIdItem()) {
2710 return false;
2711 }
2712 break;
2713 }
2714 case DexFile::kDexTypeClassDefItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002715 // There shouldn't be more class definitions than type ids allow.
2716 // This check should be redundant, since there are checks that the
2717 // class_idx_ is within range and that there is only one definition
2718 // for a given type id.
2719 if (i > kTypeIdLimit) {
2720 ErrorStringPrintf("Too many class definition items");
2721 return false;
2722 }
jeffhao10037c82012-01-23 15:06:23 -08002723 if (!CheckInterClassDefItem()) {
2724 return false;
2725 }
2726 break;
2727 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00002728 case DexFile::kDexTypeCallSiteIdItem: {
2729 if (!CheckInterCallSiteIdItem()) {
2730 return false;
2731 }
2732 break;
2733 }
2734 case DexFile::kDexTypeMethodHandleItem: {
2735 if (!CheckInterMethodHandleItem()) {
2736 return false;
2737 }
2738 break;
2739 }
jeffhao10037c82012-01-23 15:06:23 -08002740 case DexFile::kDexTypeAnnotationSetRefList: {
2741 if (!CheckInterAnnotationSetRefList()) {
2742 return false;
2743 }
2744 break;
2745 }
2746 case DexFile::kDexTypeAnnotationSetItem: {
2747 if (!CheckInterAnnotationSetItem()) {
2748 return false;
2749 }
2750 break;
2751 }
2752 case DexFile::kDexTypeClassDataItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002753 // There shouldn't be more class data than type ids allow.
2754 // This check should be redundant, since there are checks that the
2755 // class_idx_ is within range and that there is only one definition
2756 // for a given type id.
2757 if (i > kTypeIdLimit) {
2758 ErrorStringPrintf("Too many class data items");
2759 return false;
2760 }
jeffhao10037c82012-01-23 15:06:23 -08002761 if (!CheckInterClassDataItem()) {
2762 return false;
2763 }
2764 break;
2765 }
2766 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2767 if (!CheckInterAnnotationsDirectoryItem()) {
2768 return false;
2769 }
2770 break;
2771 }
jeffhao10037c82012-01-23 15:06:23 -08002772 }
2773
2774 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002775 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002776 }
2777
2778 return true;
2779}
2780
2781bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002782 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002783 const DexFile::MapItem* item = map->list_;
2784 uint32_t count = map->size_;
2785
2786 // Cross check the items listed in the map.
2787 while (count--) {
2788 uint32_t section_offset = item->offset_;
2789 uint32_t section_count = item->size_;
Orion Hodson12f4ff42017-01-13 16:43:12 +00002790 DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
2791 bool found = false;
jeffhao10037c82012-01-23 15:06:23 -08002792
2793 switch (type) {
2794 case DexFile::kDexTypeHeaderItem:
2795 case DexFile::kDexTypeMapList:
2796 case DexFile::kDexTypeTypeList:
2797 case DexFile::kDexTypeCodeItem:
2798 case DexFile::kDexTypeStringDataItem:
2799 case DexFile::kDexTypeDebugInfoItem:
2800 case DexFile::kDexTypeAnnotationItem:
2801 case DexFile::kDexTypeEncodedArrayItem:
Orion Hodson12f4ff42017-01-13 16:43:12 +00002802 found = true;
jeffhao10037c82012-01-23 15:06:23 -08002803 break;
2804 case DexFile::kDexTypeStringIdItem:
2805 case DexFile::kDexTypeTypeIdItem:
2806 case DexFile::kDexTypeProtoIdItem:
2807 case DexFile::kDexTypeFieldIdItem:
2808 case DexFile::kDexTypeMethodIdItem:
2809 case DexFile::kDexTypeClassDefItem:
Orion Hodson12f4ff42017-01-13 16:43:12 +00002810 case DexFile::kDexTypeCallSiteIdItem:
2811 case DexFile::kDexTypeMethodHandleItem:
jeffhao10037c82012-01-23 15:06:23 -08002812 case DexFile::kDexTypeAnnotationSetRefList:
2813 case DexFile::kDexTypeAnnotationSetItem:
2814 case DexFile::kDexTypeClassDataItem:
2815 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2816 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2817 return false;
2818 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00002819 found = true;
jeffhao10037c82012-01-23 15:06:23 -08002820 break;
2821 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00002822 }
2823
2824 if (!found) {
2825 ErrorStringPrintf("Unknown map item type %x", item->type_);
2826 return false;
jeffhao10037c82012-01-23 15:06:23 -08002827 }
2828
2829 item++;
2830 }
2831
2832 return true;
2833}
2834
2835bool DexFileVerifier::Verify() {
2836 // Check the header.
2837 if (!CheckHeader()) {
2838 return false;
2839 }
2840
2841 // Check the map section.
2842 if (!CheckMap()) {
2843 return false;
2844 }
2845
2846 // Check structure within remaining sections.
2847 if (!CheckIntraSection()) {
2848 return false;
2849 }
2850
2851 // Check references from one section to another.
2852 if (!CheckInterSection()) {
2853 return false;
2854 }
2855
2856 return true;
2857}
2858
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002859void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2860 va_list ap;
2861 va_start(ap, fmt);
2862 DCHECK(failure_reason_.empty()) << failure_reason_;
2863 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2864 StringAppendV(&failure_reason_, fmt, ap);
2865 va_end(ap);
2866}
2867
Andreas Gampee6215c02015-08-31 18:54:38 -07002868// Fields and methods may have only one of public/protected/private.
2869static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2870 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2871 (((flags & kAccProtected) == 0) ? 0 : 1) +
2872 (((flags & kAccPrivate) == 0) ? 0 : 1);
2873 return count <= 1;
2874}
2875
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002876// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2877// functionality, as we're still verifying the dex file. begin and header correspond to the
2878// underscored variants in the DexFileVerifier.
2879
2880static std::string GetStringOrError(const uint8_t* const begin,
2881 const DexFile::Header* const header,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002882 dex::StringIndex string_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002883 // The `string_idx` is not guaranteed to be valid yet.
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002884 if (header->string_ids_size_ <= string_idx.index_) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002885 return "(error)";
2886 }
2887
2888 const DexFile::StringId* string_id =
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002889 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_)
2890 + string_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002891
2892 // Assume that the data is OK at this point. String data has been checked at this point.
2893
2894 const uint8_t* ptr = begin + string_id->string_data_off_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002895 uint32_t dummy;
2896 if (!DecodeUnsignedLeb128Checked(&ptr, begin + header->file_size_, &dummy)) {
2897 return "(error)";
2898 }
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002899 return reinterpret_cast<const char*>(ptr);
2900}
2901
2902static std::string GetClassOrError(const uint8_t* const begin,
2903 const DexFile::Header* const header,
Andreas Gampea5b09a62016-11-17 15:21:22 -08002904 dex::TypeIndex class_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002905 // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2906 // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2907 // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2908 // a valid defining class.
Andreas Gampea5b09a62016-11-17 15:21:22 -08002909 CHECK_LT(class_idx.index_, header->type_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002910
2911 const DexFile::TypeId* type_id =
Andreas Gampea5b09a62016-11-17 15:21:22 -08002912 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002913
2914 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2915
2916 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2917}
2918
2919static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2920 const DexFile::Header* const header,
2921 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002922 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2923 CHECK_LT(idx, header->field_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002924
2925 const DexFile::FieldId* field_id =
2926 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2927
2928 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2929
2930 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2931 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2932
2933 return class_name + "." + field_name;
2934}
2935
2936static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2937 const DexFile::Header* const header,
2938 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002939 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2940 CHECK_LT(idx, header->method_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002941
2942 const DexFile::MethodId* method_id =
2943 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2944
2945 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2946
2947 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2948 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2949
2950 return class_name + "." + method_name;
2951}
2952
2953bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2954 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002955 uint32_t class_access_flags,
2956 std::string* error_msg) {
2957 // Generally sort out >16-bit flags.
2958 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002959 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2960 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2961 field_access_flags,
2962 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002963 return false;
2964 }
2965
2966 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2967 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2968 kAccPrivate |
2969 kAccProtected |
2970 kAccStatic |
2971 kAccFinal |
2972 kAccVolatile |
2973 kAccTransient |
2974 kAccSynthetic |
2975 kAccEnum;
2976
2977 // Fields may have only one of public/protected/final.
2978 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002979 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2980 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2981 field_access_flags,
2982 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002983 return false;
2984 }
2985
2986 // Interfaces have a pretty restricted list.
2987 if ((class_access_flags & kAccInterface) != 0) {
2988 // Interface fields must be public final static.
2989 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2990 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002991 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2992 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2993 field_access_flags,
2994 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002995 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002996 return false;
2997 } else {
2998 // Allow in older versions, but warn.
2999 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3000 << *error_msg;
3001 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003002 }
3003 // Interface fields may be synthetic, but may not have other flags.
3004 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
3005 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003006 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
3007 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
3008 field_access_flags,
3009 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07003010 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07003011 return false;
3012 } else {
3013 // Allow in older versions, but warn.
3014 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3015 << *error_msg;
3016 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003017 }
3018 return true;
3019 }
3020
3021 // Volatile fields may not be final.
3022 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
3023 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003024 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
3025 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003026 return false;
3027 }
3028
3029 return true;
3030}
3031
Andreas Gampee6215c02015-08-31 18:54:38 -07003032bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
3033 uint32_t method_access_flags,
3034 uint32_t class_access_flags,
Orion Hodson6c4921b2016-09-21 15:41:06 +01003035 uint32_t constructor_flags_by_name,
Andreas Gampee6215c02015-08-31 18:54:38 -07003036 bool has_code,
3037 bool expect_direct,
3038 std::string* error_msg) {
3039 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
3040 constexpr uint32_t kAllMethodFlags =
3041 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
3042 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003043 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
3044 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3045 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07003046 return false;
3047 }
3048
3049 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
3050 constexpr uint32_t kMethodAccessFlags = kAccPublic |
3051 kAccPrivate |
3052 kAccProtected |
3053 kAccStatic |
3054 kAccFinal |
3055 kAccSynthetic |
3056 kAccSynchronized |
3057 kAccBridge |
3058 kAccVarargs |
3059 kAccNative |
3060 kAccAbstract |
3061 kAccStrict;
3062
3063 // Methods may have only one of public/protected/final.
3064 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003065 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
3066 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07003067 method_access_flags);
3068 return false;
3069 }
3070
Orion Hodson6c4921b2016-09-21 15:41:06 +01003071 constexpr uint32_t kConstructorFlags = kAccStatic | kAccConstructor;
3072 const bool is_constructor_by_name = (constructor_flags_by_name & kConstructorFlags) != 0;
3073 const bool is_clinit_by_name = constructor_flags_by_name == kConstructorFlags;
Andreas Gampee6215c02015-08-31 18:54:38 -07003074
3075 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
3076 // the reverse for backwards compatibility reasons.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003077 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003078 *error_msg =
3079 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
Orion Hodson6c4921b2016-09-21 15:41:06 +01003080 method_index,
3081 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003082 return false;
3083 }
Orion Hodson6c4921b2016-09-21 15:41:06 +01003084
3085 if (is_constructor_by_name) {
3086 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
3087 // instance constructor is called "<init>".
Andreas Gampee6215c02015-08-31 18:54:38 -07003088 bool is_static = (method_access_flags & kAccStatic) != 0;
3089 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003090 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
3091 method_index,
3092 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07003093 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3094 return false;
3095 } else {
3096 // Allow in older versions, but warn.
3097 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3098 << *error_msg;
3099 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003100 }
3101 }
Orion Hodson6c4921b2016-09-21 15:41:06 +01003102
Andreas Gampee6215c02015-08-31 18:54:38 -07003103 // Check that static and private methods, as well as constructors, are in the direct methods list,
3104 // and other methods in the virtual methods list.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003105 bool is_direct = ((method_access_flags & (kAccStatic | kAccPrivate)) != 0) ||
3106 is_constructor_by_name;
Andreas Gampee6215c02015-08-31 18:54:38 -07003107 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003108 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07003109 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003110 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07003111 expect_direct);
3112 return false;
3113 }
3114
Andreas Gampee6215c02015-08-31 18:54:38 -07003115 // From here on out it is easier to mask out the bits we're supposed to ignore.
3116 method_access_flags &= kMethodAccessFlags;
3117
Alex Lightd7c10c22016-03-31 10:03:07 -07003118 // Interfaces are special.
3119 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07003120 // Non-static interface methods must be public or private.
3121 uint32_t desired_flags = (kAccPublic | kAccStatic);
3122 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3123 desired_flags |= kAccPrivate;
3124 }
3125 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07003126 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
3127 method_index,
3128 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07003129 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07003130 return false;
3131 } else {
3132 // Allow in older versions, but warn.
3133 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3134 << *error_msg;
3135 }
3136 }
3137 }
3138
Andreas Gampee6215c02015-08-31 18:54:38 -07003139 // If there aren't any instructions, make sure that's expected.
3140 if (!has_code) {
3141 // Only native or abstract methods may not have code.
3142 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003143 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07003144 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003145 method_index,
3146 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003147 return false;
3148 }
3149 // Constructors must always have code.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003150 if (is_constructor_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003151 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
3152 method_index,
3153 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07003154 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3155 return false;
3156 } else {
3157 // Allow in older versions, but warn.
3158 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3159 << *error_msg;
3160 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003161 }
3162 if ((method_access_flags & kAccAbstract) != 0) {
3163 // Abstract methods are not allowed to have the following flags.
3164 constexpr uint32_t kForbidden =
3165 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
3166 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003167 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
3168 method_index,
3169 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3170 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07003171 return false;
3172 }
Andreas Gampe97b11352015-12-10 16:23:41 -08003173 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07003174 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003175 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08003176 << " is abstract, but the declaring class is neither abstract nor an "
3177 << "interface in dex file "
3178 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07003179 }
3180 }
3181 // Interfaces are special.
3182 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07003183 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07003184 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003185 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
3186 method_index,
3187 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07003188 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07003189 return false;
3190 } else {
3191 // Allow in older versions, but warn.
3192 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3193 << *error_msg;
3194 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003195 }
3196 // At this point, we know the method is public and abstract. This means that all the checks
3197 // for invalid combinations above applies. In addition, interface methods must not be
3198 // protected. This is caught by the check for only-one-of-public-protected-private.
3199 }
3200 return true;
3201 }
3202
3203 // When there's code, the method must not be native or abstract.
3204 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003205 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
3206 method_index,
3207 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003208 return false;
3209 }
3210
Andreas Gampee6215c02015-08-31 18:54:38 -07003211 // Instance constructors must not be synchronized and a few other flags.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003212 if (constructor_flags_by_name == kAccConstructor) {
Andreas Gampee6215c02015-08-31 18:54:38 -07003213 static constexpr uint32_t kInitAllowed =
3214 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
3215 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003216 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07003217 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003218 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07003219 method_access_flags);
3220 return false;
3221 }
3222 }
3223
3224 return true;
3225}
3226
Orion Hodson6c4921b2016-09-21 15:41:06 +01003227bool DexFileVerifier::CheckConstructorProperties(
3228 uint32_t method_index,
3229 uint32_t constructor_flags) {
3230 DCHECK(constructor_flags == kAccConstructor ||
3231 constructor_flags == (kAccConstructor | kAccStatic));
3232
3233 // Check signature matches expectations.
3234 const DexFile::MethodId* const method_id = CheckLoadMethodId(method_index,
3235 "Bad <init>/<clinit> method id");
3236 if (method_id == nullptr) {
3237 return false;
3238 }
3239
3240 // Check the ProtoId for the corresponding method.
3241 //
3242 // TODO(oth): the error message here is to satisfy the MethodId test
3243 // in the DexFileVerifierTest. The test is checking that the error
3244 // contains this string if the index is out of range.
3245 const DexFile::ProtoId* const proto_id = CheckLoadProtoId(method_id->proto_idx_,
3246 "inter_method_id_item proto_idx");
3247 if (proto_id == nullptr) {
3248 return false;
3249 }
3250
3251 Signature signature = dex_file_->GetMethodSignature(*method_id);
3252 if (constructor_flags == (kAccStatic | kAccConstructor)) {
3253 if (!signature.IsVoid() || signature.GetNumberOfParameters() != 0) {
3254 ErrorStringPrintf("<clinit> must have descriptor ()V");
3255 return false;
3256 }
3257 } else if (!signature.IsVoid()) {
3258 ErrorStringPrintf("Constructor %u(%s) must be void",
3259 method_index,
3260 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3261 return false;
3262 }
3263
3264 return true;
3265}
3266
jeffhao10037c82012-01-23 15:06:23 -08003267} // namespace art