blob: 5132efc03cd44aefdfa51df5fe01445ef03bb028 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
jeffhao10037c82012-01-23 15:06:23 -080016
17#include "dex_file_verifier.h"
18
Andreas Gampee6215c02015-08-31 18:54:38 -070019#include <inttypes.h>
Narayan Kamath92572be2013-11-28 14:06:24 +000020#include <zlib.h>
Andreas Gampee6215c02015-08-31 18:54:38 -070021
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Narayan Kamath92572be2013-11-28 14:06:24 +000023
Elliott Hughese222ee02012-12-13 14:41:43 -080024#include "base/stringprintf.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070025#include "dex_file-inl.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070026#include "experimental_flags.h"
jeffhao10037c82012-01-23 15:06:23 -080027#include "leb128.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070028#include "runtime.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070029#include "safe_map.h"
Ian Rogersa6724902013-09-23 09:23:37 -070030#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "utils.h"
jeffhao10037c82012-01-23 15:06:23 -080032
33namespace art {
34
35static uint32_t MapTypeToBitMask(uint32_t map_type) {
36 switch (map_type) {
37 case DexFile::kDexTypeHeaderItem: return 1 << 0;
38 case DexFile::kDexTypeStringIdItem: return 1 << 1;
39 case DexFile::kDexTypeTypeIdItem: return 1 << 2;
40 case DexFile::kDexTypeProtoIdItem: return 1 << 3;
41 case DexFile::kDexTypeFieldIdItem: return 1 << 4;
42 case DexFile::kDexTypeMethodIdItem: return 1 << 5;
43 case DexFile::kDexTypeClassDefItem: return 1 << 6;
44 case DexFile::kDexTypeMapList: return 1 << 7;
45 case DexFile::kDexTypeTypeList: return 1 << 8;
46 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9;
47 case DexFile::kDexTypeAnnotationSetItem: return 1 << 10;
48 case DexFile::kDexTypeClassDataItem: return 1 << 11;
49 case DexFile::kDexTypeCodeItem: return 1 << 12;
50 case DexFile::kDexTypeStringDataItem: return 1 << 13;
51 case DexFile::kDexTypeDebugInfoItem: return 1 << 14;
52 case DexFile::kDexTypeAnnotationItem: return 1 << 15;
53 case DexFile::kDexTypeEncodedArrayItem: return 1 << 16;
54 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17;
55 }
56 return 0;
57}
58
59static bool IsDataSectionType(uint32_t map_type) {
60 switch (map_type) {
61 case DexFile::kDexTypeHeaderItem:
62 case DexFile::kDexTypeStringIdItem:
63 case DexFile::kDexTypeTypeIdItem:
64 case DexFile::kDexTypeProtoIdItem:
65 case DexFile::kDexTypeFieldIdItem:
66 case DexFile::kDexTypeMethodIdItem:
67 case DexFile::kDexTypeClassDefItem:
68 return false;
69 }
70 return true;
71}
72
Andreas Gampee09269c2014-06-06 18:45:35 -070073const char* DexFileVerifier::CheckLoadStringByIdx(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070074 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070075 return nullptr;
76 }
77 return dex_file_->StringDataByIdx(idx);
78}
79
80const char* DexFileVerifier::CheckLoadStringByTypeIdx(uint32_t type_idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070081 if (UNLIKELY(!CheckIndex(type_idx, dex_file_->NumTypeIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070082 return nullptr;
83 }
84 const DexFile::TypeId& type_id = dex_file_->GetTypeId(type_idx);
85 uint32_t idx = type_id.descriptor_idx_;
86 return CheckLoadStringByIdx(idx, error_string);
87}
88
89const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070090 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070091 return nullptr;
92 }
93 return &dex_file_->GetFieldId(idx);
94}
95
96const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070097 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070098 return nullptr;
99 }
100 return &dex_file_->GetMethodId(idx);
101}
102
103// Helper macro to load string and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700104#define LOAD_STRING(var, idx, error) \
105 const char* (var) = CheckLoadStringByIdx(idx, error); \
106 if (UNLIKELY((var) == nullptr)) { \
107 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700108 }
109
110// Helper macro to load string by type idx and return false on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700111#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
112 const char* (var) = CheckLoadStringByTypeIdx(type_idx, error); \
113 if (UNLIKELY((var) == nullptr)) { \
114 return false; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700115 }
116
117// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700118#define LOAD_METHOD(var, idx, error_string, error_stmt) \
119 const DexFile::MethodId* (var) = CheckLoadMethodId(idx, error_string); \
120 if (UNLIKELY((var) == nullptr)) { \
121 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700122 }
123
124// Helper macro to load method id. Return last parameter on error.
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -0700125#define LOAD_FIELD(var, idx, fmt, error_stmt) \
126 const DexFile::FieldId* (var) = CheckLoadFieldId(idx, fmt); \
127 if (UNLIKELY((var) == nullptr)) { \
128 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700129 }
130
Aart Bik37d6a3b2016-06-21 18:30:10 -0700131bool DexFileVerifier::Verify(const DexFile* dex_file,
132 const uint8_t* begin,
133 size_t size,
134 const char* location,
135 bool verify_checksum,
136 std::string* error_msg) {
137 std::unique_ptr<DexFileVerifier> verifier(
138 new DexFileVerifier(dex_file, begin, size, location, verify_checksum));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700139 if (!verifier->Verify()) {
140 *error_msg = verifier->FailureReason();
141 return false;
142 }
143 return true;
144}
145
146bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
147 bool is_return_type) {
jeffhao10037c82012-01-23 15:06:23 -0800148 switch (shorty_char) {
149 case 'V':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700150 if (UNLIKELY(!is_return_type)) {
151 ErrorStringPrintf("Invalid use of void");
jeffhao10037c82012-01-23 15:06:23 -0800152 return false;
153 }
Ian Rogersfc787ec2014-10-09 21:56:44 -0700154 FALLTHROUGH_INTENDED;
jeffhao10037c82012-01-23 15:06:23 -0800155 case 'B':
156 case 'C':
157 case 'D':
158 case 'F':
159 case 'I':
160 case 'J':
161 case 'S':
162 case 'Z':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700163 if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
164 ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
165 shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800166 return false;
167 }
168 break;
169 case 'L':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700170 if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
171 ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800172 return false;
173 }
174 break;
175 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700176 ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
jeffhao10037c82012-01-23 15:06:23 -0800177 return false;
178 }
179 return true;
180}
181
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700182bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700183 const char* label) {
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700184 // Check that size is not 0.
185 CHECK_NE(elem_size, 0U);
186
Ian Rogers13735952014-10-08 12:43:28 -0700187 const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
188 const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700189
190 // Check for overflow.
191 uintptr_t max = 0 - 1;
192 size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
193 size_t max_count = available_bytes_till_end_of_mem / elem_size;
194 if (max_count < count) {
195 ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
196 static_cast<size_t>(range_start - file_start),
197 count, elem_size);
198 return false;
199 }
200
Ian Rogers13735952014-10-08 12:43:28 -0700201 const uint8_t* range_end = range_start + count * elem_size;
202 const uint8_t* file_end = file_start + size_;
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700203 if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
204 // Note: these two tests are enough as we make sure above that there's no overflow.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800205 ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
Ian Rogerse3d55812014-06-11 13:00:44 -0700206 static_cast<size_t>(range_start - file_start),
207 static_cast<size_t>(range_end - file_start));
jeffhao10037c82012-01-23 15:06:23 -0800208 return false;
209 }
210 return true;
211}
212
Ian Rogers13735952014-10-08 12:43:28 -0700213bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700214 // Check that the list is available. The first 4B are the count.
215 if (!CheckListSize(*ptr, 1, 4U, label)) {
216 return false;
217 }
218
219 uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
220 if (count > 0) {
221 if (!CheckListSize(*ptr + 4, count, element_size, label)) {
222 return false;
223 }
224 }
225
226 *ptr += 4 + count * element_size;
227 return true;
228}
229
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700230bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
231 if (UNLIKELY(field >= limit)) {
232 ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
jeffhao10037c82012-01-23 15:06:23 -0800233 return false;
234 }
235 return true;
236}
237
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800238bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
239 uint32_t size,
240 size_t alignment,
241 const char* label) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700242 if (size == 0) {
243 if (offset != 0) {
244 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
245 return false;
246 }
247 }
248 if (size_ <= offset) {
249 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
250 return false;
251 }
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800252 if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
253 ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
254 return false;
255 }
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700256 return true;
257}
258
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100259bool DexFileVerifier::CheckSizeLimit(uint32_t size, uint32_t limit, const char* label) {
260 if (size > limit) {
261 ErrorStringPrintf("Size(%u) should not exceed limit(%u) for %s.", size, limit, label);
262 return false;
263 }
264 return true;
265}
266
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700267bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800268 // Check file size from the header.
269 uint32_t expected_size = header_->file_size_;
270 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700271 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800272 return false;
273 }
274
275 // Compute and verify the checksum in the header.
276 uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
277 const uint32_t non_sum = sizeof(header_->magic_) + sizeof(header_->checksum_);
Ian Rogers13735952014-10-08 12:43:28 -0700278 const uint8_t* non_sum_ptr = reinterpret_cast<const uint8_t*>(header_) + non_sum;
jeffhaof6174e82012-01-31 16:14:17 -0800279 adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
jeffhao10037c82012-01-23 15:06:23 -0800280 if (adler_checksum != header_->checksum_) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700281 if (verify_checksum_) {
282 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
283 return false;
284 } else {
285 LOG(WARNING) << StringPrintf(
286 "Ignoring bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
287 }
jeffhao10037c82012-01-23 15:06:23 -0800288 }
289
290 // Check the contents of the header.
291 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700292 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800293 return false;
294 }
295
296 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700297 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800298 return false;
299 }
300
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700301 // Check that all offsets are inside the file.
302 bool result =
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800303 CheckValidOffsetAndSize(header_->link_off_,
304 header_->link_size_,
305 0 /* unaligned */,
306 "link") &&
307 CheckValidOffsetAndSize(header_->map_off_,
308 header_->map_off_,
309 4,
310 "map") &&
311 CheckValidOffsetAndSize(header_->string_ids_off_,
312 header_->string_ids_size_,
313 4,
314 "string-ids") &&
315 CheckValidOffsetAndSize(header_->type_ids_off_,
316 header_->type_ids_size_,
317 4,
318 "type-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100319 CheckSizeLimit(header_->type_ids_size_, DexFile::kDexNoIndex16, "type-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800320 CheckValidOffsetAndSize(header_->proto_ids_off_,
321 header_->proto_ids_size_,
322 4,
323 "proto-ids") &&
Vladimir Marko0ca8add2016-05-03 17:17:50 +0100324 CheckSizeLimit(header_->proto_ids_size_, DexFile::kDexNoIndex16, "proto-ids") &&
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800325 CheckValidOffsetAndSize(header_->field_ids_off_,
326 header_->field_ids_size_,
327 4,
328 "field-ids") &&
329 CheckValidOffsetAndSize(header_->method_ids_off_,
330 header_->method_ids_size_,
331 4,
332 "method-ids") &&
333 CheckValidOffsetAndSize(header_->class_defs_off_,
334 header_->class_defs_size_,
335 4,
336 "class-defs") &&
337 CheckValidOffsetAndSize(header_->data_off_,
338 header_->data_size_,
339 0, // Unaligned, spec doesn't talk about it, even though size
340 // is supposed to be a multiple of 4.
341 "data");
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700342 return result;
jeffhao10037c82012-01-23 15:06:23 -0800343}
344
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700345bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700346 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
347 header_->map_off_);
348 // Check that map list content is available.
349 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
350 return false;
351 }
352
jeffhao10037c82012-01-23 15:06:23 -0800353 const DexFile::MapItem* item = map->list_;
354
355 uint32_t count = map->size_;
356 uint32_t last_offset = 0;
357 uint32_t data_item_count = 0;
358 uint32_t data_items_left = header_->data_size_;
359 uint32_t used_bits = 0;
360
361 // Sanity check the size of the map list.
362 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
363 return false;
364 }
365
366 // Check the items listed in the map.
367 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700368 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
369 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800370 return false;
371 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700372 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
373 ErrorStringPrintf("Map item after end of file: %x, size %x",
374 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800375 return false;
376 }
377
378 if (IsDataSectionType(item->type_)) {
379 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700380 if (UNLIKELY(icount > data_items_left)) {
381 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800382 return false;
383 }
384 data_items_left -= icount;
385 data_item_count += icount;
386 }
387
388 uint32_t bit = MapTypeToBitMask(item->type_);
389
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700390 if (UNLIKELY(bit == 0)) {
391 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800392 return false;
393 }
394
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700395 if (UNLIKELY((used_bits & bit) != 0)) {
396 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800397 return false;
398 }
399
400 used_bits |= bit;
401 last_offset = item->offset_;
402 item++;
403 }
404
405 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700406 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
407 ErrorStringPrintf("Map is missing header entry");
jeffhao10037c82012-01-23 15:06:23 -0800408 return false;
409 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700410 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
411 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800412 return false;
413 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700414 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
415 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
416 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800417 return false;
418 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700419 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
420 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
421 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800422 return false;
423 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700424 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
425 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
426 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800427 return false;
428 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700429 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
430 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
431 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800432 return false;
433 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700434 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
435 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
436 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800437 return false;
438 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700439 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
440 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
441 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800442 return false;
443 }
jeffhao10037c82012-01-23 15:06:23 -0800444 return true;
445}
446
447uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
448 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700449 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700450 for (uint32_t i = 0; i < size; i++) {
451 result |= ((uint32_t) *(ptr_++)) << (i * 8);
452 }
jeffhao10037c82012-01-23 15:06:23 -0800453 }
jeffhao10037c82012-01-23 15:06:23 -0800454 return result;
455}
456
457bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700458 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700459 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800460
461 for (uint32_t i = 0; i < handlers_size; i++) {
462 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800463 size_t offset = ptr_ - handlers_base;
jeffhao10037c82012-01-23 15:06:23 -0800464 int32_t size = DecodeSignedLeb128(&ptr_);
465
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700466 if (UNLIKELY((size < -65536) || (size > 65536))) {
467 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800468 return false;
469 }
470
471 if (size <= 0) {
472 catch_all = true;
473 size = -size;
474 } else {
475 catch_all = false;
476 }
477
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800478 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800479
480 while (size-- > 0) {
481 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
482 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
483 return false;
484 }
485
486 uint32_t addr = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700487 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
488 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800489 return false;
490 }
491 }
492
493 if (catch_all) {
494 uint32_t addr = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700495 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
496 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800497 return false;
498 }
499 }
500 }
501
502 return true;
503}
504
Andreas Gampee6215c02015-08-31 18:54:38 -0700505bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
506 uint32_t access_flags,
507 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700508 uint16_t class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700509 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700510 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800511 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
512 return false;
513 }
514
Andreas Gampee6215c02015-08-31 18:54:38 -0700515 // Check that it's the right class.
516 uint16_t my_class_index =
517 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
518 class_idx_;
519 if (class_type_index != my_class_index) {
520 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
521 my_class_index,
522 class_type_index);
523 return false;
524 }
525
526 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800527 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700528 if (UNLIKELY(is_static != expect_static)) {
529 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800530 return false;
531 }
532
Andreas Gampee6215c02015-08-31 18:54:38 -0700533 // Check field access flags.
534 std::string error_msg;
Andreas Gampec9f0ba12016-02-09 09:21:04 -0800535 if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700536 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800537 return false;
538 }
539
540 return true;
541}
542
Andreas Gampee6215c02015-08-31 18:54:38 -0700543bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
544 uint32_t access_flags,
545 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700546 uint16_t class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700547 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700548 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700549 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700550 DCHECK(direct_method_indexes != nullptr);
551 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800552 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
553 return false;
554 }
555
Andreas Gampee6215c02015-08-31 18:54:38 -0700556 // Check that it's the right class.
557 uint16_t my_class_index =
558 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
559 class_idx_;
560 if (class_type_index != my_class_index) {
561 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 "vs %" PRIu16,
562 my_class_index,
563 class_type_index);
jeffhao10037c82012-01-23 15:06:23 -0800564 return false;
565 }
566
Andreas Gampee6215c02015-08-31 18:54:38 -0700567 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700568 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700569 direct_method_indexes->insert(idx);
570 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700571 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
572 return false;
573 }
574
Andreas Gampee6215c02015-08-31 18:54:38 -0700575 // Check method access flags.
576 bool has_code = (code_offset != 0);
577 std::string error_msg;
578 if (!CheckMethodAccessFlags(idx,
579 access_flags,
580 class_access_flags,
581 has_code,
582 expect_direct,
583 &error_msg)) {
584 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800585 return false;
586 }
587
588 return true;
589}
590
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800591bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800592 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700593 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800594 return false;
595 }
596 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700597 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800598 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800599 return false;
600 }
601 ptr_++;
602 offset++;
603 }
604 }
605 return true;
606}
607
608bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700609 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800610 return false;
611 }
612
613 uint8_t header_byte = *(ptr_++);
614 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
615 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
616
617 switch (value_type) {
618 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700619 if (UNLIKELY(value_arg != 0)) {
620 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800621 return false;
622 }
623 ptr_++;
624 break;
625 case DexFile::kDexAnnotationShort:
626 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700627 if (UNLIKELY(value_arg > 1)) {
628 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800629 return false;
630 }
631 ptr_ += value_arg + 1;
632 break;
633 case DexFile::kDexAnnotationInt:
634 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700635 if (UNLIKELY(value_arg > 3)) {
636 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800637 return false;
638 }
639 ptr_ += value_arg + 1;
640 break;
641 case DexFile::kDexAnnotationLong:
642 case DexFile::kDexAnnotationDouble:
643 ptr_ += value_arg + 1;
644 break;
645 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700646 if (UNLIKELY(value_arg > 3)) {
647 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800648 return false;
649 }
650 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
651 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
652 return false;
653 }
654 break;
655 }
656 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700657 if (UNLIKELY(value_arg > 3)) {
658 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800659 return false;
660 }
661 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
662 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
663 return false;
664 }
665 break;
666 }
667 case DexFile::kDexAnnotationField:
668 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700669 if (UNLIKELY(value_arg > 3)) {
670 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800671 return false;
672 }
673 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
674 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
675 return false;
676 }
677 break;
678 }
679 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700680 if (UNLIKELY(value_arg > 3)) {
681 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800682 return false;
683 }
684 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
685 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
686 return false;
687 }
688 break;
689 }
690 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700691 if (UNLIKELY(value_arg != 0)) {
692 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800693 return false;
694 }
695 if (!CheckEncodedArray()) {
696 return false;
697 }
698 break;
699 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700700 if (UNLIKELY(value_arg != 0)) {
701 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800702 return false;
703 }
704 if (!CheckEncodedAnnotation()) {
705 return false;
706 }
707 break;
708 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700709 if (UNLIKELY(value_arg != 0)) {
710 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800711 return false;
712 }
713 break;
714 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700715 if (UNLIKELY(value_arg > 1)) {
716 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800717 return false;
718 }
719 break;
720 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700721 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800722 return false;
723 }
724
725 return true;
726}
727
728bool DexFileVerifier::CheckEncodedArray() {
729 uint32_t size = DecodeUnsignedLeb128(&ptr_);
730
731 while (size--) {
732 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700733 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800734 return false;
735 }
736 }
737 return true;
738}
739
740bool DexFileVerifier::CheckEncodedAnnotation() {
741 uint32_t idx = DecodeUnsignedLeb128(&ptr_);
742 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
743 return false;
744 }
745
746 uint32_t size = DecodeUnsignedLeb128(&ptr_);
747 uint32_t last_idx = 0;
748
749 for (uint32_t i = 0; i < size; i++) {
750 idx = DecodeUnsignedLeb128(&ptr_);
751 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
752 return false;
753 }
754
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700755 if (UNLIKELY(last_idx >= idx && i != 0)) {
756 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
757 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800758 return false;
759 }
760
761 if (!CheckEncodedValue()) {
762 return false;
763 }
764
765 last_idx = idx;
766 }
767 return true;
768}
769
Andreas Gampee6215c02015-08-31 18:54:38 -0700770bool DexFileVerifier::FindClassFlags(uint32_t index,
771 bool is_field,
772 uint16_t* class_type_index,
773 uint32_t* class_access_flags) {
774 DCHECK(class_type_index != nullptr);
775 DCHECK(class_access_flags != nullptr);
776
777 // First check if the index is valid.
778 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
779 return false;
780 }
781
782 // Next get the type index.
783 if (is_field) {
784 *class_type_index =
785 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
786 class_idx_;
787 } else {
788 *class_type_index =
789 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
790 class_idx_;
791 }
792
793 // Check if that is valid.
794 if (*class_type_index >= header_->type_ids_size_) {
795 return false;
796 }
797
798 // Now search for the class def. This is basically a specialized version of the DexFile code, as
799 // we should not trust that this is a valid DexFile just yet.
800 const DexFile::ClassDef* class_def_begin =
801 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
802 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
803 const DexFile::ClassDef* class_def = class_def_begin + i;
804 if (class_def->class_idx_ == *class_type_index) {
805 *class_access_flags = class_def->access_flags_;
806 return true;
807 }
808 }
809
810 // Didn't find the class-def, not defined here...
811 return false;
812}
813
814bool DexFileVerifier::CheckOrderAndGetClassFlags(bool is_field,
815 const char* type_descr,
816 uint32_t curr_index,
817 uint32_t prev_index,
818 bool* have_class,
819 uint16_t* class_type_index,
820 uint32_t* class_access_flags) {
821 if (curr_index < prev_index) {
822 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
823 type_descr,
824 prev_index,
825 curr_index);
826 return false;
827 }
828
829 if (!*have_class) {
830 *have_class = FindClassFlags(curr_index, is_field, class_type_index, class_access_flags);
831 if (!*have_class) {
832 // Should have really found one.
833 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
834 type_descr,
835 curr_index);
836 return false;
837 }
838 }
839 return true;
840}
841
842template <bool kStatic>
843bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
844 bool* have_class,
845 uint16_t* class_type_index,
846 uint32_t* class_access_flags) {
847 DCHECK(it != nullptr);
848 // These calls use the raw access flags to check whether the whole dex field is valid.
849 uint32_t prev_index = 0;
850 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
851 uint32_t curr_index = it->GetMemberIndex();
852 if (!CheckOrderAndGetClassFlags(true,
853 kStatic ? "static field" : "instance field",
854 curr_index,
855 prev_index,
856 have_class,
857 class_type_index,
858 class_access_flags)) {
859 return false;
860 }
861 prev_index = curr_index;
862
863 if (!CheckClassDataItemField(curr_index,
864 it->GetRawMemberAccessFlags(),
865 *class_access_flags,
866 *class_type_index,
867 kStatic)) {
868 return false;
869 }
870 }
871
872 return true;
873}
874
875template <bool kDirect>
876bool DexFileVerifier::CheckIntraClassDataItemMethods(
877 ClassDataItemIterator* it,
878 std::unordered_set<uint32_t>* direct_method_indexes,
879 bool* have_class,
880 uint16_t* class_type_index,
881 uint32_t* class_access_flags) {
882 uint32_t prev_index = 0;
883 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
884 uint32_t curr_index = it->GetMemberIndex();
885 if (!CheckOrderAndGetClassFlags(false,
886 kDirect ? "direct method" : "virtual method",
887 curr_index,
888 prev_index,
889 have_class,
890 class_type_index,
891 class_access_flags)) {
892 return false;
893 }
894 prev_index = curr_index;
895
896 if (!CheckClassDataItemMethod(curr_index,
897 it->GetRawMemberAccessFlags(),
898 *class_access_flags,
899 *class_type_index,
900 it->GetMethodCodeItemOffset(),
901 direct_method_indexes,
902 kDirect)) {
903 return false;
904 }
905 }
906
907 return true;
908}
909
jeffhao10037c82012-01-23 15:06:23 -0800910bool DexFileVerifier::CheckIntraClassDataItem() {
911 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -0700912 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -0800913
Andreas Gampee6215c02015-08-31 18:54:38 -0700914 // This code is complicated by the fact that we don't directly know which class this belongs to.
915 // So we need to explicitly search with the first item we find (either field or method), and then,
916 // as the lookup is expensive, cache the result.
917 bool have_class = false;
918 uint16_t class_type_index;
919 uint32_t class_access_flags;
920
921 // Check fields.
922 if (!CheckIntraClassDataItemFields<true>(&it,
923 &have_class,
924 &class_type_index,
925 &class_access_flags)) {
926 return false;
jeffhao10037c82012-01-23 15:06:23 -0800927 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700928 if (!CheckIntraClassDataItemFields<false>(&it,
929 &have_class,
930 &class_type_index,
931 &class_access_flags)) {
932 return false;
jeffhao10037c82012-01-23 15:06:23 -0800933 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700934
935 // Check methods.
936 if (!CheckIntraClassDataItemMethods<true>(&it,
937 &direct_method_indexes,
938 &have_class,
939 &class_type_index,
940 &class_access_flags)) {
941 return false;
jeffhao10037c82012-01-23 15:06:23 -0800942 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700943 if (!CheckIntraClassDataItemMethods<false>(&it,
944 &direct_method_indexes,
945 &have_class,
946 &class_type_index,
947 &class_access_flags)) {
948 return false;
jeffhao10037c82012-01-23 15:06:23 -0800949 }
950
951 ptr_ = it.EndDataPointer();
952 return true;
953}
954
955bool DexFileVerifier::CheckIntraCodeItem() {
956 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700957 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -0800958 return false;
959 }
960
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700961 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
962 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
963 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800964 return false;
965 }
966
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700967 if (UNLIKELY((code_item->outs_size_ > 5) &&
968 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -0800969 /*
970 * outs_size can be up to 5, even if registers_size is smaller, since the
971 * short forms of method invocation allow repetitions of a register multiple
972 * times within a single parameter list. However, longer parameter lists
973 * need to be represented in-order in the register file.
974 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700975 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
976 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800977 return false;
978 }
979
980 const uint16_t* insns = code_item->insns_;
981 uint32_t insns_size = code_item->insns_size_in_code_units_;
982 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
983 return false;
984 }
985
986 // Grab the end of the insns if there are no try_items.
987 uint32_t try_items_size = code_item->tries_size_;
988 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -0700989 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -0800990 return true;
991 }
992
993 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800994 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700995 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -0800996 return false;
997 }
998
999 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -08001000 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
1001 return false;
1002 }
1003
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -05001004 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
1005 uint32_t handlers_size = DecodeUnsignedLeb128(&ptr_);
1006
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001007 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
1008 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -08001009 return false;
1010 }
1011
Ian Rogers700a4022014-05-19 16:49:03 -07001012 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -07001013 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -08001014 return false;
1015 }
1016
1017 uint32_t last_addr = 0;
1018 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001019 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1020 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001021 return false;
1022 }
1023
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001024 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1025 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001026 return false;
1027 }
1028
1029 uint32_t i;
1030 for (i = 0; i < handlers_size; i++) {
1031 if (try_items->handler_off_ == handler_offsets[i]) {
1032 break;
1033 }
1034 }
1035
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001036 if (UNLIKELY(i == handlers_size)) {
1037 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -08001038 return false;
1039 }
1040
1041 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001042 if (UNLIKELY(last_addr > insns_size)) {
1043 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -08001044 return false;
1045 }
1046
1047 try_items++;
1048 }
1049
1050 return true;
1051}
1052
1053bool DexFileVerifier::CheckIntraStringDataItem() {
1054 uint32_t size = DecodeUnsignedLeb128(&ptr_);
Ian Rogers13735952014-10-08 12:43:28 -07001055 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001056
1057 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001058 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001059 if (UNLIKELY(ptr_ >= file_end)) {
1060 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001061 return false;
1062 }
1063
1064 uint8_t byte = *(ptr_++);
1065
1066 // Switch on the high 4 bits.
1067 switch (byte >> 4) {
1068 case 0x00:
1069 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001070 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001071 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001072 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001073 return false;
1074 }
1075 break;
1076 case 0x01:
1077 case 0x02:
1078 case 0x03:
1079 case 0x04:
1080 case 0x05:
1081 case 0x06:
1082 case 0x07:
1083 // No extra checks necessary for bit pattern 0xxx.
1084 break;
1085 case 0x08:
1086 case 0x09:
1087 case 0x0a:
1088 case 0x0b:
1089 case 0x0f:
1090 // Illegal bit patterns 10xx or 1111.
1091 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001092 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001093 return false;
1094 case 0x0c:
1095 case 0x0d: {
1096 // Bit pattern 110x has an additional byte.
1097 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001098 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1099 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001100 return false;
1101 }
1102 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001103 if (UNLIKELY((value != 0) && (value < 0x80))) {
1104 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001105 return false;
1106 }
1107 break;
1108 }
1109 case 0x0e: {
1110 // Bit pattern 1110 has 2 additional bytes.
1111 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001112 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1113 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001114 return false;
1115 }
1116 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001117 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1118 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001119 return false;
1120 }
1121 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001122 if (UNLIKELY(value < 0x800)) {
1123 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001124 return false;
1125 }
1126 break;
1127 }
1128 }
1129 }
1130
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001131 if (UNLIKELY(*(ptr_++) != '\0')) {
1132 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001133 return false;
1134 }
1135
1136 return true;
1137}
1138
1139bool DexFileVerifier::CheckIntraDebugInfoItem() {
1140 DecodeUnsignedLeb128(&ptr_);
1141 uint32_t parameters_size = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001142 if (UNLIKELY(parameters_size > 65536)) {
1143 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001144 return false;
1145 }
1146
1147 for (uint32_t j = 0; j < parameters_size; j++) {
1148 uint32_t parameter_name = DecodeUnsignedLeb128(&ptr_);
1149 if (parameter_name != 0) {
1150 parameter_name--;
1151 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1152 return false;
1153 }
1154 }
1155 }
1156
1157 while (true) {
1158 uint8_t opcode = *(ptr_++);
1159 switch (opcode) {
1160 case DexFile::DBG_END_SEQUENCE: {
1161 return true;
1162 }
1163 case DexFile::DBG_ADVANCE_PC: {
1164 DecodeUnsignedLeb128(&ptr_);
1165 break;
1166 }
1167 case DexFile::DBG_ADVANCE_LINE: {
1168 DecodeSignedLeb128(&ptr_);
1169 break;
1170 }
1171 case DexFile::DBG_START_LOCAL: {
1172 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001173 if (UNLIKELY(reg_num >= 65536)) {
1174 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001175 return false;
1176 }
1177 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1178 if (name_idx != 0) {
1179 name_idx--;
1180 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1181 return false;
1182 }
1183 }
1184 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
1185 if (type_idx != 0) {
1186 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001187 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001188 return false;
1189 }
1190 }
1191 break;
1192 }
1193 case DexFile::DBG_END_LOCAL:
1194 case DexFile::DBG_RESTART_LOCAL: {
1195 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001196 if (UNLIKELY(reg_num >= 65536)) {
1197 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001198 return false;
1199 }
1200 break;
1201 }
1202 case DexFile::DBG_START_LOCAL_EXTENDED: {
1203 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001204 if (UNLIKELY(reg_num >= 65536)) {
1205 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001206 return false;
1207 }
1208 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1209 if (name_idx != 0) {
1210 name_idx--;
1211 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1212 return false;
1213 }
1214 }
1215 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
1216 if (type_idx != 0) {
1217 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001218 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001219 return false;
1220 }
1221 }
1222 uint32_t sig_idx = DecodeUnsignedLeb128(&ptr_);
1223 if (sig_idx != 0) {
1224 sig_idx--;
1225 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1226 return false;
1227 }
1228 }
1229 break;
1230 }
1231 case DexFile::DBG_SET_FILE: {
1232 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1233 if (name_idx != 0) {
1234 name_idx--;
1235 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1236 return false;
1237 }
1238 }
1239 break;
1240 }
1241 }
1242 }
1243}
1244
1245bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001246 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001247 return false;
1248 }
1249
1250 // Check visibility
1251 switch (*(ptr_++)) {
1252 case DexFile::kDexVisibilityBuild:
1253 case DexFile::kDexVisibilityRuntime:
1254 case DexFile::kDexVisibilitySystem:
1255 break;
1256 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001257 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001258 return false;
1259 }
1260
1261 if (!CheckEncodedAnnotation()) {
1262 return false;
1263 }
1264
1265 return true;
1266}
1267
1268bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1269 const DexFile::AnnotationsDirectoryItem* item =
1270 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001271 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001272 return false;
1273 }
1274
1275 // Field annotations follow immediately after the annotations directory.
1276 const DexFile::FieldAnnotationsItem* field_item =
1277 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1278 uint32_t field_count = item->fields_size_;
1279 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1280 return false;
1281 }
1282
1283 uint32_t last_idx = 0;
1284 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001285 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1286 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001287 return false;
1288 }
1289 last_idx = field_item->field_idx_;
1290 field_item++;
1291 }
1292
1293 // Method annotations follow immediately after field annotations.
1294 const DexFile::MethodAnnotationsItem* method_item =
1295 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1296 uint32_t method_count = item->methods_size_;
1297 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1298 return false;
1299 }
1300
1301 last_idx = 0;
1302 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001303 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1304 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1305 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001306 return false;
1307 }
1308 last_idx = method_item->method_idx_;
1309 method_item++;
1310 }
1311
1312 // Parameter annotations follow immediately after method annotations.
1313 const DexFile::ParameterAnnotationsItem* parameter_item =
1314 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1315 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001316 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001317 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001318 return false;
1319 }
1320
1321 last_idx = 0;
1322 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001323 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1324 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1325 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001326 return false;
1327 }
1328 last_idx = parameter_item->method_idx_;
1329 parameter_item++;
1330 }
1331
1332 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001333 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001334 return true;
1335}
1336
Andreas Gampeb061cc12014-09-02 10:22:20 -07001337bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
1338 uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001339 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001340 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001341 switch (type) {
1342 case DexFile::kDexTypeClassDataItem:
1343 case DexFile::kDexTypeStringDataItem:
1344 case DexFile::kDexTypeDebugInfoItem:
1345 case DexFile::kDexTypeAnnotationItem:
1346 case DexFile::kDexTypeEncodedArrayItem:
1347 alignment_mask = sizeof(uint8_t) - 1;
1348 break;
1349 default:
1350 alignment_mask = sizeof(uint32_t) - 1;
1351 break;
1352 }
1353
1354 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001355 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001356 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001357
1358 // Check the padding between items.
1359 if (!CheckPadding(offset, aligned_offset)) {
1360 return false;
1361 }
1362
1363 // Check depending on the section type.
1364 switch (type) {
1365 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001366 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001367 return false;
1368 }
1369 ptr_ += sizeof(DexFile::StringId);
1370 break;
1371 }
1372 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001373 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001374 return false;
1375 }
1376 ptr_ += sizeof(DexFile::TypeId);
1377 break;
1378 }
1379 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001380 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001381 return false;
1382 }
1383 ptr_ += sizeof(DexFile::ProtoId);
1384 break;
1385 }
1386 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001387 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001388 return false;
1389 }
1390 ptr_ += sizeof(DexFile::FieldId);
1391 break;
1392 }
1393 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001394 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001395 return false;
1396 }
1397 ptr_ += sizeof(DexFile::MethodId);
1398 break;
1399 }
1400 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001401 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001402 return false;
1403 }
1404 ptr_ += sizeof(DexFile::ClassDef);
1405 break;
1406 }
1407 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001408 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001409 return false;
1410 }
jeffhao10037c82012-01-23 15:06:23 -08001411 break;
1412 }
1413 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001414 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001415 return false;
1416 }
jeffhao10037c82012-01-23 15:06:23 -08001417 break;
1418 }
1419 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001420 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001421 return false;
1422 }
jeffhao10037c82012-01-23 15:06:23 -08001423 break;
1424 }
1425 case DexFile::kDexTypeClassDataItem: {
1426 if (!CheckIntraClassDataItem()) {
1427 return false;
1428 }
1429 break;
1430 }
1431 case DexFile::kDexTypeCodeItem: {
1432 if (!CheckIntraCodeItem()) {
1433 return false;
1434 }
1435 break;
1436 }
1437 case DexFile::kDexTypeStringDataItem: {
1438 if (!CheckIntraStringDataItem()) {
1439 return false;
1440 }
1441 break;
1442 }
1443 case DexFile::kDexTypeDebugInfoItem: {
1444 if (!CheckIntraDebugInfoItem()) {
1445 return false;
1446 }
1447 break;
1448 }
1449 case DexFile::kDexTypeAnnotationItem: {
1450 if (!CheckIntraAnnotationItem()) {
1451 return false;
1452 }
1453 break;
1454 }
1455 case DexFile::kDexTypeEncodedArrayItem: {
1456 if (!CheckEncodedArray()) {
1457 return false;
1458 }
1459 break;
1460 }
1461 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1462 if (!CheckIntraAnnotationsDirectoryItem()) {
1463 return false;
1464 }
1465 break;
1466 }
1467 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001468 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001469 return false;
1470 }
1471
1472 if (IsDataSectionType(type)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001473 if (aligned_offset == 0u) {
1474 ErrorStringPrintf("Item %d offset is 0", i);
1475 return false;
1476 }
1477 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1478 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001479 }
1480
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001481 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001482 if (UNLIKELY(aligned_offset > size_)) {
1483 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001484 return false;
1485 }
1486
1487 offset = aligned_offset;
1488 }
1489
1490 return true;
1491}
1492
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001493bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001494 uint32_t expected_offset;
1495 uint32_t expected_size;
1496
1497 // Get the expected offset and size from the header.
1498 switch (type) {
1499 case DexFile::kDexTypeStringIdItem:
1500 expected_offset = header_->string_ids_off_;
1501 expected_size = header_->string_ids_size_;
1502 break;
1503 case DexFile::kDexTypeTypeIdItem:
1504 expected_offset = header_->type_ids_off_;
1505 expected_size = header_->type_ids_size_;
1506 break;
1507 case DexFile::kDexTypeProtoIdItem:
1508 expected_offset = header_->proto_ids_off_;
1509 expected_size = header_->proto_ids_size_;
1510 break;
1511 case DexFile::kDexTypeFieldIdItem:
1512 expected_offset = header_->field_ids_off_;
1513 expected_size = header_->field_ids_size_;
1514 break;
1515 case DexFile::kDexTypeMethodIdItem:
1516 expected_offset = header_->method_ids_off_;
1517 expected_size = header_->method_ids_size_;
1518 break;
1519 case DexFile::kDexTypeClassDefItem:
1520 expected_offset = header_->class_defs_off_;
1521 expected_size = header_->class_defs_size_;
1522 break;
1523 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001524 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001525 return false;
1526 }
1527
1528 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001529 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001530 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001531 return false;
1532 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001533 if (UNLIKELY(count != expected_size)) {
1534 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001535 return false;
1536 }
1537
1538 return CheckIntraSectionIterate(offset, count, type);
1539}
1540
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001541bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count, uint16_t type) {
1542 size_t data_start = header_->data_off_;
1543 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001544
1545 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001546 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001547 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001548 return false;
1549 }
1550
1551 if (!CheckIntraSectionIterate(offset, count, type)) {
1552 return false;
1553 }
1554
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001555 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001556 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001557 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001558 return false;
1559 }
1560
1561 return true;
1562}
1563
1564bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001565 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001566 const DexFile::MapItem* item = map->list_;
1567
1568 uint32_t count = map->size_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001569 size_t offset = 0;
Ian Rogers30fab402012-01-23 15:43:46 -08001570 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001571
1572 // Check the items listed in the map.
1573 while (count--) {
1574 uint32_t section_offset = item->offset_;
1575 uint32_t section_count = item->size_;
1576 uint16_t type = item->type_;
1577
1578 // Check for padding and overlap between items.
1579 if (!CheckPadding(offset, section_offset)) {
1580 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001581 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001582 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001583 return false;
1584 }
1585
1586 // Check each item based on its type.
1587 switch (type) {
1588 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001589 if (UNLIKELY(section_count != 1)) {
1590 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001591 return false;
1592 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001593 if (UNLIKELY(section_offset != 0)) {
1594 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001595 return false;
1596 }
Ian Rogers30fab402012-01-23 15:43:46 -08001597 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001598 offset = header_->header_size_;
1599 break;
1600 case DexFile::kDexTypeStringIdItem:
1601 case DexFile::kDexTypeTypeIdItem:
1602 case DexFile::kDexTypeProtoIdItem:
1603 case DexFile::kDexTypeFieldIdItem:
1604 case DexFile::kDexTypeMethodIdItem:
1605 case DexFile::kDexTypeClassDefItem:
1606 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1607 return false;
1608 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001609 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001610 break;
1611 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001612 if (UNLIKELY(section_count != 1)) {
1613 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001614 return false;
1615 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001616 if (UNLIKELY(section_offset != header_->map_off_)) {
1617 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1618 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001619 return false;
1620 }
1621 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1622 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1623 break;
1624 case DexFile::kDexTypeTypeList:
1625 case DexFile::kDexTypeAnnotationSetRefList:
1626 case DexFile::kDexTypeAnnotationSetItem:
1627 case DexFile::kDexTypeClassDataItem:
1628 case DexFile::kDexTypeCodeItem:
1629 case DexFile::kDexTypeStringDataItem:
1630 case DexFile::kDexTypeDebugInfoItem:
1631 case DexFile::kDexTypeAnnotationItem:
1632 case DexFile::kDexTypeEncodedArrayItem:
1633 case DexFile::kDexTypeAnnotationsDirectoryItem:
1634 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1635 return false;
1636 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001637 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001638 break;
1639 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001640 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001641 return false;
1642 }
1643
1644 item++;
1645 }
1646
1647 return true;
1648}
1649
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001650bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001651 DCHECK_NE(offset, 0u);
1652 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001653 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001654 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001655 return false;
1656 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001657 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001658 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001659 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001660 return false;
1661 }
1662 return true;
1663}
1664
Ian Rogers13735952014-10-08 12:43:28 -07001665uint16_t DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001666 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001667 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001668
1669 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001670 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
1671 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001672 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001673 }
1674
1675 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001676 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
1677 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001678 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001679 }
1680
1681 return DexFile::kDexNoIndex16;
1682}
1683
Ian Rogers13735952014-10-08 12:43:28 -07001684uint16_t DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001685 const DexFile::AnnotationsDirectoryItem* item =
1686 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001687 *success = true;
1688
jeffhao10037c82012-01-23 15:06:23 -08001689 if (item->fields_size_ != 0) {
1690 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001691 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
1692 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001693 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001694 }
1695
1696 if (item->methods_size_ != 0) {
1697 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001698 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001699 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001700 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001701 }
1702
1703 if (item->parameters_size_ != 0) {
1704 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001705 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001706 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001707 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001708 }
1709
1710 return DexFile::kDexNoIndex16;
1711}
1712
1713bool DexFileVerifier::CheckInterStringIdItem() {
1714 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1715
1716 // Check the map to make sure it has the right offset->type.
1717 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1718 return false;
1719 }
1720
1721 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001722 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001723 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1724 const char* prev_str = dex_file_->GetStringData(*prev_item);
1725 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001726 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1727 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001728 return false;
1729 }
1730 }
1731
1732 ptr_ += sizeof(DexFile::StringId);
1733 return true;
1734}
1735
1736bool DexFileVerifier::CheckInterTypeIdItem() {
1737 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001738
1739 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001740
1741 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001742 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1743 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001744 return false;
1745 }
1746
1747 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001748 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001749 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001750 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1751 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
1752 prev_item->descriptor_idx_, item->descriptor_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001753 return false;
1754 }
1755 }
1756
1757 ptr_ += sizeof(DexFile::TypeId);
1758 return true;
1759}
1760
1761bool DexFileVerifier::CheckInterProtoIdItem() {
1762 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001763
1764 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1765
jeffhao10037c82012-01-23 15:06:23 -08001766 if (item->parameters_off_ != 0 &&
1767 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1768 return false;
1769 }
1770
1771 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001772 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1773 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001774 return false;
1775 }
1776 shorty++;
1777
1778 DexFileParameterIterator it(*dex_file_, *item);
1779 while (it.HasNext() && *shorty != '\0') {
Andreas Gampebb836e12014-06-13 15:31:40 -07001780 if (!CheckIndex(it.GetTypeIdx(), dex_file_->NumTypeIds(),
1781 "inter_proto_id_item shorty type_idx")) {
1782 return false;
1783 }
jeffhao10037c82012-01-23 15:06:23 -08001784 const char* descriptor = it.GetDescriptor();
1785 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1786 return false;
1787 }
1788 it.Next();
1789 shorty++;
1790 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001791 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1792 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001793 return false;
1794 }
1795
1796 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001797 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001798 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001799 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1800 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001801 return false;
1802 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1803 DexFileParameterIterator curr_it(*dex_file_, *item);
1804 DexFileParameterIterator prev_it(*dex_file_, *prev);
1805
1806 while (curr_it.HasNext() && prev_it.HasNext()) {
1807 uint16_t prev_idx = prev_it.GetTypeIdx();
1808 uint16_t curr_idx = curr_it.GetTypeIdx();
Vladimir Marko0ca8add2016-05-03 17:17:50 +01001809 DCHECK_NE(prev_idx, DexFile::kDexNoIndex16);
1810 DCHECK_NE(curr_idx, DexFile::kDexNoIndex16);
jeffhao10037c82012-01-23 15:06:23 -08001811
1812 if (prev_idx < curr_idx) {
1813 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001814 } else if (UNLIKELY(prev_idx > curr_idx)) {
1815 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001816 return false;
1817 }
1818
1819 prev_it.Next();
1820 curr_it.Next();
1821 }
Vladimir Marko0ca8add2016-05-03 17:17:50 +01001822 if (!curr_it.HasNext()) {
1823 // Either a duplicate ProtoId or a ProtoId with a shorter argument list follows
1824 // a ProtoId with a longer one. Both cases are forbidden by the specification.
1825 ErrorStringPrintf("Out-of-order proto_id arguments");
1826 return false;
1827 }
jeffhao10037c82012-01-23 15:06:23 -08001828 }
1829 }
1830
1831 ptr_ += sizeof(DexFile::ProtoId);
1832 return true;
1833}
1834
1835bool DexFileVerifier::CheckInterFieldIdItem() {
1836 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1837
1838 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001839 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1840 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1841 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001842 return false;
1843 }
1844
1845 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001846 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1847 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1848 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001849 return false;
1850 }
1851
1852 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001853 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001854 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1855 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001856 return false;
1857 }
1858
1859 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001860 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001861 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001862 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1863 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001864 return false;
1865 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001866 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1867 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001868 return false;
1869 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001870 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
1871 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001872 return false;
1873 }
1874 }
1875 }
1876 }
1877
1878 ptr_ += sizeof(DexFile::FieldId);
1879 return true;
1880}
1881
1882bool DexFileVerifier::CheckInterMethodIdItem() {
1883 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
1884
1885 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001886 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
1887 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
1888 class_descriptor[0] != '['))) {
1889 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001890 return false;
1891 }
1892
1893 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07001894 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001895 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1896 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001897 return false;
1898 }
1899
Andreas Gampedf10b322014-06-11 21:46:05 -07001900 // Check that the proto id is valid.
1901 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
1902 "inter_method_id_item proto_idx"))) {
1903 return false;
1904 }
1905
jeffhao10037c82012-01-23 15:06:23 -08001906 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001907 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001908 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001909 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1910 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001911 return false;
1912 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001913 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1914 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001915 return false;
1916 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001917 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
1918 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001919 return false;
1920 }
1921 }
1922 }
1923 }
1924
1925 ptr_ += sizeof(DexFile::MethodId);
1926 return true;
1927}
1928
1929bool DexFileVerifier::CheckInterClassDefItem() {
1930 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001931
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001932 // Check for duplicate class def.
1933 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
1934 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_);
1935 return false;
1936 }
1937 defined_classes_.insert(item->class_idx_);
1938
Andreas Gampee09269c2014-06-06 18:45:35 -07001939 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
1940 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1941 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001942 return false;
1943 }
1944
Andreas Gampeacc2bb62014-07-17 19:26:50 -07001945 // Only allow non-runtime modifiers.
1946 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
1947 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
1948 return false;
1949 }
1950
jeffhao10037c82012-01-23 15:06:23 -08001951 if (item->interfaces_off_ != 0 &&
1952 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
1953 return false;
1954 }
1955 if (item->annotations_off_ != 0 &&
1956 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
1957 return false;
1958 }
1959 if (item->class_data_off_ != 0 &&
1960 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
1961 return false;
1962 }
1963 if (item->static_values_off_ != 0 &&
1964 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
1965 return false;
1966 }
1967
1968 if (item->superclass_idx_ != DexFile::kDexNoIndex16) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01001969 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
1970 // Check that a class does not inherit from itself directly (by having
1971 // the same type idx as its super class).
1972 if (UNLIKELY(item->superclass_idx_ == item->class_idx_)) {
1973 ErrorStringPrintf("Class with same type idx as its superclass: '%d'", item->class_idx_);
1974 return false;
1975 }
1976
1977 // Check that a class is defined after its super class (if the
1978 // latter is defined in the same Dex file).
1979 const DexFile::ClassDef* superclass_def = dex_file_->FindClassDef(item->superclass_idx_);
1980 if (superclass_def != nullptr) {
1981 // The superclass is defined in this Dex file.
1982 if (superclass_def > item) {
1983 // ClassDef item for super class appearing after the class' ClassDef item.
1984 ErrorStringPrintf("Invalid class definition ordering:"
1985 " class with type idx: '%d' defined before"
1986 " superclass with type idx: '%d'",
1987 item->class_idx_,
1988 item->superclass_idx_);
1989 return false;
1990 }
1991 }
1992 }
1993
Andreas Gampee09269c2014-06-06 18:45:35 -07001994 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
1995 "inter_class_def_item superclass_idx")
1996 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
1997 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001998 return false;
1999 }
2000 }
2001
Roland Levillain621b5ea2016-05-18 11:41:33 +01002002 // Check interfaces.
jeffhao10037c82012-01-23 15:06:23 -08002003 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002004 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08002005 uint32_t size = interfaces->Size();
jeffhao10037c82012-01-23 15:06:23 -08002006 for (uint32_t i = 0; i < size; i++) {
Roland Levillain621b5ea2016-05-18 11:41:33 +01002007 if (header_->GetVersion() >= DexFile::kClassDefinitionOrderEnforcedVersion) {
2008 // Check that a class does not implement itself directly (by having the
2009 // same type idx as one of its immediate implemented interfaces).
2010 if (UNLIKELY(interfaces->GetTypeItem(i).type_idx_ == item->class_idx_)) {
2011 ErrorStringPrintf("Class with same type idx as implemented interface: '%d'",
2012 item->class_idx_);
2013 return false;
2014 }
2015
2016 // Check that a class is defined after the interfaces it implements
2017 // (if they are defined in the same Dex file).
2018 const DexFile::ClassDef* interface_def =
2019 dex_file_->FindClassDef(interfaces->GetTypeItem(i).type_idx_);
2020 if (interface_def != nullptr) {
2021 // The interface is defined in this Dex file.
2022 if (interface_def > item) {
2023 // ClassDef item for interface appearing after the class' ClassDef item.
2024 ErrorStringPrintf("Invalid class definition ordering:"
2025 " class with type idx: '%d' defined before"
2026 " implemented interface with type idx: '%d'",
2027 item->class_idx_,
2028 interfaces->GetTypeItem(i).type_idx_);
2029 return false;
2030 }
2031 }
2032 }
2033
2034 // Ensure that the interface refers to a class (not an array nor a primitive type).
Andreas Gampee09269c2014-06-06 18:45:35 -07002035 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
2036 "inter_class_def_item interface type_idx")
2037 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
2038 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08002039 return false;
2040 }
2041 }
2042
2043 /*
2044 * Ensure that there are no duplicates. This is an O(N^2) test, but in
2045 * practice the number of interfaces implemented by any given class is low.
2046 */
2047 for (uint32_t i = 1; i < size; i++) {
2048 uint32_t idx1 = interfaces->GetTypeItem(i).type_idx_;
2049 for (uint32_t j =0; j < i; j++) {
2050 uint32_t idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002051 if (UNLIKELY(idx1 == idx2)) {
2052 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08002053 return false;
2054 }
2055 }
2056 }
2057 }
2058
2059 // Check that references in class_data_item are to the right class.
2060 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07002061 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002062 bool success;
2063 uint16_t data_definer = FindFirstClassDataDefiner(data, &success);
2064 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002065 return false;
2066 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002067 if (UNLIKELY((data_definer != item->class_idx_) && (data_definer != DexFile::kDexNoIndex16))) {
2068 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08002069 return false;
2070 }
2071 }
2072
2073 // Check that references in annotations_directory_item are to right class.
2074 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002075 // annotations_off_ is supposed to be aligned by 4.
2076 if (!IsAlignedParam(item->annotations_off_, 4)) {
2077 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2078 return false;
2079 }
Ian Rogers13735952014-10-08 12:43:28 -07002080 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002081 bool success;
2082 uint16_t annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
2083 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002084 return false;
2085 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002086 if (UNLIKELY((annotations_definer != item->class_idx_) &&
2087 (annotations_definer != DexFile::kDexNoIndex16))) {
2088 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002089 return false;
2090 }
2091 }
2092
2093 ptr_ += sizeof(DexFile::ClassDef);
2094 return true;
2095}
2096
2097bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2098 const DexFile::AnnotationSetRefList* list =
2099 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2100 const DexFile::AnnotationSetRefItem* item = list->list_;
2101 uint32_t count = list->size_;
2102
2103 while (count--) {
2104 if (item->annotations_off_ != 0 &&
2105 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2106 return false;
2107 }
2108 item++;
2109 }
2110
Ian Rogers13735952014-10-08 12:43:28 -07002111 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002112 return true;
2113}
2114
2115bool DexFileVerifier::CheckInterAnnotationSetItem() {
2116 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2117 const uint32_t* offsets = set->entries_;
2118 uint32_t count = set->size_;
2119 uint32_t last_idx = 0;
2120
2121 for (uint32_t i = 0; i < count; i++) {
2122 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2123 return false;
2124 }
2125
2126 // Get the annotation from the offset and the type index for the annotation.
2127 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002128 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002129 const uint8_t* data = annotation->annotation_;
2130 uint32_t idx = DecodeUnsignedLeb128(&data);
2131
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002132 if (UNLIKELY(last_idx >= idx && i != 0)) {
2133 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002134 return false;
2135 }
2136
2137 last_idx = idx;
2138 offsets++;
2139 }
2140
Ian Rogers13735952014-10-08 12:43:28 -07002141 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002142 return true;
2143}
2144
2145bool DexFileVerifier::CheckInterClassDataItem() {
2146 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002147 bool success;
2148 uint16_t defining_class = FindFirstClassDataDefiner(ptr_, &success);
2149 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002150 return false;
2151 }
jeffhao10037c82012-01-23 15:06:23 -08002152
2153 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002154 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002155 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002156 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002157 return false;
2158 }
2159 }
2160 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2161 uint32_t code_off = it.GetMethodCodeItemOffset();
2162 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2163 return false;
2164 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002165 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002166 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002167 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002168 return false;
2169 }
2170 }
2171
2172 ptr_ = it.EndDataPointer();
2173 return true;
2174}
2175
2176bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2177 const DexFile::AnnotationsDirectoryItem* item =
2178 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002179 bool success;
2180 uint16_t defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
2181 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002182 return false;
2183 }
jeffhao10037c82012-01-23 15:06:23 -08002184
2185 if (item->class_annotations_off_ != 0 &&
2186 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2187 return false;
2188 }
2189
2190 // Field annotations follow immediately after the annotations directory.
2191 const DexFile::FieldAnnotationsItem* field_item =
2192 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2193 uint32_t field_count = item->fields_size_;
2194 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002195 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2196 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002197 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002198 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002199 return false;
2200 }
2201 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2202 return false;
2203 }
2204 field_item++;
2205 }
2206
2207 // Method annotations follow immediately after field annotations.
2208 const DexFile::MethodAnnotationsItem* method_item =
2209 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2210 uint32_t method_count = item->methods_size_;
2211 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002212 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002213 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002214 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002215 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002216 return false;
2217 }
2218 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2219 return false;
2220 }
2221 method_item++;
2222 }
2223
2224 // Parameter annotations follow immediately after method annotations.
2225 const DexFile::ParameterAnnotationsItem* parameter_item =
2226 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2227 uint32_t parameter_count = item->parameters_size_;
2228 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002229 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002230 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002231 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002232 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002233 return false;
2234 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002235 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2236 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002237 return false;
2238 }
2239 parameter_item++;
2240 }
2241
Ian Rogers13735952014-10-08 12:43:28 -07002242 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002243 return true;
2244}
2245
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002246bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002247 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002248 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002249 switch (type) {
2250 case DexFile::kDexTypeClassDataItem:
2251 alignment_mask = sizeof(uint8_t) - 1;
2252 break;
2253 default:
2254 alignment_mask = sizeof(uint32_t) - 1;
2255 break;
2256 }
2257
2258 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002259 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002260 for (uint32_t i = 0; i < count; i++) {
2261 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002262 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002263 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002264
2265 // Check depending on the section type.
2266 switch (type) {
2267 case DexFile::kDexTypeStringIdItem: {
2268 if (!CheckInterStringIdItem()) {
2269 return false;
2270 }
2271 break;
2272 }
2273 case DexFile::kDexTypeTypeIdItem: {
2274 if (!CheckInterTypeIdItem()) {
2275 return false;
2276 }
2277 break;
2278 }
2279 case DexFile::kDexTypeProtoIdItem: {
2280 if (!CheckInterProtoIdItem()) {
2281 return false;
2282 }
2283 break;
2284 }
2285 case DexFile::kDexTypeFieldIdItem: {
2286 if (!CheckInterFieldIdItem()) {
2287 return false;
2288 }
2289 break;
2290 }
2291 case DexFile::kDexTypeMethodIdItem: {
2292 if (!CheckInterMethodIdItem()) {
2293 return false;
2294 }
2295 break;
2296 }
2297 case DexFile::kDexTypeClassDefItem: {
2298 if (!CheckInterClassDefItem()) {
2299 return false;
2300 }
2301 break;
2302 }
2303 case DexFile::kDexTypeAnnotationSetRefList: {
2304 if (!CheckInterAnnotationSetRefList()) {
2305 return false;
2306 }
2307 break;
2308 }
2309 case DexFile::kDexTypeAnnotationSetItem: {
2310 if (!CheckInterAnnotationSetItem()) {
2311 return false;
2312 }
2313 break;
2314 }
2315 case DexFile::kDexTypeClassDataItem: {
2316 if (!CheckInterClassDataItem()) {
2317 return false;
2318 }
2319 break;
2320 }
2321 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2322 if (!CheckInterAnnotationsDirectoryItem()) {
2323 return false;
2324 }
2325 break;
2326 }
2327 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002328 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002329 return false;
2330 }
2331
2332 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002333 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002334 }
2335
2336 return true;
2337}
2338
2339bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002340 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002341 const DexFile::MapItem* item = map->list_;
2342 uint32_t count = map->size_;
2343
2344 // Cross check the items listed in the map.
2345 while (count--) {
2346 uint32_t section_offset = item->offset_;
2347 uint32_t section_count = item->size_;
2348 uint16_t type = item->type_;
2349
2350 switch (type) {
2351 case DexFile::kDexTypeHeaderItem:
2352 case DexFile::kDexTypeMapList:
2353 case DexFile::kDexTypeTypeList:
2354 case DexFile::kDexTypeCodeItem:
2355 case DexFile::kDexTypeStringDataItem:
2356 case DexFile::kDexTypeDebugInfoItem:
2357 case DexFile::kDexTypeAnnotationItem:
2358 case DexFile::kDexTypeEncodedArrayItem:
2359 break;
2360 case DexFile::kDexTypeStringIdItem:
2361 case DexFile::kDexTypeTypeIdItem:
2362 case DexFile::kDexTypeProtoIdItem:
2363 case DexFile::kDexTypeFieldIdItem:
2364 case DexFile::kDexTypeMethodIdItem:
2365 case DexFile::kDexTypeClassDefItem:
2366 case DexFile::kDexTypeAnnotationSetRefList:
2367 case DexFile::kDexTypeAnnotationSetItem:
2368 case DexFile::kDexTypeClassDataItem:
2369 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2370 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2371 return false;
2372 }
2373 break;
2374 }
2375 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002376 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002377 return false;
2378 }
2379
2380 item++;
2381 }
2382
2383 return true;
2384}
2385
2386bool DexFileVerifier::Verify() {
2387 // Check the header.
2388 if (!CheckHeader()) {
2389 return false;
2390 }
2391
2392 // Check the map section.
2393 if (!CheckMap()) {
2394 return false;
2395 }
2396
2397 // Check structure within remaining sections.
2398 if (!CheckIntraSection()) {
2399 return false;
2400 }
2401
2402 // Check references from one section to another.
2403 if (!CheckInterSection()) {
2404 return false;
2405 }
2406
2407 return true;
2408}
2409
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002410void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2411 va_list ap;
2412 va_start(ap, fmt);
2413 DCHECK(failure_reason_.empty()) << failure_reason_;
2414 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2415 StringAppendV(&failure_reason_, fmt, ap);
2416 va_end(ap);
2417}
2418
Andreas Gampee6215c02015-08-31 18:54:38 -07002419// Fields and methods may have only one of public/protected/private.
2420static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2421 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2422 (((flags & kAccProtected) == 0) ? 0 : 1) +
2423 (((flags & kAccPrivate) == 0) ? 0 : 1);
2424 return count <= 1;
2425}
2426
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002427// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2428// functionality, as we're still verifying the dex file. begin and header correspond to the
2429// underscored variants in the DexFileVerifier.
2430
2431static std::string GetStringOrError(const uint8_t* const begin,
2432 const DexFile::Header* const header,
2433 uint32_t string_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002434 // The `string_idx` is not guaranteed to be valid yet.
2435 if (header->string_ids_size_ <= string_idx) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002436 return "(error)";
2437 }
2438
2439 const DexFile::StringId* string_id =
2440 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx;
2441
2442 // Assume that the data is OK at this point. String data has been checked at this point.
2443
2444 const uint8_t* ptr = begin + string_id->string_data_off_;
2445 DecodeUnsignedLeb128(&ptr);
2446 return reinterpret_cast<const char*>(ptr);
2447}
2448
2449static std::string GetClassOrError(const uint8_t* const begin,
2450 const DexFile::Header* const header,
2451 uint32_t class_idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002452 // The `class_idx` is either `FieldId::class_idx_` or `MethodId::class_idx_` and
2453 // it has already been checked in `DexFileVerifier::CheckClassDataItemField()`
2454 // or `DexFileVerifier::CheckClassDataItemMethod()`, respectively, to match
2455 // a valid defining class.
2456 CHECK_LT(class_idx, header->type_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002457
2458 const DexFile::TypeId* type_id =
2459 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx;
2460
2461 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2462
2463 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2464}
2465
2466static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2467 const DexFile::Header* const header,
2468 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002469 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemField()`.
2470 CHECK_LT(idx, header->field_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002471
2472 const DexFile::FieldId* field_id =
2473 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2474
2475 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2476
2477 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2478 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2479
2480 return class_name + "." + field_name;
2481}
2482
2483static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2484 const DexFile::Header* const header,
2485 uint32_t idx) {
Vladimir Marko59399ab2016-05-03 16:31:52 +01002486 // The `idx` has already been checked in `DexFileVerifier::CheckClassDataItemMethod()`.
2487 CHECK_LT(idx, header->method_ids_size_);
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002488
2489 const DexFile::MethodId* method_id =
2490 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2491
2492 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2493
2494 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2495 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2496
2497 return class_name + "." + method_name;
2498}
2499
2500bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2501 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002502 uint32_t class_access_flags,
2503 std::string* error_msg) {
2504 // Generally sort out >16-bit flags.
2505 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002506 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2507 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2508 field_access_flags,
2509 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002510 return false;
2511 }
2512
2513 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2514 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2515 kAccPrivate |
2516 kAccProtected |
2517 kAccStatic |
2518 kAccFinal |
2519 kAccVolatile |
2520 kAccTransient |
2521 kAccSynthetic |
2522 kAccEnum;
2523
2524 // Fields may have only one of public/protected/final.
2525 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002526 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2527 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2528 field_access_flags,
2529 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002530 return false;
2531 }
2532
2533 // Interfaces have a pretty restricted list.
2534 if ((class_access_flags & kAccInterface) != 0) {
2535 // Interface fields must be public final static.
2536 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2537 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002538 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2539 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2540 field_access_flags,
2541 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002542 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002543 return false;
2544 } else {
2545 // Allow in older versions, but warn.
2546 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2547 << *error_msg;
2548 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002549 }
2550 // Interface fields may be synthetic, but may not have other flags.
2551 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2552 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002553 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
2554 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2555 field_access_flags,
2556 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002557 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002558 return false;
2559 } else {
2560 // Allow in older versions, but warn.
2561 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2562 << *error_msg;
2563 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002564 }
2565 return true;
2566 }
2567
2568 // Volatile fields may not be final.
2569 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2570 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002571 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
2572 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002573 return false;
2574 }
2575
2576 return true;
2577}
2578
2579// Try to find the name of the method with the given index. We do not want to rely on DexFile
2580// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
2581// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
2582// (flagged by the return value), otherwise error_msg will contain an error string.
2583static bool FindMethodName(uint32_t method_index,
2584 const uint8_t* begin,
2585 const DexFile::Header* header,
2586 const char** str,
2587 std::string* error_msg) {
2588 if (method_index >= header->method_ids_size_) {
2589 *error_msg = "Method index not available for method flags verification";
2590 return false;
2591 }
2592 uint32_t string_idx =
2593 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
2594 method_index)->name_idx_;
2595 if (string_idx >= header->string_ids_size_) {
2596 *error_msg = "String index not available for method flags verification";
2597 return false;
2598 }
2599 uint32_t string_off =
2600 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
2601 string_data_off_;
2602 if (string_off >= header->file_size_) {
2603 *error_msg = "String offset out of bounds for method flags verification";
2604 return false;
2605 }
2606 const uint8_t* str_data_ptr = begin + string_off;
2607 DecodeUnsignedLeb128(&str_data_ptr);
2608 *str = reinterpret_cast<const char*>(str_data_ptr);
2609 return true;
2610}
2611
2612bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2613 uint32_t method_access_flags,
2614 uint32_t class_access_flags,
2615 bool has_code,
2616 bool expect_direct,
2617 std::string* error_msg) {
2618 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2619 constexpr uint32_t kAllMethodFlags =
2620 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2621 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002622 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
2623 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2624 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002625 return false;
2626 }
2627
2628 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2629 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2630 kAccPrivate |
2631 kAccProtected |
2632 kAccStatic |
2633 kAccFinal |
2634 kAccSynthetic |
2635 kAccSynchronized |
2636 kAccBridge |
2637 kAccVarargs |
2638 kAccNative |
2639 kAccAbstract |
2640 kAccStrict;
2641
2642 // Methods may have only one of public/protected/final.
2643 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002644 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
2645 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002646 method_access_flags);
2647 return false;
2648 }
2649
2650 // Try to find the name, to check for constructor properties.
2651 const char* str;
2652 if (!FindMethodName(method_index, begin_, header_, &str, error_msg)) {
2653 return false;
2654 }
2655 bool is_init_by_name = false;
2656 constexpr const char* kInitName = "<init>";
2657 size_t str_offset = (reinterpret_cast<const uint8_t*>(str) - begin_);
2658 if (header_->file_size_ - str_offset >= sizeof(kInitName)) {
2659 is_init_by_name = strcmp(kInitName, str) == 0;
2660 }
2661 bool is_clinit_by_name = false;
2662 constexpr const char* kClinitName = "<clinit>";
2663 if (header_->file_size_ - str_offset >= sizeof(kClinitName)) {
2664 is_clinit_by_name = strcmp(kClinitName, str) == 0;
2665 }
2666 bool is_constructor = is_init_by_name || is_clinit_by_name;
2667
2668 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2669 // the reverse for backwards compatibility reasons.
2670 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002671 *error_msg =
2672 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
2673 method_index,
2674 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002675 return false;
2676 }
2677 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2678 // instance constructor is called "<init>".
2679 if (is_constructor) {
2680 bool is_static = (method_access_flags & kAccStatic) != 0;
2681 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002682 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
2683 method_index,
2684 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002685 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2686 return false;
2687 } else {
2688 // Allow in older versions, but warn.
2689 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2690 << *error_msg;
2691 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002692 }
2693 }
2694 // Check that static and private methods, as well as constructors, are in the direct methods list,
2695 // and other methods in the virtual methods list.
2696 bool is_direct = (method_access_flags & (kAccStatic | kAccPrivate)) != 0 || is_constructor;
2697 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002698 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07002699 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002700 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002701 expect_direct);
2702 return false;
2703 }
2704
2705
2706 // From here on out it is easier to mask out the bits we're supposed to ignore.
2707 method_access_flags &= kMethodAccessFlags;
2708
Alex Lightd7c10c22016-03-31 10:03:07 -07002709 // Interfaces are special.
2710 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07002711 // Non-static interface methods must be public or private.
2712 uint32_t desired_flags = (kAccPublic | kAccStatic);
2713 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2714 desired_flags |= kAccPrivate;
2715 }
2716 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002717 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
2718 method_index,
2719 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002720 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002721 return false;
2722 } else {
2723 // Allow in older versions, but warn.
2724 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2725 << *error_msg;
2726 }
2727 }
2728 }
2729
Andreas Gampee6215c02015-08-31 18:54:38 -07002730 // If there aren't any instructions, make sure that's expected.
2731 if (!has_code) {
2732 // Only native or abstract methods may not have code.
2733 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002734 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07002735 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002736 method_index,
2737 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002738 return false;
2739 }
2740 // Constructors must always have code.
2741 if (is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002742 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
2743 method_index,
2744 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightf0ecae72016-05-06 10:39:06 -07002745 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2746 return false;
2747 } else {
2748 // Allow in older versions, but warn.
2749 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2750 << *error_msg;
2751 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002752 }
2753 if ((method_access_flags & kAccAbstract) != 0) {
2754 // Abstract methods are not allowed to have the following flags.
2755 constexpr uint32_t kForbidden =
2756 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2757 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002758 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
2759 method_index,
2760 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2761 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002762 return false;
2763 }
Andreas Gampe97b11352015-12-10 16:23:41 -08002764 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07002765 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002766 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08002767 << " is abstract, but the declaring class is neither abstract nor an "
2768 << "interface in dex file "
2769 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07002770 }
2771 }
2772 // Interfaces are special.
2773 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002774 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07002775 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002776 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
2777 method_index,
2778 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002779 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002780 return false;
2781 } else {
2782 // Allow in older versions, but warn.
2783 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2784 << *error_msg;
2785 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002786 }
2787 // At this point, we know the method is public and abstract. This means that all the checks
2788 // for invalid combinations above applies. In addition, interface methods must not be
2789 // protected. This is caught by the check for only-one-of-public-protected-private.
2790 }
2791 return true;
2792 }
2793
2794 // When there's code, the method must not be native or abstract.
2795 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002796 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
2797 method_index,
2798 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002799 return false;
2800 }
2801
Andreas Gampee6215c02015-08-31 18:54:38 -07002802 // Instance constructors must not be synchronized and a few other flags.
2803 if (is_init_by_name) {
2804 static constexpr uint32_t kInitAllowed =
2805 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2806 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002807 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07002808 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002809 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002810 method_access_flags);
2811 return false;
2812 }
2813 }
2814
2815 return true;
2816}
2817
jeffhao10037c82012-01-23 15:06:23 -08002818} // namespace art