blob: 025952f7a9c6d43b60c0a8bccece2535eb66430f [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) {
Nicolas Geoffray28453cf2017-08-10 15:30:26 +0100366 ErrorStringPrintf("Bad file size (%zd, expected %u)", 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
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700724bool DexFileVerifier::CheckPadding(size_t offset,
725 uint32_t aligned_offset,
726 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -0800727 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700728 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800729 return false;
730 }
731 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700732 if (UNLIKELY(*ptr_ != '\0')) {
Mathieu Chartier24066ec2017-10-21 16:01:08 -0700733 ErrorStringPrintf("Non-zero padding %x before section of type %zu at offset 0x%zx",
734 *ptr_,
735 static_cast<size_t>(type),
736 offset);
jeffhao10037c82012-01-23 15:06:23 -0800737 return false;
738 }
739 ptr_++;
740 offset++;
741 }
742 }
743 return true;
744}
745
746bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700747 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800748 return false;
749 }
750
751 uint8_t header_byte = *(ptr_++);
752 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
753 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
754
755 switch (value_type) {
756 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700757 if (UNLIKELY(value_arg != 0)) {
758 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800759 return false;
760 }
761 ptr_++;
762 break;
763 case DexFile::kDexAnnotationShort:
764 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700765 if (UNLIKELY(value_arg > 1)) {
766 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800767 return false;
768 }
769 ptr_ += value_arg + 1;
770 break;
771 case DexFile::kDexAnnotationInt:
772 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700773 if (UNLIKELY(value_arg > 3)) {
774 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800775 return false;
776 }
777 ptr_ += value_arg + 1;
778 break;
779 case DexFile::kDexAnnotationLong:
780 case DexFile::kDexAnnotationDouble:
781 ptr_ += value_arg + 1;
782 break;
783 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700784 if (UNLIKELY(value_arg > 3)) {
785 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800786 return false;
787 }
788 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
789 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
790 return false;
791 }
792 break;
793 }
794 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700795 if (UNLIKELY(value_arg > 3)) {
796 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800797 return false;
798 }
799 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
800 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
801 return false;
802 }
803 break;
804 }
805 case DexFile::kDexAnnotationField:
806 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700807 if (UNLIKELY(value_arg > 3)) {
808 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800809 return false;
810 }
811 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
812 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
813 return false;
814 }
815 break;
816 }
817 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700818 if (UNLIKELY(value_arg > 3)) {
819 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800820 return false;
821 }
822 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
823 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
824 return false;
825 }
826 break;
827 }
828 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700829 if (UNLIKELY(value_arg != 0)) {
830 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800831 return false;
832 }
833 if (!CheckEncodedArray()) {
834 return false;
835 }
836 break;
837 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700838 if (UNLIKELY(value_arg != 0)) {
839 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800840 return false;
841 }
842 if (!CheckEncodedAnnotation()) {
843 return false;
844 }
845 break;
846 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700847 if (UNLIKELY(value_arg != 0)) {
848 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800849 return false;
850 }
851 break;
852 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700853 if (UNLIKELY(value_arg > 1)) {
854 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800855 return false;
856 }
857 break;
Orion Hodson12f4ff42017-01-13 16:43:12 +0000858 case DexFile::kDexAnnotationMethodType: {
859 if (UNLIKELY(value_arg > 3)) {
860 ErrorStringPrintf("Bad encoded_value method type size %x", value_arg);
861 return false;
862 }
863 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
864 if (!CheckIndex(idx, header_->proto_ids_size_, "method_type value")) {
865 return false;
866 }
867 break;
868 }
869 case DexFile::kDexAnnotationMethodHandle: {
870 if (UNLIKELY(value_arg > 3)) {
871 ErrorStringPrintf("Bad encoded_value method handle size %x", value_arg);
872 return false;
873 }
874 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
875 if (!CheckIndex(idx, dex_file_->NumMethodHandles(), "method_handle value")) {
876 return false;
877 }
878 break;
879 }
jeffhao10037c82012-01-23 15:06:23 -0800880 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700881 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800882 return false;
883 }
884
885 return true;
886}
887
888bool DexFileVerifier::CheckEncodedArray() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700889 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800890
891 while (size--) {
892 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700893 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800894 return false;
895 }
896 }
897 return true;
898}
899
900bool DexFileVerifier::CheckEncodedAnnotation() {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700901 DECODE_UNSIGNED_CHECKED_FROM(ptr_, anno_idx);
902 if (!CheckIndex(anno_idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -0800903 return false;
904 }
905
Andreas Gampebed6daf2016-09-02 18:12:00 -0700906 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
jeffhao10037c82012-01-23 15:06:23 -0800907 uint32_t last_idx = 0;
908
909 for (uint32_t i = 0; i < size; i++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -0700910 DECODE_UNSIGNED_CHECKED_FROM(ptr_, idx);
jeffhao10037c82012-01-23 15:06:23 -0800911 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
912 return false;
913 }
914
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700915 if (UNLIKELY(last_idx >= idx && i != 0)) {
916 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
917 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800918 return false;
919 }
920
921 if (!CheckEncodedValue()) {
922 return false;
923 }
924
925 last_idx = idx;
926 }
927 return true;
928}
929
Jeff Hao326c1a22017-05-04 14:12:56 -0700930bool DexFileVerifier::FindClassIndexAndDef(uint32_t index,
931 bool is_field,
932 dex::TypeIndex* class_type_index,
933 const DexFile::ClassDef** output_class_def) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700934 DCHECK(class_type_index != nullptr);
Jeff Hao326c1a22017-05-04 14:12:56 -0700935 DCHECK(output_class_def != nullptr);
Andreas Gampee6215c02015-08-31 18:54:38 -0700936
937 // First check if the index is valid.
938 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
939 return false;
940 }
941
942 // Next get the type index.
943 if (is_field) {
944 *class_type_index =
945 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
946 class_idx_;
947 } else {
948 *class_type_index =
949 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
950 class_idx_;
951 }
952
953 // Check if that is valid.
Andreas Gampea5b09a62016-11-17 15:21:22 -0800954 if (class_type_index->index_ >= header_->type_ids_size_) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700955 return false;
956 }
957
958 // Now search for the class def. This is basically a specialized version of the DexFile code, as
959 // we should not trust that this is a valid DexFile just yet.
960 const DexFile::ClassDef* class_def_begin =
961 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
962 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
963 const DexFile::ClassDef* class_def = class_def_begin + i;
964 if (class_def->class_idx_ == *class_type_index) {
Jeff Hao326c1a22017-05-04 14:12:56 -0700965 *output_class_def = class_def;
Andreas Gampee6215c02015-08-31 18:54:38 -0700966 return true;
967 }
968 }
969
970 // Didn't find the class-def, not defined here...
971 return false;
972}
973
Jeff Hao326c1a22017-05-04 14:12:56 -0700974bool DexFileVerifier::CheckOrderAndGetClassDef(bool is_field,
975 const char* type_descr,
976 uint32_t curr_index,
977 uint32_t prev_index,
978 bool* have_class,
979 dex::TypeIndex* class_type_index,
980 const DexFile::ClassDef** class_def) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700981 if (curr_index < prev_index) {
982 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
983 type_descr,
984 prev_index,
985 curr_index);
986 return false;
987 }
988
989 if (!*have_class) {
Jeff Hao326c1a22017-05-04 14:12:56 -0700990 *have_class = FindClassIndexAndDef(curr_index, is_field, class_type_index, class_def);
Andreas Gampee6215c02015-08-31 18:54:38 -0700991 if (!*have_class) {
992 // Should have really found one.
993 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
994 type_descr,
995 curr_index);
996 return false;
997 }
998 }
999 return true;
1000}
1001
Jeff Hao326c1a22017-05-04 14:12:56 -07001002bool DexFileVerifier::CheckStaticFieldTypes(const DexFile::ClassDef* class_def) {
1003 if (class_def == nullptr) {
1004 return true;
1005 }
1006
1007 ClassDataItemIterator field_it(*dex_file_, ptr_);
1008 EncodedStaticFieldValueIterator array_it(*dex_file_, *class_def);
1009
1010 for (; field_it.HasNextStaticField() && array_it.HasNext(); field_it.Next(), array_it.Next()) {
1011 uint32_t index = field_it.GetMemberIndex();
1012 const DexFile::TypeId& type_id = dex_file_->GetTypeId(dex_file_->GetFieldId(index).type_idx_);
1013 const char* field_type_name =
1014 dex_file_->GetStringData(dex_file_->GetStringId(type_id.descriptor_idx_));
1015 Primitive::Type field_type = Primitive::GetType(field_type_name[0]);
1016 EncodedArrayValueIterator::ValueType array_type = array_it.GetValueType();
1017 // Ensure this matches RuntimeEncodedStaticFieldValueIterator.
1018 switch (array_type) {
1019 case EncodedArrayValueIterator::ValueType::kBoolean:
1020 if (field_type != Primitive::kPrimBoolean) {
1021 ErrorStringPrintf("unexpected static field initial value type: 'Z' vs '%c'",
1022 field_type_name[0]);
1023 return false;
1024 }
1025 break;
1026 case EncodedArrayValueIterator::ValueType::kByte:
1027 if (field_type != Primitive::kPrimByte) {
1028 ErrorStringPrintf("unexpected static field initial value type: 'B' vs '%c'",
1029 field_type_name[0]);
1030 return false;
1031 }
1032 break;
1033 case EncodedArrayValueIterator::ValueType::kShort:
1034 if (field_type != Primitive::kPrimShort) {
1035 ErrorStringPrintf("unexpected static field initial value type: 'S' vs '%c'",
1036 field_type_name[0]);
1037 return false;
1038 }
1039 break;
1040 case EncodedArrayValueIterator::ValueType::kChar:
1041 if (field_type != Primitive::kPrimChar) {
1042 ErrorStringPrintf("unexpected static field initial value type: 'C' vs '%c'",
1043 field_type_name[0]);
1044 return false;
1045 }
1046 break;
1047 case EncodedArrayValueIterator::ValueType::kInt:
1048 if (field_type != Primitive::kPrimInt) {
1049 ErrorStringPrintf("unexpected static field initial value type: 'I' vs '%c'",
1050 field_type_name[0]);
1051 return false;
1052 }
1053 break;
1054 case EncodedArrayValueIterator::ValueType::kLong:
1055 if (field_type != Primitive::kPrimLong) {
1056 ErrorStringPrintf("unexpected static field initial value type: 'J' vs '%c'",
1057 field_type_name[0]);
1058 return false;
1059 }
1060 break;
1061 case EncodedArrayValueIterator::ValueType::kFloat:
1062 if (field_type != Primitive::kPrimFloat) {
1063 ErrorStringPrintf("unexpected static field initial value type: 'F' vs '%c'",
1064 field_type_name[0]);
1065 return false;
1066 }
1067 break;
1068 case EncodedArrayValueIterator::ValueType::kDouble:
1069 if (field_type != Primitive::kPrimDouble) {
1070 ErrorStringPrintf("unexpected static field initial value type: 'D' vs '%c'",
1071 field_type_name[0]);
1072 return false;
1073 }
1074 break;
1075 case EncodedArrayValueIterator::ValueType::kNull:
1076 case EncodedArrayValueIterator::ValueType::kString:
1077 case EncodedArrayValueIterator::ValueType::kType:
1078 if (field_type != Primitive::kPrimNot) {
1079 ErrorStringPrintf("unexpected static field initial value type: 'L' vs '%c'",
1080 field_type_name[0]);
1081 return false;
1082 }
1083 break;
1084 default:
1085 ErrorStringPrintf("unexpected static field initial value type: %x", array_type);
1086 return false;
1087 }
1088 }
1089
1090 if (array_it.HasNext()) {
1091 ErrorStringPrintf("too many static field initial values");
1092 return false;
1093 }
1094 return true;
1095}
1096
Andreas Gampee6215c02015-08-31 18:54:38 -07001097template <bool kStatic>
1098bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
1099 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -08001100 dex::TypeIndex* class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001101 const DexFile::ClassDef** class_def) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001102 DCHECK(it != nullptr);
1103 // These calls use the raw access flags to check whether the whole dex field is valid.
1104 uint32_t prev_index = 0;
1105 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
1106 uint32_t curr_index = it->GetMemberIndex();
Jeff Hao326c1a22017-05-04 14:12:56 -07001107 if (!CheckOrderAndGetClassDef(true,
1108 kStatic ? "static field" : "instance field",
1109 curr_index,
1110 prev_index,
1111 have_class,
1112 class_type_index,
1113 class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001114 return false;
1115 }
Jeff Hao326c1a22017-05-04 14:12:56 -07001116 DCHECK(class_def != nullptr);
Andreas Gampee6215c02015-08-31 18:54:38 -07001117 if (!CheckClassDataItemField(curr_index,
1118 it->GetRawMemberAccessFlags(),
Jeff Hao326c1a22017-05-04 14:12:56 -07001119 (*class_def)->access_flags_,
Andreas Gampee6215c02015-08-31 18:54:38 -07001120 *class_type_index,
1121 kStatic)) {
1122 return false;
1123 }
Jeff Hao326c1a22017-05-04 14:12:56 -07001124
1125 prev_index = curr_index;
Andreas Gampee6215c02015-08-31 18:54:38 -07001126 }
1127
1128 return true;
1129}
1130
1131template <bool kDirect>
1132bool DexFileVerifier::CheckIntraClassDataItemMethods(
1133 ClassDataItemIterator* it,
1134 std::unordered_set<uint32_t>* direct_method_indexes,
1135 bool* have_class,
Andreas Gampea5b09a62016-11-17 15:21:22 -08001136 dex::TypeIndex* class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001137 const DexFile::ClassDef** class_def) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001138 uint32_t prev_index = 0;
1139 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
1140 uint32_t curr_index = it->GetMemberIndex();
Jeff Hao326c1a22017-05-04 14:12:56 -07001141 if (!CheckOrderAndGetClassDef(false,
1142 kDirect ? "direct method" : "virtual method",
1143 curr_index,
1144 prev_index,
1145 have_class,
1146 class_type_index,
1147 class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001148 return false;
1149 }
Jeff Hao326c1a22017-05-04 14:12:56 -07001150 DCHECK(class_def != nullptr);
Andreas Gampee6215c02015-08-31 18:54:38 -07001151 if (!CheckClassDataItemMethod(curr_index,
1152 it->GetRawMemberAccessFlags(),
Jeff Hao326c1a22017-05-04 14:12:56 -07001153 (*class_def)->access_flags_,
Andreas Gampee6215c02015-08-31 18:54:38 -07001154 *class_type_index,
1155 it->GetMethodCodeItemOffset(),
1156 direct_method_indexes,
1157 kDirect)) {
1158 return false;
1159 }
Jeff Hao326c1a22017-05-04 14:12:56 -07001160
1161 prev_index = curr_index;
Andreas Gampee6215c02015-08-31 18:54:38 -07001162 }
1163
1164 return true;
1165}
1166
jeffhao10037c82012-01-23 15:06:23 -08001167bool DexFileVerifier::CheckIntraClassDataItem() {
1168 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -07001169 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -08001170
Andreas Gampee6215c02015-08-31 18:54:38 -07001171 // This code is complicated by the fact that we don't directly know which class this belongs to.
1172 // So we need to explicitly search with the first item we find (either field or method), and then,
1173 // as the lookup is expensive, cache the result.
1174 bool have_class = false;
Andreas Gampea5b09a62016-11-17 15:21:22 -08001175 dex::TypeIndex class_type_index;
Jeff Hao326c1a22017-05-04 14:12:56 -07001176 const DexFile::ClassDef* class_def = nullptr;
Andreas Gampee6215c02015-08-31 18:54:38 -07001177
1178 // Check fields.
1179 if (!CheckIntraClassDataItemFields<true>(&it,
1180 &have_class,
1181 &class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001182 &class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001183 return false;
jeffhao10037c82012-01-23 15:06:23 -08001184 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001185 if (!CheckIntraClassDataItemFields<false>(&it,
1186 &have_class,
1187 &class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001188 &class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001189 return false;
jeffhao10037c82012-01-23 15:06:23 -08001190 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001191
1192 // Check methods.
1193 if (!CheckIntraClassDataItemMethods<true>(&it,
1194 &direct_method_indexes,
1195 &have_class,
1196 &class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001197 &class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001198 return false;
jeffhao10037c82012-01-23 15:06:23 -08001199 }
Andreas Gampee6215c02015-08-31 18:54:38 -07001200 if (!CheckIntraClassDataItemMethods<false>(&it,
1201 &direct_method_indexes,
1202 &have_class,
1203 &class_type_index,
Jeff Hao326c1a22017-05-04 14:12:56 -07001204 &class_def)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07001205 return false;
jeffhao10037c82012-01-23 15:06:23 -08001206 }
1207
Jeff Hao326c1a22017-05-04 14:12:56 -07001208 const uint8_t* end_ptr = it.EndDataPointer();
1209
1210 // Check static field types against initial static values in encoded array.
1211 if (!CheckStaticFieldTypes(class_def)) {
1212 return false;
1213 }
1214
1215 ptr_ = end_ptr;
jeffhao10037c82012-01-23 15:06:23 -08001216 return true;
1217}
1218
1219bool DexFileVerifier::CheckIntraCodeItem() {
1220 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001221 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -08001222 return false;
1223 }
1224
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001225 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
1226 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
1227 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -08001228 return false;
1229 }
1230
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001231 if (UNLIKELY((code_item->outs_size_ > 5) &&
1232 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -08001233 /*
1234 * outs_size can be up to 5, even if registers_size is smaller, since the
1235 * short forms of method invocation allow repetitions of a register multiple
1236 * times within a single parameter list. However, longer parameter lists
1237 * need to be represented in-order in the register file.
1238 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001239 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
1240 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -08001241 return false;
1242 }
1243
1244 const uint16_t* insns = code_item->insns_;
1245 uint32_t insns_size = code_item->insns_size_in_code_units_;
1246 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
1247 return false;
1248 }
1249
1250 // Grab the end of the insns if there are no try_items.
1251 uint32_t try_items_size = code_item->tries_size_;
1252 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001253 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001254 return true;
1255 }
1256
1257 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001258 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001259 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -08001260 return false;
1261 }
1262
1263 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -08001264 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
1265 return false;
1266 }
1267
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001268 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
Andreas Gampebed6daf2016-09-02 18:12:00 -07001269 DECODE_UNSIGNED_CHECKED_FROM(ptr_, handlers_size);
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001270
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001271 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
1272 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -08001273 return false;
1274 }
1275
Ian Rogers700a4022014-05-19 16:49:03 -07001276 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -07001277 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -08001278 return false;
1279 }
1280
1281 uint32_t last_addr = 0;
1282 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001283 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1284 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001285 return false;
1286 }
1287
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001288 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1289 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001290 return false;
1291 }
1292
1293 uint32_t i;
1294 for (i = 0; i < handlers_size; i++) {
1295 if (try_items->handler_off_ == handler_offsets[i]) {
1296 break;
1297 }
1298 }
1299
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001300 if (UNLIKELY(i == handlers_size)) {
1301 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -08001302 return false;
1303 }
1304
1305 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001306 if (UNLIKELY(last_addr > insns_size)) {
1307 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -08001308 return false;
1309 }
1310
1311 try_items++;
1312 }
1313
1314 return true;
1315}
1316
1317bool DexFileVerifier::CheckIntraStringDataItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001318 DECODE_UNSIGNED_CHECKED_FROM(ptr_, size);
Ian Rogers13735952014-10-08 12:43:28 -07001319 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001320
1321 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001322 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001323 if (UNLIKELY(ptr_ >= file_end)) {
1324 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001325 return false;
1326 }
1327
1328 uint8_t byte = *(ptr_++);
1329
1330 // Switch on the high 4 bits.
1331 switch (byte >> 4) {
1332 case 0x00:
1333 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001334 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001335 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001336 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001337 return false;
1338 }
1339 break;
1340 case 0x01:
1341 case 0x02:
1342 case 0x03:
1343 case 0x04:
1344 case 0x05:
1345 case 0x06:
1346 case 0x07:
1347 // No extra checks necessary for bit pattern 0xxx.
1348 break;
1349 case 0x08:
1350 case 0x09:
1351 case 0x0a:
1352 case 0x0b:
1353 case 0x0f:
1354 // Illegal bit patterns 10xx or 1111.
1355 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001356 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001357 return false;
1358 case 0x0c:
1359 case 0x0d: {
1360 // Bit pattern 110x has an additional byte.
1361 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001362 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1363 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001364 return false;
1365 }
1366 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001367 if (UNLIKELY((value != 0) && (value < 0x80))) {
1368 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001369 return false;
1370 }
1371 break;
1372 }
1373 case 0x0e: {
1374 // Bit pattern 1110 has 2 additional bytes.
1375 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001376 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1377 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001378 return false;
1379 }
1380 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001381 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1382 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001383 return false;
1384 }
1385 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001386 if (UNLIKELY(value < 0x800)) {
1387 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001388 return false;
1389 }
1390 break;
1391 }
1392 }
1393 }
1394
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001395 if (UNLIKELY(*(ptr_++) != '\0')) {
1396 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001397 return false;
1398 }
1399
1400 return true;
1401}
1402
1403bool DexFileVerifier::CheckIntraDebugInfoItem() {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001404 DECODE_UNSIGNED_CHECKED_FROM(ptr_, dummy);
1405 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameters_size);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001406 if (UNLIKELY(parameters_size > 65536)) {
1407 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001408 return false;
1409 }
1410
1411 for (uint32_t j = 0; j < parameters_size; j++) {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001412 DECODE_UNSIGNED_CHECKED_FROM(ptr_, parameter_name);
jeffhao10037c82012-01-23 15:06:23 -08001413 if (parameter_name != 0) {
1414 parameter_name--;
1415 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1416 return false;
1417 }
1418 }
1419 }
1420
1421 while (true) {
1422 uint8_t opcode = *(ptr_++);
1423 switch (opcode) {
1424 case DexFile::DBG_END_SEQUENCE: {
1425 return true;
1426 }
1427 case DexFile::DBG_ADVANCE_PC: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001428 DECODE_UNSIGNED_CHECKED_FROM(ptr_, advance_pc_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001429 break;
1430 }
1431 case DexFile::DBG_ADVANCE_LINE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001432 DECODE_SIGNED_CHECKED_FROM(ptr_, advance_line_dummy);
jeffhao10037c82012-01-23 15:06:23 -08001433 break;
1434 }
1435 case DexFile::DBG_START_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001436 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001437 if (UNLIKELY(reg_num >= 65536)) {
1438 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001439 return false;
1440 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001441 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001442 if (name_idx != 0) {
1443 name_idx--;
1444 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1445 return false;
1446 }
1447 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001448 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001449 if (type_idx != 0) {
1450 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001451 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001452 return false;
1453 }
1454 }
1455 break;
1456 }
1457 case DexFile::DBG_END_LOCAL:
1458 case DexFile::DBG_RESTART_LOCAL: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001459 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001460 if (UNLIKELY(reg_num >= 65536)) {
1461 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001462 return false;
1463 }
1464 break;
1465 }
1466 case DexFile::DBG_START_LOCAL_EXTENDED: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001467 DECODE_UNSIGNED_CHECKED_FROM(ptr_, reg_num);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001468 if (UNLIKELY(reg_num >= 65536)) {
1469 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001470 return false;
1471 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001472 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001473 if (name_idx != 0) {
1474 name_idx--;
1475 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1476 return false;
1477 }
1478 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001479 DECODE_UNSIGNED_CHECKED_FROM(ptr_, type_idx);
jeffhao10037c82012-01-23 15:06:23 -08001480 if (type_idx != 0) {
1481 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001482 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001483 return false;
1484 }
1485 }
Andreas Gampebed6daf2016-09-02 18:12:00 -07001486 DECODE_UNSIGNED_CHECKED_FROM(ptr_, sig_idx);
jeffhao10037c82012-01-23 15:06:23 -08001487 if (sig_idx != 0) {
1488 sig_idx--;
1489 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1490 return false;
1491 }
1492 }
1493 break;
1494 }
1495 case DexFile::DBG_SET_FILE: {
Andreas Gampebed6daf2016-09-02 18:12:00 -07001496 DECODE_UNSIGNED_CHECKED_FROM(ptr_, name_idx);
jeffhao10037c82012-01-23 15:06:23 -08001497 if (name_idx != 0) {
1498 name_idx--;
1499 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1500 return false;
1501 }
1502 }
1503 break;
1504 }
1505 }
1506 }
1507}
1508
1509bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001510 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001511 return false;
1512 }
1513
1514 // Check visibility
1515 switch (*(ptr_++)) {
1516 case DexFile::kDexVisibilityBuild:
1517 case DexFile::kDexVisibilityRuntime:
1518 case DexFile::kDexVisibilitySystem:
1519 break;
1520 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001521 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001522 return false;
1523 }
1524
1525 if (!CheckEncodedAnnotation()) {
1526 return false;
1527 }
1528
1529 return true;
1530}
1531
1532bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1533 const DexFile::AnnotationsDirectoryItem* item =
1534 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001535 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001536 return false;
1537 }
1538
1539 // Field annotations follow immediately after the annotations directory.
1540 const DexFile::FieldAnnotationsItem* field_item =
1541 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1542 uint32_t field_count = item->fields_size_;
1543 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1544 return false;
1545 }
1546
1547 uint32_t last_idx = 0;
1548 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001549 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1550 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001551 return false;
1552 }
1553 last_idx = field_item->field_idx_;
1554 field_item++;
1555 }
1556
1557 // Method annotations follow immediately after field annotations.
1558 const DexFile::MethodAnnotationsItem* method_item =
1559 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1560 uint32_t method_count = item->methods_size_;
1561 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1562 return false;
1563 }
1564
1565 last_idx = 0;
1566 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001567 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1568 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1569 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001570 return false;
1571 }
1572 last_idx = method_item->method_idx_;
1573 method_item++;
1574 }
1575
1576 // Parameter annotations follow immediately after method annotations.
1577 const DexFile::ParameterAnnotationsItem* parameter_item =
1578 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1579 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001580 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001581 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001582 return false;
1583 }
1584
1585 last_idx = 0;
1586 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001587 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1588 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1589 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001590 return false;
1591 }
1592 last_idx = parameter_item->method_idx_;
1593 parameter_item++;
1594 }
1595
1596 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001597 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001598 return true;
1599}
1600
Andreas Gampeb061cc12014-09-02 10:22:20 -07001601bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
Orion Hodson12f4ff42017-01-13 16:43:12 +00001602 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -08001603 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001604 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001605 switch (type) {
1606 case DexFile::kDexTypeClassDataItem:
1607 case DexFile::kDexTypeStringDataItem:
1608 case DexFile::kDexTypeDebugInfoItem:
1609 case DexFile::kDexTypeAnnotationItem:
1610 case DexFile::kDexTypeEncodedArrayItem:
1611 alignment_mask = sizeof(uint8_t) - 1;
1612 break;
1613 default:
1614 alignment_mask = sizeof(uint32_t) - 1;
1615 break;
1616 }
1617
1618 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001619 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001620 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001621
1622 // Check the padding between items.
Mathieu Chartier24066ec2017-10-21 16:01:08 -07001623 if (!CheckPadding(offset, aligned_offset, type)) {
jeffhao10037c82012-01-23 15:06:23 -08001624 return false;
1625 }
1626
1627 // Check depending on the section type.
Orion Hodson12f4ff42017-01-13 16:43:12 +00001628 const uint8_t* start_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08001629 switch (type) {
1630 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001631 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001632 return false;
1633 }
1634 ptr_ += sizeof(DexFile::StringId);
1635 break;
1636 }
1637 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001638 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001639 return false;
1640 }
1641 ptr_ += sizeof(DexFile::TypeId);
1642 break;
1643 }
1644 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001645 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001646 return false;
1647 }
1648 ptr_ += sizeof(DexFile::ProtoId);
1649 break;
1650 }
1651 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001652 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001653 return false;
1654 }
1655 ptr_ += sizeof(DexFile::FieldId);
1656 break;
1657 }
1658 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001659 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001660 return false;
1661 }
1662 ptr_ += sizeof(DexFile::MethodId);
1663 break;
1664 }
1665 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001666 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001667 return false;
1668 }
1669 ptr_ += sizeof(DexFile::ClassDef);
1670 break;
1671 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00001672 case DexFile::kDexTypeCallSiteIdItem: {
1673 if (!CheckListSize(ptr_, 1, sizeof(DexFile::CallSiteIdItem), "call_site_ids")) {
1674 return false;
1675 }
1676 ptr_ += sizeof(DexFile::CallSiteIdItem);
1677 break;
1678 }
1679 case DexFile::kDexTypeMethodHandleItem: {
1680 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodHandleItem), "method_handles")) {
1681 return false;
1682 }
1683 ptr_ += sizeof(DexFile::MethodHandleItem);
1684 break;
1685 }
jeffhao10037c82012-01-23 15:06:23 -08001686 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001687 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001688 return false;
1689 }
jeffhao10037c82012-01-23 15:06:23 -08001690 break;
1691 }
1692 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001693 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001694 return false;
1695 }
jeffhao10037c82012-01-23 15:06:23 -08001696 break;
1697 }
1698 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001699 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001700 return false;
1701 }
jeffhao10037c82012-01-23 15:06:23 -08001702 break;
1703 }
1704 case DexFile::kDexTypeClassDataItem: {
1705 if (!CheckIntraClassDataItem()) {
1706 return false;
1707 }
1708 break;
1709 }
1710 case DexFile::kDexTypeCodeItem: {
1711 if (!CheckIntraCodeItem()) {
1712 return false;
1713 }
1714 break;
1715 }
1716 case DexFile::kDexTypeStringDataItem: {
1717 if (!CheckIntraStringDataItem()) {
1718 return false;
1719 }
1720 break;
1721 }
1722 case DexFile::kDexTypeDebugInfoItem: {
1723 if (!CheckIntraDebugInfoItem()) {
1724 return false;
1725 }
1726 break;
1727 }
1728 case DexFile::kDexTypeAnnotationItem: {
1729 if (!CheckIntraAnnotationItem()) {
1730 return false;
1731 }
1732 break;
1733 }
1734 case DexFile::kDexTypeEncodedArrayItem: {
1735 if (!CheckEncodedArray()) {
1736 return false;
1737 }
1738 break;
1739 }
1740 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1741 if (!CheckIntraAnnotationsDirectoryItem()) {
1742 return false;
1743 }
1744 break;
1745 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00001746 case DexFile::kDexTypeHeaderItem:
1747 case DexFile::kDexTypeMapList:
1748 break;
1749 }
1750
1751 if (start_ptr == ptr_) {
1752 ErrorStringPrintf("Unknown map item type %x", type);
1753 return false;
jeffhao10037c82012-01-23 15:06:23 -08001754 }
1755
1756 if (IsDataSectionType(type)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001757 if (aligned_offset == 0u) {
1758 ErrorStringPrintf("Item %d offset is 0", i);
1759 return false;
1760 }
1761 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1762 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001763 }
1764
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001765 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001766 if (UNLIKELY(aligned_offset > size_)) {
1767 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001768 return false;
1769 }
1770
1771 offset = aligned_offset;
1772 }
1773
1774 return true;
1775}
1776
Orion Hodson12f4ff42017-01-13 16:43:12 +00001777bool DexFileVerifier::CheckIntraIdSection(size_t offset,
1778 uint32_t count,
1779 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -08001780 uint32_t expected_offset;
1781 uint32_t expected_size;
1782
1783 // Get the expected offset and size from the header.
1784 switch (type) {
1785 case DexFile::kDexTypeStringIdItem:
1786 expected_offset = header_->string_ids_off_;
1787 expected_size = header_->string_ids_size_;
1788 break;
1789 case DexFile::kDexTypeTypeIdItem:
1790 expected_offset = header_->type_ids_off_;
1791 expected_size = header_->type_ids_size_;
1792 break;
1793 case DexFile::kDexTypeProtoIdItem:
1794 expected_offset = header_->proto_ids_off_;
1795 expected_size = header_->proto_ids_size_;
1796 break;
1797 case DexFile::kDexTypeFieldIdItem:
1798 expected_offset = header_->field_ids_off_;
1799 expected_size = header_->field_ids_size_;
1800 break;
1801 case DexFile::kDexTypeMethodIdItem:
1802 expected_offset = header_->method_ids_off_;
1803 expected_size = header_->method_ids_size_;
1804 break;
1805 case DexFile::kDexTypeClassDefItem:
1806 expected_offset = header_->class_defs_off_;
1807 expected_size = header_->class_defs_size_;
1808 break;
1809 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001810 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001811 return false;
1812 }
1813
1814 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001815 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001816 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001817 return false;
1818 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001819 if (UNLIKELY(count != expected_size)) {
1820 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001821 return false;
1822 }
1823
1824 return CheckIntraSectionIterate(offset, count, type);
1825}
1826
Orion Hodson12f4ff42017-01-13 16:43:12 +00001827bool DexFileVerifier::CheckIntraDataSection(size_t offset,
1828 uint32_t count,
1829 DexFile::MapItemType type) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001830 size_t data_start = header_->data_off_;
1831 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001832
1833 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001834 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001835 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001836 return false;
1837 }
1838
1839 if (!CheckIntraSectionIterate(offset, count, type)) {
1840 return false;
1841 }
1842
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001843 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001844 if (next_offset > data_end) {
Mathieu Chartier24066ec2017-10-21 16:01:08 -07001845 ErrorStringPrintf("Out-of-bounds end of data subsection: %zu data_off=%u data_size=%u",
1846 next_offset,
1847 header_->data_off_,
1848 header_->data_size_);
jeffhao10037c82012-01-23 15:06:23 -08001849 return false;
1850 }
1851
1852 return true;
1853}
1854
1855bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001856 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001857 const DexFile::MapItem* item = map->list_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001858 size_t offset = 0;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001859 uint32_t count = map->size_;
Ian Rogers30fab402012-01-23 15:43:46 -08001860 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001861
1862 // Check the items listed in the map.
1863 while (count--) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00001864 const size_t current_offset = offset;
jeffhao10037c82012-01-23 15:06:23 -08001865 uint32_t section_offset = item->offset_;
1866 uint32_t section_count = item->size_;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001867 DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
jeffhao10037c82012-01-23 15:06:23 -08001868
1869 // Check for padding and overlap between items.
Mathieu Chartier24066ec2017-10-21 16:01:08 -07001870 if (!CheckPadding(offset, section_offset, type)) {
jeffhao10037c82012-01-23 15:06:23 -08001871 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001872 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001873 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001874 return false;
1875 }
1876
1877 // Check each item based on its type.
1878 switch (type) {
1879 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001880 if (UNLIKELY(section_count != 1)) {
1881 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001882 return false;
1883 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001884 if (UNLIKELY(section_offset != 0)) {
1885 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001886 return false;
1887 }
Ian Rogers30fab402012-01-23 15:43:46 -08001888 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001889 offset = header_->header_size_;
1890 break;
1891 case DexFile::kDexTypeStringIdItem:
1892 case DexFile::kDexTypeTypeIdItem:
1893 case DexFile::kDexTypeProtoIdItem:
1894 case DexFile::kDexTypeFieldIdItem:
1895 case DexFile::kDexTypeMethodIdItem:
1896 case DexFile::kDexTypeClassDefItem:
1897 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1898 return false;
1899 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001900 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001901 break;
1902 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001903 if (UNLIKELY(section_count != 1)) {
1904 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001905 return false;
1906 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001907 if (UNLIKELY(section_offset != header_->map_off_)) {
1908 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1909 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001910 return false;
1911 }
1912 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1913 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1914 break;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001915 case DexFile::kDexTypeMethodHandleItem:
1916 case DexFile::kDexTypeCallSiteIdItem:
1917 CheckIntraSectionIterate(section_offset, section_count, type);
1918 offset = ptr_ - begin_;
1919 break;
jeffhao10037c82012-01-23 15:06:23 -08001920 case DexFile::kDexTypeTypeList:
1921 case DexFile::kDexTypeAnnotationSetRefList:
1922 case DexFile::kDexTypeAnnotationSetItem:
1923 case DexFile::kDexTypeClassDataItem:
1924 case DexFile::kDexTypeCodeItem:
1925 case DexFile::kDexTypeStringDataItem:
1926 case DexFile::kDexTypeDebugInfoItem:
1927 case DexFile::kDexTypeAnnotationItem:
1928 case DexFile::kDexTypeEncodedArrayItem:
1929 case DexFile::kDexTypeAnnotationsDirectoryItem:
1930 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1931 return false;
1932 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001933 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001934 break;
Orion Hodson12f4ff42017-01-13 16:43:12 +00001935 }
1936
1937 if (offset == current_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001938 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001939 return false;
1940 }
1941
1942 item++;
1943 }
1944
1945 return true;
1946}
1947
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001948bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001949 DCHECK_NE(offset, 0u);
1950 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001951 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001952 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001953 return false;
1954 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001955 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001956 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001957 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001958 return false;
1959 }
1960 return true;
1961}
1962
Andreas Gampea5b09a62016-11-17 15:21:22 -08001963dex::TypeIndex DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001964 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001965 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001966
1967 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001968 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001969 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001970 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001971 }
1972
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001973 if (it.HasNextMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001974 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001975 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001976 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001977 }
1978
Andreas Gampea5b09a62016-11-17 15:21:22 -08001979 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001980}
1981
Andreas Gampea5b09a62016-11-17 15:21:22 -08001982dex::TypeIndex DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr,
1983 bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001984 const DexFile::AnnotationsDirectoryItem* item =
1985 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001986 *success = true;
1987
jeffhao10037c82012-01-23 15:06:23 -08001988 if (item->fields_size_ != 0) {
1989 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001990 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001991 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001992 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001993 }
1994
1995 if (item->methods_size_ != 0) {
1996 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001997 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08001998 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07001999 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08002000 }
2001
2002 if (item->parameters_size_ != 0) {
2003 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07002004 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002005 *success = false; return dex::TypeIndex(DexFile::kDexNoIndex16))
Andreas Gampee09269c2014-06-06 18:45:35 -07002006 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08002007 }
2008
Andreas Gampea5b09a62016-11-17 15:21:22 -08002009 return dex::TypeIndex(DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08002010}
2011
2012bool DexFileVerifier::CheckInterStringIdItem() {
2013 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
2014
2015 // Check the map to make sure it has the right offset->type.
2016 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
2017 return false;
2018 }
2019
2020 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002021 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002022 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
2023 const char* prev_str = dex_file_->GetStringData(*prev_item);
2024 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002025 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
2026 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08002027 return false;
2028 }
2029 }
2030
2031 ptr_ += sizeof(DexFile::StringId);
2032 return true;
2033}
2034
2035bool DexFileVerifier::CheckInterTypeIdItem() {
2036 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07002037
2038 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08002039
2040 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002041 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
2042 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002043 return false;
2044 }
2045
2046 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002047 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002048 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002049 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
2050 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002051 prev_item->descriptor_idx_.index_,
2052 item->descriptor_idx_.index_);
jeffhao10037c82012-01-23 15:06:23 -08002053 return false;
2054 }
2055 }
2056
2057 ptr_ += sizeof(DexFile::TypeId);
2058 return true;
2059}
2060
2061bool DexFileVerifier::CheckInterProtoIdItem() {
2062 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07002063
2064 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
2065
jeffhao10037c82012-01-23 15:06:23 -08002066 if (item->parameters_off_ != 0 &&
2067 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
2068 return false;
2069 }
2070
David Sehr28e74ed2016-11-21 12:52:12 -08002071 // Check that return type is representable as a uint16_t;
2072 if (UNLIKELY(!IsValidOrNoTypeId(item->return_type_idx_.index_, item->pad_))) {
2073 ErrorStringPrintf("proto with return type idx outside uint16_t range '%x:%x'",
2074 item->pad_, item->return_type_idx_.index_);
2075 return false;
2076 }
jeffhao10037c82012-01-23 15:06:23 -08002077 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07002078 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
2079 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08002080 return false;
2081 }
2082 shorty++;
2083
2084 DexFileParameterIterator it(*dex_file_, *item);
2085 while (it.HasNext() && *shorty != '\0') {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002086 if (!CheckIndex(it.GetTypeIdx().index_,
2087 dex_file_->NumTypeIds(),
Andreas Gampebb836e12014-06-13 15:31:40 -07002088 "inter_proto_id_item shorty type_idx")) {
2089 return false;
2090 }
jeffhao10037c82012-01-23 15:06:23 -08002091 const char* descriptor = it.GetDescriptor();
2092 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
2093 return false;
2094 }
2095 it.Next();
2096 shorty++;
2097 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002098 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
2099 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08002100 return false;
2101 }
2102
2103 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002104 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002105 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002106 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
2107 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08002108 return false;
2109 } else if (prev->return_type_idx_ == item->return_type_idx_) {
2110 DexFileParameterIterator curr_it(*dex_file_, *item);
2111 DexFileParameterIterator prev_it(*dex_file_, *prev);
2112
2113 while (curr_it.HasNext() && prev_it.HasNext()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002114 dex::TypeIndex prev_idx = prev_it.GetTypeIdx();
2115 dex::TypeIndex curr_idx = curr_it.GetTypeIdx();
2116 DCHECK_NE(prev_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
2117 DCHECK_NE(curr_idx, dex::TypeIndex(DexFile::kDexNoIndex16));
jeffhao10037c82012-01-23 15:06:23 -08002118
2119 if (prev_idx < curr_idx) {
2120 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002121 } else if (UNLIKELY(prev_idx > curr_idx)) {
2122 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08002123 return false;
2124 }
2125
2126 prev_it.Next();
2127 curr_it.Next();
2128 }
Vladimir Marko0ca8add2016-05-03 17:17:50 +01002129 if (!curr_it.HasNext()) {
2130 // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
2131 // a ProtoId with a longer one. Both cases are forbidden by the specification.
2132 ErrorStringPrintf("Out-of-order proto_id arguments");
2133 return false;
2134 }
jeffhao10037c82012-01-23 15:06:23 -08002135 }
2136 }
2137
2138 ptr_ += sizeof(DexFile::ProtoId);
2139 return true;
2140}
2141
2142bool DexFileVerifier::CheckInterFieldIdItem() {
2143 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
2144
2145 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07002146 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
2147 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
2148 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002149 return false;
2150 }
2151
2152 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07002153 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
2154 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
2155 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002156 return false;
2157 }
2158
2159 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07002160 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002161 if (UNLIKELY(!IsValidMemberName(descriptor))) {
2162 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002163 return false;
2164 }
2165
2166 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002167 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002168 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002169 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
2170 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002171 return false;
2172 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002173 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
2174 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002175 return false;
2176 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002177 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
2178 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08002179 return false;
2180 }
2181 }
2182 }
2183 }
2184
2185 ptr_ += sizeof(DexFile::FieldId);
2186 return true;
2187}
2188
2189bool DexFileVerifier::CheckInterMethodIdItem() {
2190 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
2191
2192 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07002193 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
2194 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
2195 class_descriptor[0] != '['))) {
2196 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002197 return false;
2198 }
2199
2200 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07002201 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002202 if (UNLIKELY(!IsValidMemberName(descriptor))) {
2203 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002204 return false;
2205 }
2206
Andreas Gampedf10b322014-06-11 21:46:05 -07002207 // Check that the proto id is valid.
2208 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
2209 "inter_method_id_item proto_idx"))) {
2210 return false;
2211 }
2212
jeffhao10037c82012-01-23 15:06:23 -08002213 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002214 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002215 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002216 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
2217 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002218 return false;
2219 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002220 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
2221 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002222 return false;
2223 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002224 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
2225 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08002226 return false;
2227 }
2228 }
2229 }
2230 }
2231
2232 ptr_ += sizeof(DexFile::MethodId);
2233 return true;
2234}
2235
2236bool DexFileVerifier::CheckInterClassDefItem() {
2237 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08002238
David Sehr28e74ed2016-11-21 12:52:12 -08002239 // Check that class_idx_ is representable as a uint16_t;
2240 if (UNLIKELY(!IsValidTypeId(item->class_idx_.index_, item->pad1_))) {
2241 ErrorStringPrintf("class with type idx outside uint16_t range '%x:%x'", item->pad1_,
2242 item->class_idx_.index_);
2243 return false;
2244 }
2245 // Check that superclass_idx_ is representable as a uint16_t;
2246 if (UNLIKELY(!IsValidOrNoTypeId(item->superclass_idx_.index_, item->pad2_))) {
2247 ErrorStringPrintf("class with superclass type idx outside uint16_t range '%x:%x'", item->pad2_,
2248 item->superclass_idx_.index_);
2249 return false;
2250 }
Andreas Gampe0ba238d2014-07-29 01:22:07 -07002251 // Check for duplicate class def.
2252 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002253 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_.index_);
Andreas Gampe0ba238d2014-07-29 01:22:07 -07002254 return false;
2255 }
2256 defined_classes_.insert(item->class_idx_);
2257
Andreas Gampee09269c2014-06-06 18:45:35 -07002258 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
2259 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
2260 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002261 return false;
2262 }
2263
Andreas Gampeacc2bb62014-07-17 19:26:50 -07002264 // Only allow non-runtime modifiers.
2265 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
2266 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
2267 return false;
2268 }
2269
jeffhao10037c82012-01-23 15:06:23 -08002270 if (item->interfaces_off_ != 0 &&
2271 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
2272 return false;
2273 }
2274 if (item->annotations_off_ != 0 &&
2275 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
2276 return false;
2277 }
2278 if (item->class_data_off_ != 0 &&
2279 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
2280 return false;
2281 }
2282 if (item->static_values_off_ != 0 &&
2283 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
2284 return false;
2285 }
2286
Andreas Gampea5b09a62016-11-17 15:21:22 -08002287 if (item->superclass_idx_.IsValid()) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002288 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2289 // Check that a class does not inherit from itself directly (by having
2290 // the same type idx as its super class).
2291 if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002292 ErrorStringPrintf("Class with same type idx as its superclass: '%d'",
2293 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002294 return false;
2295 }
2296
2297 // Check that a class is defined after its super class (if the
2298 // latter is defined in the same Dex file).
2299 const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
2300 if (superclass_def != nullptr) {
2301 // The superclass is defined in this Dex file.
2302 if (superclass_def > item) {
2303 // ClassDef item for super class appearing after the class' ClassDef item.
2304 ErrorStringPrintf("Invalid class definition ordering:"
2305 " class with type idx: '%d' defined before"
2306 " superclass with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002307 item->class_idx_.index_,
2308 item->superclass_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002309 return false;
2310 }
2311 }
2312 }
2313
Andreas Gampee09269c2014-06-06 18:45:35 -07002314 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
2315 "inter_class_def_item superclass_idx")
2316 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
2317 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002318 return false;
2319 }
2320 }
2321
Roland Levillain621b5ea2016-05-18 11:41:33 +01002322 // Check interfaces.
jeffhao10037c82012-01-23 15:06:23 -08002323 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002324 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002325 uint32_t size = interfaces->Size();
jeffhao10037c82012-01-23 15:06:23 -08002326 for (uint32_t i = 0; i < size; i++) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002327 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2328 // Check that a class does not implement itself directly (by having the
2329 // same type idx as one of its immediate implemented interfaces).
2330 if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2331 ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002332 item->class_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002333 return false;
2334 }
2335
2336 // Check that a class is defined after the interfaces it implements
2337 // (if they are defined in the same Dex file).
2338 const DexFile::ClassDef* interface_def =
2339 dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2340 if (interface_def != nullptr) {
2341 // The interface is defined in this Dex file.
2342 if (interface_def > item) {
2343 // ClassDef item for interface appearing after the class' ClassDef item.
2344 ErrorStringPrintf("Invalid class definition ordering:"
2345 " class with type idx: '%d' defined before"
2346 " implemented interface with type idx: '%d'",
Andreas Gampea5b09a62016-11-17 15:21:22 -08002347 item->class_idx_.index_,
2348 interfaces->GetTypeItem(i).type_idx_.index_);
Roland Levillain621b5ea2016-05-18 11:41:33 +01002349 return false;
2350 }
2351 }
2352 }
2353
2354 // Ensure that the interface refers to a class (not an array nor a primitive type).
Andreas Gampee09269c2014-06-06 18:45:35 -07002355 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2356 "inter_class_def_item interface type_idx")
2357 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2358 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002359 return false;
2360 }
2361 }
2362
2363 /*
2364 * Ensure that there are no duplicates. This is an O(N^2) test, but in
2365 * practice the number of interfaces implemented by any given class is low.
2366 */
2367 for (uint32_t i = 1; i < size; i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002368 dex::TypeIndex idx1 = interfaces->GetTypeItem(i).type_idx_;
jeffhao10037c82012-01-23 15:06:23 -08002369 for (uint32_t j =0; j < i; j++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002370 dex::TypeIndex idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002371 if (UNLIKELY(idx1 == idx2)) {
2372 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08002373 return false;
2374 }
2375 }
2376 }
2377 }
2378
2379 // Check that references in class_data_item are to the right class.
2380 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07002381 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002382 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002383 dex::TypeIndex data_definer = FindFirstClassDataDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002384 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002385 return false;
2386 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08002387 if (UNLIKELY((data_definer != item->class_idx_) &&
2388 (data_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002389 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08002390 return false;
2391 }
2392 }
2393
2394 // Check that references in annotations_directory_item are to right class.
2395 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002396 // annotations_off_ is supposed to be aligned by 4.
2397 if (!IsAlignedParam(item->annotations_off_, 4)) {
2398 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2399 return false;
2400 }
Ian Rogers13735952014-10-08 12:43:28 -07002401 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002402 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002403 dex::TypeIndex annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002404 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002405 return false;
2406 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002407 if (UNLIKELY((annotations_definer != item->class_idx_) &&
Andreas Gampea5b09a62016-11-17 15:21:22 -08002408 (annotations_definer != dex::TypeIndex(DexFile::kDexNoIndex16)))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002409 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002410 return false;
2411 }
2412 }
2413
2414 ptr_ += sizeof(DexFile::ClassDef);
2415 return true;
2416}
2417
Orion Hodson12f4ff42017-01-13 16:43:12 +00002418bool DexFileVerifier::CheckInterCallSiteIdItem() {
2419 const DexFile::CallSiteIdItem* item = reinterpret_cast<const DexFile::CallSiteIdItem*>(ptr_);
2420
2421 // Check call site referenced by item is in encoded array section.
2422 if (!CheckOffsetToTypeMap(item->data_off_, DexFile::kDexTypeEncodedArrayItem)) {
2423 ErrorStringPrintf("Invalid offset in CallSideIdItem");
2424 return false;
2425 }
2426
2427 CallSiteArrayValueIterator it(*dex_file_, *item);
2428
2429 // Check Method Handle
2430 if (!it.HasNext() || it.GetValueType() != EncodedArrayValueIterator::ValueType::kMethodHandle) {
2431 ErrorStringPrintf("CallSiteArray missing method handle");
2432 return false;
2433 }
2434
2435 uint32_t handle_index = static_cast<uint32_t>(it.GetJavaValue().i);
2436 if (handle_index >= dex_file_->NumMethodHandles()) {
2437 ErrorStringPrintf("CallSite has bad method handle id: %x", handle_index);
2438 return false;
2439 }
2440
2441 // Check target method name.
2442 it.Next();
2443 if (!it.HasNext() ||
2444 it.GetValueType() != EncodedArrayValueIterator::ValueType::kString) {
2445 ErrorStringPrintf("CallSiteArray missing target method name");
2446 return false;
2447 }
2448
2449 uint32_t name_index = static_cast<uint32_t>(it.GetJavaValue().i);
2450 if (name_index >= dex_file_->NumStringIds()) {
2451 ErrorStringPrintf("CallSite has bad method name id: %x", name_index);
2452 return false;
2453 }
2454
2455 // Check method type.
2456 it.Next();
2457 if (!it.HasNext() ||
2458 it.GetValueType() != EncodedArrayValueIterator::ValueType::kMethodType) {
2459 ErrorStringPrintf("CallSiteArray missing method type");
2460 return false;
2461 }
2462
2463 uint32_t proto_index = static_cast<uint32_t>(it.GetJavaValue().i);
2464 if (proto_index >= dex_file_->NumProtoIds()) {
2465 ErrorStringPrintf("CallSite has bad method type: %x", proto_index);
2466 return false;
2467 }
2468
2469 ptr_ += sizeof(DexFile::CallSiteIdItem);
2470 return true;
2471}
2472
2473bool DexFileVerifier::CheckInterMethodHandleItem() {
2474 const DexFile::MethodHandleItem* item = reinterpret_cast<const DexFile::MethodHandleItem*>(ptr_);
2475
2476 DexFile::MethodHandleType method_handle_type =
2477 static_cast<DexFile::MethodHandleType>(item->method_handle_type_);
2478 if (method_handle_type > DexFile::MethodHandleType::kLast) {
2479 ErrorStringPrintf("Bad method handle type %x", item->method_handle_type_);
2480 return false;
2481 }
2482
2483 uint32_t index = item->field_or_method_idx_;
2484 switch (method_handle_type) {
Orion Hodsonc069a302017-01-18 09:23:12 +00002485 case DexFile::MethodHandleType::kStaticPut:
2486 case DexFile::MethodHandleType::kStaticGet:
2487 case DexFile::MethodHandleType::kInstancePut:
2488 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson12f4ff42017-01-13 16:43:12 +00002489 LOAD_FIELD(field, index, "method_handle_item field_idx", return false);
2490 break;
2491 }
2492 case DexFile::MethodHandleType::kInvokeStatic:
2493 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodson631827d2017-04-10 14:53:47 +01002494 case DexFile::MethodHandleType::kInvokeConstructor:
2495 case DexFile::MethodHandleType::kInvokeDirect:
2496 case DexFile::MethodHandleType::kInvokeInterface: {
Orion Hodson12f4ff42017-01-13 16:43:12 +00002497 LOAD_METHOD(method, index, "method_handle_item method_idx", return false);
2498 break;
2499 }
2500 }
2501
2502 ptr_ += sizeof(DexFile::MethodHandleItem);
2503 return true;
2504}
2505
jeffhao10037c82012-01-23 15:06:23 -08002506bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2507 const DexFile::AnnotationSetRefList* list =
2508 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2509 const DexFile::AnnotationSetRefItem* item = list->list_;
2510 uint32_t count = list->size_;
2511
2512 while (count--) {
2513 if (item->annotations_off_ != 0 &&
2514 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2515 return false;
2516 }
2517 item++;
2518 }
2519
Ian Rogers13735952014-10-08 12:43:28 -07002520 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002521 return true;
2522}
2523
2524bool DexFileVerifier::CheckInterAnnotationSetItem() {
2525 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2526 const uint32_t* offsets = set->entries_;
2527 uint32_t count = set->size_;
2528 uint32_t last_idx = 0;
2529
2530 for (uint32_t i = 0; i < count; i++) {
2531 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2532 return false;
2533 }
2534
2535 // Get the annotation from the offset and the type index for the annotation.
2536 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002537 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002538 const uint8_t* data = annotation->annotation_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002539 DECODE_UNSIGNED_CHECKED_FROM(data, idx);
jeffhao10037c82012-01-23 15:06:23 -08002540
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002541 if (UNLIKELY(last_idx >= idx && i != 0)) {
2542 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002543 return false;
2544 }
2545
2546 last_idx = idx;
2547 offsets++;
2548 }
2549
Ian Rogers13735952014-10-08 12:43:28 -07002550 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002551 return true;
2552}
2553
2554bool DexFileVerifier::CheckInterClassDataItem() {
2555 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002556 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002557 dex::TypeIndex defining_class = FindFirstClassDataDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002558 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002559 return false;
2560 }
jeffhao10037c82012-01-23 15:06:23 -08002561
2562 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002563 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002564 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002565 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002566 return false;
2567 }
2568 }
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08002569 for (; it.HasNextMethod(); it.Next()) {
jeffhao10037c82012-01-23 15:06:23 -08002570 uint32_t code_off = it.GetMethodCodeItemOffset();
2571 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2572 return false;
2573 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002574 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002575 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002576 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002577 return false;
2578 }
2579 }
2580
2581 ptr_ = it.EndDataPointer();
2582 return true;
2583}
2584
2585bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2586 const DexFile::AnnotationsDirectoryItem* item =
2587 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002588 bool success;
Andreas Gampea5b09a62016-11-17 15:21:22 -08002589 dex::TypeIndex defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002590 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002591 return false;
2592 }
jeffhao10037c82012-01-23 15:06:23 -08002593
2594 if (item->class_annotations_off_ != 0 &&
2595 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2596 return false;
2597 }
2598
2599 // Field annotations follow immediately after the annotations directory.
2600 const DexFile::FieldAnnotationsItem* field_item =
2601 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2602 uint32_t field_count = item->fields_size_;
2603 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002604 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2605 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002606 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002607 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002608 return false;
2609 }
2610 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2611 return false;
2612 }
2613 field_item++;
2614 }
2615
2616 // Method annotations follow immediately after field annotations.
2617 const DexFile::MethodAnnotationsItem* method_item =
2618 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2619 uint32_t method_count = item->methods_size_;
2620 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002621 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002622 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002623 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002624 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002625 return false;
2626 }
2627 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2628 return false;
2629 }
2630 method_item++;
2631 }
2632
2633 // Parameter annotations follow immediately after method annotations.
2634 const DexFile::ParameterAnnotationsItem* parameter_item =
2635 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2636 uint32_t parameter_count = item->parameters_size_;
2637 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002638 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002639 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002640 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002641 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002642 return false;
2643 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002644 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2645 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002646 return false;
2647 }
2648 parameter_item++;
2649 }
2650
Ian Rogers13735952014-10-08 12:43:28 -07002651 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002652 return true;
2653}
2654
Orion Hodson12f4ff42017-01-13 16:43:12 +00002655bool DexFileVerifier::CheckInterSectionIterate(size_t offset,
2656 uint32_t count,
2657 DexFile::MapItemType type) {
jeffhao10037c82012-01-23 15:06:23 -08002658 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002659 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002660 switch (type) {
2661 case DexFile::kDexTypeClassDataItem:
2662 alignment_mask = sizeof(uint8_t) - 1;
2663 break;
2664 default:
2665 alignment_mask = sizeof(uint32_t) - 1;
2666 break;
2667 }
2668
2669 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002670 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002671 for (uint32_t i = 0; i < count; i++) {
2672 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002673 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002674 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002675
Orion Hodson12f4ff42017-01-13 16:43:12 +00002676 if (MapTypeToBitMask(type) == 0) {
2677 ErrorStringPrintf("Unknown map item type %x", type);
2678 return false;
2679 }
2680
jeffhao10037c82012-01-23 15:06:23 -08002681 // Check depending on the section type.
2682 switch (type) {
Orion Hodson12f4ff42017-01-13 16:43:12 +00002683 case DexFile::kDexTypeHeaderItem:
2684 case DexFile::kDexTypeMapList:
2685 case DexFile::kDexTypeTypeList:
2686 case DexFile::kDexTypeCodeItem:
2687 case DexFile::kDexTypeStringDataItem:
2688 case DexFile::kDexTypeDebugInfoItem:
2689 case DexFile::kDexTypeAnnotationItem:
2690 case DexFile::kDexTypeEncodedArrayItem:
2691 break;
jeffhao10037c82012-01-23 15:06:23 -08002692 case DexFile::kDexTypeStringIdItem: {
2693 if (!CheckInterStringIdItem()) {
2694 return false;
2695 }
2696 break;
2697 }
2698 case DexFile::kDexTypeTypeIdItem: {
2699 if (!CheckInterTypeIdItem()) {
2700 return false;
2701 }
2702 break;
2703 }
2704 case DexFile::kDexTypeProtoIdItem: {
2705 if (!CheckInterProtoIdItem()) {
2706 return false;
2707 }
2708 break;
2709 }
2710 case DexFile::kDexTypeFieldIdItem: {
2711 if (!CheckInterFieldIdItem()) {
2712 return false;
2713 }
2714 break;
2715 }
2716 case DexFile::kDexTypeMethodIdItem: {
2717 if (!CheckInterMethodIdItem()) {
2718 return false;
2719 }
2720 break;
2721 }
2722 case DexFile::kDexTypeClassDefItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002723 // There shouldn't be more class definitions than type ids allow.
2724 // This check should be redundant, since there are checks that the
2725 // class_idx_ is within range and that there is only one definition
2726 // for a given type id.
2727 if (i > kTypeIdLimit) {
2728 ErrorStringPrintf("Too many class definition items");
2729 return false;
2730 }
jeffhao10037c82012-01-23 15:06:23 -08002731 if (!CheckInterClassDefItem()) {
2732 return false;
2733 }
2734 break;
2735 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00002736 case DexFile::kDexTypeCallSiteIdItem: {
2737 if (!CheckInterCallSiteIdItem()) {
2738 return false;
2739 }
2740 break;
2741 }
2742 case DexFile::kDexTypeMethodHandleItem: {
2743 if (!CheckInterMethodHandleItem()) {
2744 return false;
2745 }
2746 break;
2747 }
jeffhao10037c82012-01-23 15:06:23 -08002748 case DexFile::kDexTypeAnnotationSetRefList: {
2749 if (!CheckInterAnnotationSetRefList()) {
2750 return false;
2751 }
2752 break;
2753 }
2754 case DexFile::kDexTypeAnnotationSetItem: {
2755 if (!CheckInterAnnotationSetItem()) {
2756 return false;
2757 }
2758 break;
2759 }
2760 case DexFile::kDexTypeClassDataItem: {
David Sehr28e74ed2016-11-21 12:52:12 -08002761 // There shouldn't be more class data than type ids allow.
2762 // This check should be redundant, since there are checks that the
2763 // class_idx_ is within range and that there is only one definition
2764 // for a given type id.
2765 if (i > kTypeIdLimit) {
2766 ErrorStringPrintf("Too many class data items");
2767 return false;
2768 }
jeffhao10037c82012-01-23 15:06:23 -08002769 if (!CheckInterClassDataItem()) {
2770 return false;
2771 }
2772 break;
2773 }
2774 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2775 if (!CheckInterAnnotationsDirectoryItem()) {
2776 return false;
2777 }
2778 break;
2779 }
jeffhao10037c82012-01-23 15:06:23 -08002780 }
2781
2782 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002783 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002784 }
2785
2786 return true;
2787}
2788
2789bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002790 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002791 const DexFile::MapItem* item = map->list_;
2792 uint32_t count = map->size_;
2793
2794 // Cross check the items listed in the map.
2795 while (count--) {
2796 uint32_t section_offset = item->offset_;
2797 uint32_t section_count = item->size_;
Orion Hodson12f4ff42017-01-13 16:43:12 +00002798 DexFile::MapItemType type = static_cast<DexFile::MapItemType>(item->type_);
2799 bool found = false;
jeffhao10037c82012-01-23 15:06:23 -08002800
2801 switch (type) {
2802 case DexFile::kDexTypeHeaderItem:
2803 case DexFile::kDexTypeMapList:
2804 case DexFile::kDexTypeTypeList:
2805 case DexFile::kDexTypeCodeItem:
2806 case DexFile::kDexTypeStringDataItem:
2807 case DexFile::kDexTypeDebugInfoItem:
2808 case DexFile::kDexTypeAnnotationItem:
2809 case DexFile::kDexTypeEncodedArrayItem:
Orion Hodson12f4ff42017-01-13 16:43:12 +00002810 found = true;
jeffhao10037c82012-01-23 15:06:23 -08002811 break;
2812 case DexFile::kDexTypeStringIdItem:
2813 case DexFile::kDexTypeTypeIdItem:
2814 case DexFile::kDexTypeProtoIdItem:
2815 case DexFile::kDexTypeFieldIdItem:
2816 case DexFile::kDexTypeMethodIdItem:
2817 case DexFile::kDexTypeClassDefItem:
Orion Hodson12f4ff42017-01-13 16:43:12 +00002818 case DexFile::kDexTypeCallSiteIdItem:
2819 case DexFile::kDexTypeMethodHandleItem:
jeffhao10037c82012-01-23 15:06:23 -08002820 case DexFile::kDexTypeAnnotationSetRefList:
2821 case DexFile::kDexTypeAnnotationSetItem:
2822 case DexFile::kDexTypeClassDataItem:
2823 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2824 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2825 return false;
2826 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00002827 found = true;
jeffhao10037c82012-01-23 15:06:23 -08002828 break;
2829 }
Orion Hodson12f4ff42017-01-13 16:43:12 +00002830 }
2831
2832 if (!found) {
2833 ErrorStringPrintf("Unknown map item type %x", item->type_);
2834 return false;
jeffhao10037c82012-01-23 15:06:23 -08002835 }
2836
2837 item++;
2838 }
2839
2840 return true;
2841}
2842
2843bool DexFileVerifier::Verify() {
2844 // Check the header.
2845 if (!CheckHeader()) {
2846 return false;
2847 }
2848
2849 // Check the map section.
2850 if (!CheckMap()) {
2851 return false;
2852 }
2853
2854 // Check structure within remaining sections.
2855 if (!CheckIntraSection()) {
2856 return false;
2857 }
2858
2859 // Check references from one section to another.
2860 if (!CheckInterSection()) {
2861 return false;
2862 }
2863
2864 return true;
2865}
2866
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002867void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2868 va_list ap;
2869 va_start(ap, fmt);
2870 DCHECK(failure_reason_.empty()) << failure_reason_;
2871 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2872 StringAppendV(&failure_reason_, fmt, ap);
2873 va_end(ap);
2874}
2875
Andreas Gampee6215c02015-08-31 18:54:38 -07002876// Fields and methods may have only one of public/protected/private.
2877static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2878 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2879 (((flags & kAccProtected) == 0) ? 0 : 1) +
2880 (((flags & kAccPrivate) == 0) ? 0 : 1);
2881 return count <= 1;
2882}
2883
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002884// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2885// functionality, as we're still verifying the dex file. begin and header correspond to the
2886// underscored variants in the DexFileVerifier.
2887
2888static std::string GetStringOrError(const uint8_t* const begin,
2889 const DexFile::Header* const header,
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002890 dex::StringIndex string_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002891 // The `string_idx` is not guaranteed to be valid yet.
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002892 if (header->string_ids_size_ <= string_idx.index_) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002893 return "(error)";
2894 }
2895
2896 const DexFile::StringId* string_id =
Andreas Gampe8a0128a2016-11-28 07:38:35 -08002897 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_)
2898 + string_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002899
2900 // Assume that the data is OK at this point. String data has been checked at this point.
2901
2902 const uint8_t* ptr = begin + string_id->string_data_off_;
Andreas Gampebed6daf2016-09-02 18:12:00 -07002903 uint32_t dummy;
2904 if (!DecodeUnsignedLeb128Checked(&ptr, begin + header->file_size_, &dummy)) {
2905 return "(error)";
2906 }
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002907 return reinterpret_cast<const char*>(ptr);
2908}
2909
2910static std::string GetClassOrError(const uint8_t* const begin,
2911 const DexFile::Header* const header,
Andreas Gampea5b09a62016-11-17 15:21:22 -08002912 dex::TypeIndex class_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002913 // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2914 // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2915 // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2916 // a valid defining class.
Andreas Gampea5b09a62016-11-17 15:21:22 -08002917 CHECK_LT(class_idx.index_, header->type_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002918
2919 const DexFile::TypeId* type_id =
Andreas Gampea5b09a62016-11-17 15:21:22 -08002920 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx.index_;
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002921
2922 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2923
2924 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2925}
2926
2927static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2928 const DexFile::Header* const header,
2929 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002930 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2931 CHECK_LT(idx, header->field_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002932
2933 const DexFile::FieldId* field_id =
2934 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2935
2936 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2937
2938 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2939 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2940
2941 return class_name + "." + field_name;
2942}
2943
2944static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2945 const DexFile::Header* const header,
2946 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002947 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2948 CHECK_LT(idx, header->method_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002949
2950 const DexFile::MethodId* method_id =
2951 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2952
2953 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2954
2955 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2956 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2957
2958 return class_name + "." + method_name;
2959}
2960
2961bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2962 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002963 uint32_t class_access_flags,
2964 std::string* error_msg) {
2965 // Generally sort out >16-bit flags.
2966 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002967 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2968 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2969 field_access_flags,
2970 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002971 return false;
2972 }
2973
2974 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2975 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2976 kAccPrivate |
2977 kAccProtected |
2978 kAccStatic |
2979 kAccFinal |
2980 kAccVolatile |
2981 kAccTransient |
2982 kAccSynthetic |
2983 kAccEnum;
2984
2985 // Fields may have only one of public/protected/final.
2986 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002987 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2988 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2989 field_access_flags,
2990 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002991 return false;
2992 }
2993
2994 // Interfaces have a pretty restricted list.
2995 if ((class_access_flags & kAccInterface) != 0) {
2996 // Interface fields must be public final static.
2997 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2998 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002999 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
3000 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
3001 field_access_flags,
3002 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07003003 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07003004 return false;
3005 } else {
3006 // Allow in older versions, but warn.
3007 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3008 << *error_msg;
3009 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003010 }
3011 // Interface fields may be synthetic, but may not have other flags.
3012 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
3013 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003014 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
3015 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
3016 field_access_flags,
3017 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07003018 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07003019 return false;
3020 } else {
3021 // Allow in older versions, but warn.
3022 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3023 << *error_msg;
3024 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003025 }
3026 return true;
3027 }
3028
3029 // Volatile fields may not be final.
3030 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
3031 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003032 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
3033 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003034 return false;
3035 }
3036
3037 return true;
3038}
3039
Andreas Gampee6215c02015-08-31 18:54:38 -07003040bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
3041 uint32_t method_access_flags,
3042 uint32_t class_access_flags,
Orion Hodson6c4921b2016-09-21 15:41:06 +01003043 uint32_t constructor_flags_by_name,
Andreas Gampee6215c02015-08-31 18:54:38 -07003044 bool has_code,
3045 bool expect_direct,
3046 std::string* error_msg) {
3047 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
3048 constexpr uint32_t kAllMethodFlags =
3049 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
3050 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003051 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
3052 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3053 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07003054 return false;
3055 }
3056
3057 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
3058 constexpr uint32_t kMethodAccessFlags = kAccPublic |
3059 kAccPrivate |
3060 kAccProtected |
3061 kAccStatic |
3062 kAccFinal |
3063 kAccSynthetic |
3064 kAccSynchronized |
3065 kAccBridge |
3066 kAccVarargs |
3067 kAccNative |
3068 kAccAbstract |
3069 kAccStrict;
3070
3071 // Methods may have only one of public/protected/final.
3072 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003073 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
3074 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07003075 method_access_flags);
3076 return false;
3077 }
3078
Orion Hodson6c4921b2016-09-21 15:41:06 +01003079 constexpr uint32_t kConstructorFlags = kAccStatic | kAccConstructor;
3080 const bool is_constructor_by_name = (constructor_flags_by_name & kConstructorFlags) != 0;
3081 const bool is_clinit_by_name = constructor_flags_by_name == kConstructorFlags;
Andreas Gampee6215c02015-08-31 18:54:38 -07003082
3083 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
3084 // the reverse for backwards compatibility reasons.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003085 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003086 *error_msg =
3087 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
Orion Hodson6c4921b2016-09-21 15:41:06 +01003088 method_index,
3089 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003090 return false;
3091 }
Orion Hodson6c4921b2016-09-21 15:41:06 +01003092
3093 if (is_constructor_by_name) {
3094 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
3095 // instance constructor is called "<init>".
Andreas Gampee6215c02015-08-31 18:54:38 -07003096 bool is_static = (method_access_flags & kAccStatic) != 0;
3097 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003098 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
3099 method_index,
3100 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07003101 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3102 return false;
3103 } else {
3104 // Allow in older versions, but warn.
3105 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3106 << *error_msg;
3107 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003108 }
3109 }
Orion Hodson6c4921b2016-09-21 15:41:06 +01003110
Andreas Gampee6215c02015-08-31 18:54:38 -07003111 // Check that static and private methods, as well as constructors, are in the direct methods list,
3112 // and other methods in the virtual methods list.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003113 bool is_direct = ((method_access_flags & (kAccStatic | kAccPrivate)) != 0) ||
3114 is_constructor_by_name;
Andreas Gampee6215c02015-08-31 18:54:38 -07003115 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003116 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07003117 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003118 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07003119 expect_direct);
3120 return false;
3121 }
3122
Andreas Gampee6215c02015-08-31 18:54:38 -07003123 // From here on out it is easier to mask out the bits we're supposed to ignore.
3124 method_access_flags &= kMethodAccessFlags;
3125
Alex Lightd7c10c22016-03-31 10:03:07 -07003126 // Interfaces are special.
3127 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07003128 // Non-static interface methods must be public or private.
3129 uint32_t desired_flags = (kAccPublic | kAccStatic);
3130 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3131 desired_flags |= kAccPrivate;
3132 }
3133 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07003134 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
3135 method_index,
3136 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07003137 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07003138 return false;
3139 } else {
3140 // Allow in older versions, but warn.
3141 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3142 << *error_msg;
3143 }
3144 }
3145 }
3146
Andreas Gampee6215c02015-08-31 18:54:38 -07003147 // If there aren't any instructions, make sure that's expected.
3148 if (!has_code) {
3149 // Only native or abstract methods may not have code.
3150 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003151 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07003152 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003153 method_index,
3154 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003155 return false;
3156 }
3157 // Constructors must always have code.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003158 if (is_constructor_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003159 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
3160 method_index,
3161 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07003162 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
3163 return false;
3164 } else {
3165 // Allow in older versions, but warn.
3166 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3167 << *error_msg;
3168 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003169 }
3170 if ((method_access_flags & kAccAbstract) != 0) {
3171 // Abstract methods are not allowed to have the following flags.
3172 constexpr uint32_t kForbidden =
3173 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
3174 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003175 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
3176 method_index,
3177 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
3178 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07003179 return false;
3180 }
Andreas Gampe97b11352015-12-10 16:23:41 -08003181 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07003182 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003183 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08003184 << " is abstract, but the declaring class is neither abstract nor an "
3185 << "interface in dex file "
3186 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07003187 }
3188 }
3189 // Interfaces are special.
3190 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07003191 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07003192 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003193 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
3194 method_index,
3195 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07003196 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07003197 return false;
3198 } else {
3199 // Allow in older versions, but warn.
3200 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
3201 << *error_msg;
3202 }
Andreas Gampee6215c02015-08-31 18:54:38 -07003203 }
3204 // At this point, we know the method is public and abstract. This means that all the checks
3205 // for invalid combinations above applies. In addition, interface methods must not be
3206 // protected. This is caught by the check for only-one-of-public-protected-private.
3207 }
3208 return true;
3209 }
3210
3211 // When there's code, the method must not be native or abstract.
3212 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003213 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
3214 method_index,
3215 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07003216 return false;
3217 }
3218
Andreas Gampee6215c02015-08-31 18:54:38 -07003219 // Instance constructors must not be synchronized and a few other flags.
Orion Hodson6c4921b2016-09-21 15:41:06 +01003220 if (constructor_flags_by_name == kAccConstructor) {
Andreas Gampee6215c02015-08-31 18:54:38 -07003221 static constexpr uint32_t kInitAllowed =
3222 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
3223 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003224 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07003225 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08003226 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07003227 method_access_flags);
3228 return false;
3229 }
3230 }
3231
3232 return true;
3233}
3234
Orion Hodson6c4921b2016-09-21 15:41:06 +01003235bool DexFileVerifier::CheckConstructorProperties(
3236 uint32_t method_index,
3237 uint32_t constructor_flags) {
3238 DCHECK(constructor_flags == kAccConstructor ||
3239 constructor_flags == (kAccConstructor | kAccStatic));
3240
3241 // Check signature matches expectations.
3242 const DexFile::MethodId* const method_id = CheckLoadMethodId(method_index,
3243 "Bad <init>/<clinit> method id");
3244 if (method_id == nullptr) {
3245 return false;
3246 }
3247
3248 // Check the ProtoId for the corresponding method.
3249 //
3250 // TODO(oth): the error message here is to satisfy the MethodId test
3251 // in the DexFileVerifierTest. The test is checking that the error
3252 // contains this string if the index is out of range.
3253 const DexFile::ProtoId* const proto_id = CheckLoadProtoId(method_id->proto_idx_,
3254 "inter_method_id_item proto_idx");
3255 if (proto_id == nullptr) {
3256 return false;
3257 }
3258
3259 Signature signature = dex_file_->GetMethodSignature(*method_id);
3260 if (constructor_flags == (kAccStatic | kAccConstructor)) {
3261 if (!signature.IsVoid() || signature.GetNumberOfParameters() != 0) {
3262 ErrorStringPrintf("<clinit> must have descriptor ()V");
3263 return false;
3264 }
3265 } else if (!signature.IsVoid()) {
3266 ErrorStringPrintf("Constructor %u(%s) must be void",
3267 method_index,
3268 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
3269 return false;
3270 }
3271
3272 return true;
3273}
3274
jeffhao10037c82012-01-23 15:06:23 -08003275} // namespace art