blob: 09416cc5c4f74506aa91c70946bc932c16c1d429 [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"
jeffhao10037c82012-01-23 15:06:23 -080026#include "leb128.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070027#include "safe_map.h"
Ian Rogersa6724902013-09-23 09:23:37 -070028#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080029#include "utils.h"
jeffhao10037c82012-01-23 15:06:23 -080030
31namespace art {
32
33static uint32_t MapTypeToBitMask(uint32_t map_type) {
34 switch (map_type) {
35 case DexFile::kDexTypeHeaderItem: return 1 << 0;
36 case DexFile::kDexTypeStringIdItem: return 1 << 1;
37 case DexFile::kDexTypeTypeIdItem: return 1 << 2;
38 case DexFile::kDexTypeProtoIdItem: return 1 << 3;
39 case DexFile::kDexTypeFieldIdItem: return 1 << 4;
40 case DexFile::kDexTypeMethodIdItem: return 1 << 5;
41 case DexFile::kDexTypeClassDefItem: return 1 << 6;
42 case DexFile::kDexTypeMapList: return 1 << 7;
43 case DexFile::kDexTypeTypeList: return 1 << 8;
44 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9;
45 case DexFile::kDexTypeAnnotationSetItem: return 1 << 10;
46 case DexFile::kDexTypeClassDataItem: return 1 << 11;
47 case DexFile::kDexTypeCodeItem: return 1 << 12;
48 case DexFile::kDexTypeStringDataItem: return 1 << 13;
49 case DexFile::kDexTypeDebugInfoItem: return 1 << 14;
50 case DexFile::kDexTypeAnnotationItem: return 1 << 15;
51 case DexFile::kDexTypeEncodedArrayItem: return 1 << 16;
52 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17;
53 }
54 return 0;
55}
56
57static bool IsDataSectionType(uint32_t map_type) {
58 switch (map_type) {
59 case DexFile::kDexTypeHeaderItem:
60 case DexFile::kDexTypeStringIdItem:
61 case DexFile::kDexTypeTypeIdItem:
62 case DexFile::kDexTypeProtoIdItem:
63 case DexFile::kDexTypeFieldIdItem:
64 case DexFile::kDexTypeMethodIdItem:
65 case DexFile::kDexTypeClassDefItem:
66 return false;
67 }
68 return true;
69}
70
Andreas Gampee09269c2014-06-06 18:45:35 -070071const char* DexFileVerifier::CheckLoadStringByIdx(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070072 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070073 return nullptr;
74 }
75 return dex_file_->StringDataByIdx(idx);
76}
77
78const char* DexFileVerifier::CheckLoadStringByTypeIdx(uint32_t type_idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070079 if (UNLIKELY(!CheckIndex(type_idx, dex_file_->NumTypeIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070080 return nullptr;
81 }
82 const DexFile::TypeId& type_id = dex_file_->GetTypeId(type_idx);
83 uint32_t idx = type_id.descriptor_idx_;
84 return CheckLoadStringByIdx(idx, error_string);
85}
86
87const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070088 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070089 return nullptr;
90 }
91 return &dex_file_->GetFieldId(idx);
92}
93
94const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070095 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070096 return nullptr;
97 }
98 return &dex_file_->GetMethodId(idx);
99}
100
101// Helper macro to load string and return false on error.
102#define LOAD_STRING(var, idx, error) \
103 const char* var = CheckLoadStringByIdx(idx, error); \
Andreas Gampedf10b322014-06-11 21:46:05 -0700104 if (UNLIKELY(var == nullptr)) { \
Andreas Gampee09269c2014-06-06 18:45:35 -0700105 return false; \
106 }
107
108// Helper macro to load string by type idx and return false on error.
109#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
110 const char* var = CheckLoadStringByTypeIdx(type_idx, error); \
Andreas Gampedf10b322014-06-11 21:46:05 -0700111 if (UNLIKELY(var == nullptr)) { \
Andreas Gampee09269c2014-06-06 18:45:35 -0700112 return false; \
113 }
114
115// Helper macro to load method id. Return last parameter on error.
Andreas Gampe5e31dda2014-06-13 11:35:12 -0700116#define LOAD_METHOD(var, idx, error_string, error_stmt) \
Andreas Gampee09269c2014-06-06 18:45:35 -0700117 const DexFile::MethodId* var = CheckLoadMethodId(idx, error_string); \
Andreas Gampedf10b322014-06-11 21:46:05 -0700118 if (UNLIKELY(var == nullptr)) { \
Andreas Gampe5e31dda2014-06-13 11:35:12 -0700119 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700120 }
121
122// Helper macro to load method id. Return last parameter on error.
Andreas Gampe5e31dda2014-06-13 11:35:12 -0700123#define LOAD_FIELD(var, idx, fmt, error_stmt) \
Andreas Gampee09269c2014-06-06 18:45:35 -0700124 const DexFile::FieldId* var = CheckLoadFieldId(idx, fmt); \
Andreas Gampedf10b322014-06-11 21:46:05 -0700125 if (UNLIKELY(var == nullptr)) { \
Andreas Gampe5e31dda2014-06-13 11:35:12 -0700126 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700127 }
128
Ian Rogers13735952014-10-08 12:43:28 -0700129bool DexFileVerifier::Verify(const DexFile* dex_file, const uint8_t* begin, size_t size,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700130 const char* location, std::string* error_msg) {
Ian Rogers700a4022014-05-19 16:49:03 -0700131 std::unique_ptr<DexFileVerifier> verifier(new DexFileVerifier(dex_file, begin, size, location));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700132 if (!verifier->Verify()) {
133 *error_msg = verifier->FailureReason();
134 return false;
135 }
136 return true;
137}
138
139bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
140 bool is_return_type) {
jeffhao10037c82012-01-23 15:06:23 -0800141 switch (shorty_char) {
142 case 'V':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700143 if (UNLIKELY(!is_return_type)) {
144 ErrorStringPrintf("Invalid use of void");
jeffhao10037c82012-01-23 15:06:23 -0800145 return false;
146 }
Ian Rogersfc787ec2014-10-09 21:56:44 -0700147 FALLTHROUGH_INTENDED;
jeffhao10037c82012-01-23 15:06:23 -0800148 case 'B':
149 case 'C':
150 case 'D':
151 case 'F':
152 case 'I':
153 case 'J':
154 case 'S':
155 case 'Z':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700156 if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
157 ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
158 shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800159 return false;
160 }
161 break;
162 case 'L':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700163 if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
164 ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800165 return false;
166 }
167 break;
168 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700169 ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
jeffhao10037c82012-01-23 15:06:23 -0800170 return false;
171 }
172 return true;
173}
174
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700175bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700176 const char* label) {
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700177 // Check that size is not 0.
178 CHECK_NE(elem_size, 0U);
179
Ian Rogers13735952014-10-08 12:43:28 -0700180 const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
181 const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700182
183 // Check for overflow.
184 uintptr_t max = 0 - 1;
185 size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
186 size_t max_count = available_bytes_till_end_of_mem / elem_size;
187 if (max_count < count) {
188 ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
189 static_cast<size_t>(range_start - file_start),
190 count, elem_size);
191 return false;
192 }
193
Ian Rogers13735952014-10-08 12:43:28 -0700194 const uint8_t* range_end = range_start + count * elem_size;
195 const uint8_t* file_end = file_start + size_;
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700196 if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
197 // Note: these two tests are enough as we make sure above that there's no overflow.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800198 ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
Ian Rogerse3d55812014-06-11 13:00:44 -0700199 static_cast<size_t>(range_start - file_start),
200 static_cast<size_t>(range_end - file_start));
jeffhao10037c82012-01-23 15:06:23 -0800201 return false;
202 }
203 return true;
204}
205
Ian Rogers13735952014-10-08 12:43:28 -0700206bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700207 // Check that the list is available. The first 4B are the count.
208 if (!CheckListSize(*ptr, 1, 4U, label)) {
209 return false;
210 }
211
212 uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
213 if (count > 0) {
214 if (!CheckListSize(*ptr + 4, count, element_size, label)) {
215 return false;
216 }
217 }
218
219 *ptr += 4 + count * element_size;
220 return true;
221}
222
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700223bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
224 if (UNLIKELY(field >= limit)) {
225 ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
jeffhao10037c82012-01-23 15:06:23 -0800226 return false;
227 }
228 return true;
229}
230
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700231bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset, uint32_t size, const char* label) {
232 if (size == 0) {
233 if (offset != 0) {
234 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
235 return false;
236 }
237 }
238 if (size_ <= offset) {
239 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
240 return false;
241 }
242 return true;
243}
244
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700245bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800246 // Check file size from the header.
247 uint32_t expected_size = header_->file_size_;
248 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700249 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800250 return false;
251 }
252
253 // Compute and verify the checksum in the header.
254 uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
255 const uint32_t non_sum = sizeof(header_->magic_) + sizeof(header_->checksum_);
Ian Rogers13735952014-10-08 12:43:28 -0700256 const uint8_t* non_sum_ptr = reinterpret_cast<const uint8_t*>(header_) + non_sum;
jeffhaof6174e82012-01-31 16:14:17 -0800257 adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
jeffhao10037c82012-01-23 15:06:23 -0800258 if (adler_checksum != header_->checksum_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700259 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
jeffhao10037c82012-01-23 15:06:23 -0800260 return false;
261 }
262
263 // Check the contents of the header.
264 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700265 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800266 return false;
267 }
268
269 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700270 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800271 return false;
272 }
273
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700274 // Check that all offsets are inside the file.
275 bool result =
276 CheckValidOffsetAndSize(header_->link_off_, header_->link_size_, "link") &&
277 CheckValidOffsetAndSize(header_->map_off_, header_->map_off_, "map") &&
278 CheckValidOffsetAndSize(header_->string_ids_off_, header_->string_ids_size_, "string-ids") &&
279 CheckValidOffsetAndSize(header_->type_ids_off_, header_->type_ids_size_, "type-ids") &&
280 CheckValidOffsetAndSize(header_->proto_ids_off_, header_->proto_ids_size_, "proto-ids") &&
281 CheckValidOffsetAndSize(header_->field_ids_off_, header_->field_ids_size_, "field-ids") &&
282 CheckValidOffsetAndSize(header_->method_ids_off_, header_->method_ids_size_, "method-ids") &&
283 CheckValidOffsetAndSize(header_->class_defs_off_, header_->class_defs_size_, "class-defs") &&
284 CheckValidOffsetAndSize(header_->data_off_, header_->data_size_, "data");
285
286 return result;
jeffhao10037c82012-01-23 15:06:23 -0800287}
288
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700289bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700290 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
291 header_->map_off_);
292 // Check that map list content is available.
293 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
294 return false;
295 }
296
jeffhao10037c82012-01-23 15:06:23 -0800297 const DexFile::MapItem* item = map->list_;
298
299 uint32_t count = map->size_;
300 uint32_t last_offset = 0;
301 uint32_t data_item_count = 0;
302 uint32_t data_items_left = header_->data_size_;
303 uint32_t used_bits = 0;
304
305 // Sanity check the size of the map list.
306 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
307 return false;
308 }
309
310 // Check the items listed in the map.
311 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700312 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
313 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800314 return false;
315 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700316 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
317 ErrorStringPrintf("Map item after end of file: %x, size %x",
318 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800319 return false;
320 }
321
322 if (IsDataSectionType(item->type_)) {
323 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700324 if (UNLIKELY(icount > data_items_left)) {
325 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800326 return false;
327 }
328 data_items_left -= icount;
329 data_item_count += icount;
330 }
331
332 uint32_t bit = MapTypeToBitMask(item->type_);
333
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700334 if (UNLIKELY(bit == 0)) {
335 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800336 return false;
337 }
338
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700339 if (UNLIKELY((used_bits & bit) != 0)) {
340 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800341 return false;
342 }
343
344 used_bits |= bit;
345 last_offset = item->offset_;
346 item++;
347 }
348
349 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700350 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
351 ErrorStringPrintf("Map is missing header entry");
jeffhao10037c82012-01-23 15:06:23 -0800352 return false;
353 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700354 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
355 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800356 return false;
357 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700358 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
359 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
360 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800361 return false;
362 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700363 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
364 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
365 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800366 return false;
367 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700368 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
369 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
370 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800371 return false;
372 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700373 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
374 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
375 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800376 return false;
377 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700378 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
379 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
380 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800381 return false;
382 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700383 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
384 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
385 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800386 return false;
387 }
jeffhao10037c82012-01-23 15:06:23 -0800388 return true;
389}
390
391uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
392 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700393 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700394 for (uint32_t i = 0; i < size; i++) {
395 result |= ((uint32_t) *(ptr_++)) << (i * 8);
396 }
jeffhao10037c82012-01-23 15:06:23 -0800397 }
jeffhao10037c82012-01-23 15:06:23 -0800398 return result;
399}
400
401bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700402 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700403 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800404
405 for (uint32_t i = 0; i < handlers_size; i++) {
406 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800407 size_t offset = ptr_ - handlers_base;
jeffhao10037c82012-01-23 15:06:23 -0800408 int32_t size = DecodeSignedLeb128(&ptr_);
409
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700410 if (UNLIKELY((size < -65536) || (size > 65536))) {
411 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800412 return false;
413 }
414
415 if (size <= 0) {
416 catch_all = true;
417 size = -size;
418 } else {
419 catch_all = false;
420 }
421
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800422 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800423
424 while (size-- > 0) {
425 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
426 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
427 return false;
428 }
429
430 uint32_t addr = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700431 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
432 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800433 return false;
434 }
435 }
436
437 if (catch_all) {
438 uint32_t addr = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700439 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
440 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800441 return false;
442 }
443 }
444 }
445
446 return true;
447}
448
Andreas Gampee6215c02015-08-31 18:54:38 -0700449bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
450 uint32_t access_flags,
451 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700452 uint16_t class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700453 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700454 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800455 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
456 return false;
457 }
458
Andreas Gampee6215c02015-08-31 18:54:38 -0700459 // Check that it's the right class.
460 uint16_t my_class_index =
461 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
462 class_idx_;
463 if (class_type_index != my_class_index) {
464 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
465 my_class_index,
466 class_type_index);
467 return false;
468 }
469
470 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800471 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700472 if (UNLIKELY(is_static != expect_static)) {
473 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800474 return false;
475 }
476
Andreas Gampee6215c02015-08-31 18:54:38 -0700477 // Check field access flags.
478 std::string error_msg;
479 if (!CheckFieldAccessFlags(access_flags, class_access_flags, &error_msg)) {
480 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800481 return false;
482 }
483
484 return true;
485}
486
Andreas Gampee6215c02015-08-31 18:54:38 -0700487bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
488 uint32_t access_flags,
489 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700490 uint16_t class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700491 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700492 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700493 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700494 DCHECK(direct_method_indexes != nullptr);
495 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800496 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
497 return false;
498 }
499
Andreas Gampee6215c02015-08-31 18:54:38 -0700500 // Check that it's the right class.
501 uint16_t my_class_index =
502 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
503 class_idx_;
504 if (class_type_index != my_class_index) {
505 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 "vs %" PRIu16,
506 my_class_index,
507 class_type_index);
jeffhao10037c82012-01-23 15:06:23 -0800508 return false;
509 }
510
Andreas Gampee6215c02015-08-31 18:54:38 -0700511 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700512 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700513 direct_method_indexes->insert(idx);
514 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700515 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
516 return false;
517 }
518
Andreas Gampee6215c02015-08-31 18:54:38 -0700519 // Check method access flags.
520 bool has_code = (code_offset != 0);
521 std::string error_msg;
522 if (!CheckMethodAccessFlags(idx,
523 access_flags,
524 class_access_flags,
525 has_code,
526 expect_direct,
527 &error_msg)) {
528 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800529 return false;
530 }
531
532 return true;
533}
534
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800535bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800536 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700537 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800538 return false;
539 }
540 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700541 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800542 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800543 return false;
544 }
545 ptr_++;
546 offset++;
547 }
548 }
549 return true;
550}
551
552bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700553 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800554 return false;
555 }
556
557 uint8_t header_byte = *(ptr_++);
558 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
559 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
560
561 switch (value_type) {
562 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700563 if (UNLIKELY(value_arg != 0)) {
564 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800565 return false;
566 }
567 ptr_++;
568 break;
569 case DexFile::kDexAnnotationShort:
570 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700571 if (UNLIKELY(value_arg > 1)) {
572 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800573 return false;
574 }
575 ptr_ += value_arg + 1;
576 break;
577 case DexFile::kDexAnnotationInt:
578 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700579 if (UNLIKELY(value_arg > 3)) {
580 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800581 return false;
582 }
583 ptr_ += value_arg + 1;
584 break;
585 case DexFile::kDexAnnotationLong:
586 case DexFile::kDexAnnotationDouble:
587 ptr_ += value_arg + 1;
588 break;
589 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700590 if (UNLIKELY(value_arg > 3)) {
591 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800592 return false;
593 }
594 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
595 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
596 return false;
597 }
598 break;
599 }
600 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700601 if (UNLIKELY(value_arg > 3)) {
602 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800603 return false;
604 }
605 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
606 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
607 return false;
608 }
609 break;
610 }
611 case DexFile::kDexAnnotationField:
612 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700613 if (UNLIKELY(value_arg > 3)) {
614 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800615 return false;
616 }
617 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
618 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
619 return false;
620 }
621 break;
622 }
623 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700624 if (UNLIKELY(value_arg > 3)) {
625 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800626 return false;
627 }
628 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
629 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
630 return false;
631 }
632 break;
633 }
634 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700635 if (UNLIKELY(value_arg != 0)) {
636 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800637 return false;
638 }
639 if (!CheckEncodedArray()) {
640 return false;
641 }
642 break;
643 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700644 if (UNLIKELY(value_arg != 0)) {
645 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800646 return false;
647 }
648 if (!CheckEncodedAnnotation()) {
649 return false;
650 }
651 break;
652 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700653 if (UNLIKELY(value_arg != 0)) {
654 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800655 return false;
656 }
657 break;
658 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700659 if (UNLIKELY(value_arg > 1)) {
660 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800661 return false;
662 }
663 break;
664 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700665 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800666 return false;
667 }
668
669 return true;
670}
671
672bool DexFileVerifier::CheckEncodedArray() {
673 uint32_t size = DecodeUnsignedLeb128(&ptr_);
674
675 while (size--) {
676 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700677 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800678 return false;
679 }
680 }
681 return true;
682}
683
684bool DexFileVerifier::CheckEncodedAnnotation() {
685 uint32_t idx = DecodeUnsignedLeb128(&ptr_);
686 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
687 return false;
688 }
689
690 uint32_t size = DecodeUnsignedLeb128(&ptr_);
691 uint32_t last_idx = 0;
692
693 for (uint32_t i = 0; i < size; i++) {
694 idx = DecodeUnsignedLeb128(&ptr_);
695 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
696 return false;
697 }
698
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700699 if (UNLIKELY(last_idx >= idx && i != 0)) {
700 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
701 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800702 return false;
703 }
704
705 if (!CheckEncodedValue()) {
706 return false;
707 }
708
709 last_idx = idx;
710 }
711 return true;
712}
713
Andreas Gampee6215c02015-08-31 18:54:38 -0700714bool DexFileVerifier::FindClassFlags(uint32_t index,
715 bool is_field,
716 uint16_t* class_type_index,
717 uint32_t* class_access_flags) {
718 DCHECK(class_type_index != nullptr);
719 DCHECK(class_access_flags != nullptr);
720
721 // First check if the index is valid.
722 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
723 return false;
724 }
725
726 // Next get the type index.
727 if (is_field) {
728 *class_type_index =
729 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
730 class_idx_;
731 } else {
732 *class_type_index =
733 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
734 class_idx_;
735 }
736
737 // Check if that is valid.
738 if (*class_type_index >= header_->type_ids_size_) {
739 return false;
740 }
741
742 // Now search for the class def. This is basically a specialized version of the DexFile code, as
743 // we should not trust that this is a valid DexFile just yet.
744 const DexFile::ClassDef* class_def_begin =
745 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
746 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
747 const DexFile::ClassDef* class_def = class_def_begin + i;
748 if (class_def->class_idx_ == *class_type_index) {
749 *class_access_flags = class_def->access_flags_;
750 return true;
751 }
752 }
753
754 // Didn't find the class-def, not defined here...
755 return false;
756}
757
758bool DexFileVerifier::CheckOrderAndGetClassFlags(bool is_field,
759 const char* type_descr,
760 uint32_t curr_index,
761 uint32_t prev_index,
762 bool* have_class,
763 uint16_t* class_type_index,
764 uint32_t* class_access_flags) {
765 if (curr_index < prev_index) {
766 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
767 type_descr,
768 prev_index,
769 curr_index);
770 return false;
771 }
772
773 if (!*have_class) {
774 *have_class = FindClassFlags(curr_index, is_field, class_type_index, class_access_flags);
775 if (!*have_class) {
776 // Should have really found one.
777 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
778 type_descr,
779 curr_index);
780 return false;
781 }
782 }
783 return true;
784}
785
786template <bool kStatic>
787bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
788 bool* have_class,
789 uint16_t* class_type_index,
790 uint32_t* class_access_flags) {
791 DCHECK(it != nullptr);
792 // These calls use the raw access flags to check whether the whole dex field is valid.
793 uint32_t prev_index = 0;
794 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
795 uint32_t curr_index = it->GetMemberIndex();
796 if (!CheckOrderAndGetClassFlags(true,
797 kStatic ? "static field" : "instance field",
798 curr_index,
799 prev_index,
800 have_class,
801 class_type_index,
802 class_access_flags)) {
803 return false;
804 }
805 prev_index = curr_index;
806
807 if (!CheckClassDataItemField(curr_index,
808 it->GetRawMemberAccessFlags(),
809 *class_access_flags,
810 *class_type_index,
811 kStatic)) {
812 return false;
813 }
814 }
815
816 return true;
817}
818
819template <bool kDirect>
820bool DexFileVerifier::CheckIntraClassDataItemMethods(
821 ClassDataItemIterator* it,
822 std::unordered_set<uint32_t>* direct_method_indexes,
823 bool* have_class,
824 uint16_t* class_type_index,
825 uint32_t* class_access_flags) {
826 uint32_t prev_index = 0;
827 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
828 uint32_t curr_index = it->GetMemberIndex();
829 if (!CheckOrderAndGetClassFlags(false,
830 kDirect ? "direct method" : "virtual method",
831 curr_index,
832 prev_index,
833 have_class,
834 class_type_index,
835 class_access_flags)) {
836 return false;
837 }
838 prev_index = curr_index;
839
840 if (!CheckClassDataItemMethod(curr_index,
841 it->GetRawMemberAccessFlags(),
842 *class_access_flags,
843 *class_type_index,
844 it->GetMethodCodeItemOffset(),
845 direct_method_indexes,
846 kDirect)) {
847 return false;
848 }
849 }
850
851 return true;
852}
853
jeffhao10037c82012-01-23 15:06:23 -0800854bool DexFileVerifier::CheckIntraClassDataItem() {
855 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -0700856 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -0800857
Andreas Gampee6215c02015-08-31 18:54:38 -0700858 // This code is complicated by the fact that we don't directly know which class this belongs to.
859 // So we need to explicitly search with the first item we find (either field or method), and then,
860 // as the lookup is expensive, cache the result.
861 bool have_class = false;
862 uint16_t class_type_index;
863 uint32_t class_access_flags;
864
865 // Check fields.
866 if (!CheckIntraClassDataItemFields<true>(&it,
867 &have_class,
868 &class_type_index,
869 &class_access_flags)) {
870 return false;
jeffhao10037c82012-01-23 15:06:23 -0800871 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700872 if (!CheckIntraClassDataItemFields<false>(&it,
873 &have_class,
874 &class_type_index,
875 &class_access_flags)) {
876 return false;
jeffhao10037c82012-01-23 15:06:23 -0800877 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700878
879 // Check methods.
880 if (!CheckIntraClassDataItemMethods<true>(&it,
881 &direct_method_indexes,
882 &have_class,
883 &class_type_index,
884 &class_access_flags)) {
885 return false;
jeffhao10037c82012-01-23 15:06:23 -0800886 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700887 if (!CheckIntraClassDataItemMethods<false>(&it,
888 &direct_method_indexes,
889 &have_class,
890 &class_type_index,
891 &class_access_flags)) {
892 return false;
jeffhao10037c82012-01-23 15:06:23 -0800893 }
894
895 ptr_ = it.EndDataPointer();
896 return true;
897}
898
899bool DexFileVerifier::CheckIntraCodeItem() {
900 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700901 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -0800902 return false;
903 }
904
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700905 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
906 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
907 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800908 return false;
909 }
910
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700911 if (UNLIKELY((code_item->outs_size_ > 5) &&
912 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -0800913 /*
914 * outs_size can be up to 5, even if registers_size is smaller, since the
915 * short forms of method invocation allow repetitions of a register multiple
916 * times within a single parameter list. However, longer parameter lists
917 * need to be represented in-order in the register file.
918 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700919 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
920 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800921 return false;
922 }
923
924 const uint16_t* insns = code_item->insns_;
925 uint32_t insns_size = code_item->insns_size_in_code_units_;
926 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
927 return false;
928 }
929
930 // Grab the end of the insns if there are no try_items.
931 uint32_t try_items_size = code_item->tries_size_;
932 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -0700933 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -0800934 return true;
935 }
936
937 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800938 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700939 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -0800940 return false;
941 }
942
943 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800944 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
945 return false;
946 }
947
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -0500948 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
949 uint32_t handlers_size = DecodeUnsignedLeb128(&ptr_);
950
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700951 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
952 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -0800953 return false;
954 }
955
Ian Rogers700a4022014-05-19 16:49:03 -0700956 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -0700957 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -0800958 return false;
959 }
960
961 uint32_t last_addr = 0;
962 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700963 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
964 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -0800965 return false;
966 }
967
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700968 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
969 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -0800970 return false;
971 }
972
973 uint32_t i;
974 for (i = 0; i < handlers_size; i++) {
975 if (try_items->handler_off_ == handler_offsets[i]) {
976 break;
977 }
978 }
979
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700980 if (UNLIKELY(i == handlers_size)) {
981 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -0800982 return false;
983 }
984
985 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700986 if (UNLIKELY(last_addr > insns_size)) {
987 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -0800988 return false;
989 }
990
991 try_items++;
992 }
993
994 return true;
995}
996
997bool DexFileVerifier::CheckIntraStringDataItem() {
998 uint32_t size = DecodeUnsignedLeb128(&ptr_);
Ian Rogers13735952014-10-08 12:43:28 -0700999 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001000
1001 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001002 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001003 if (UNLIKELY(ptr_ >= file_end)) {
1004 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001005 return false;
1006 }
1007
1008 uint8_t byte = *(ptr_++);
1009
1010 // Switch on the high 4 bits.
1011 switch (byte >> 4) {
1012 case 0x00:
1013 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001014 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001015 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001016 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001017 return false;
1018 }
1019 break;
1020 case 0x01:
1021 case 0x02:
1022 case 0x03:
1023 case 0x04:
1024 case 0x05:
1025 case 0x06:
1026 case 0x07:
1027 // No extra checks necessary for bit pattern 0xxx.
1028 break;
1029 case 0x08:
1030 case 0x09:
1031 case 0x0a:
1032 case 0x0b:
1033 case 0x0f:
1034 // Illegal bit patterns 10xx or 1111.
1035 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001036 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001037 return false;
1038 case 0x0c:
1039 case 0x0d: {
1040 // Bit pattern 110x has an additional byte.
1041 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001042 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1043 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001044 return false;
1045 }
1046 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001047 if (UNLIKELY((value != 0) && (value < 0x80))) {
1048 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001049 return false;
1050 }
1051 break;
1052 }
1053 case 0x0e: {
1054 // Bit pattern 1110 has 2 additional bytes.
1055 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001056 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1057 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001058 return false;
1059 }
1060 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001061 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1062 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001063 return false;
1064 }
1065 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001066 if (UNLIKELY(value < 0x800)) {
1067 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001068 return false;
1069 }
1070 break;
1071 }
1072 }
1073 }
1074
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001075 if (UNLIKELY(*(ptr_++) != '\0')) {
1076 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001077 return false;
1078 }
1079
1080 return true;
1081}
1082
1083bool DexFileVerifier::CheckIntraDebugInfoItem() {
1084 DecodeUnsignedLeb128(&ptr_);
1085 uint32_t parameters_size = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001086 if (UNLIKELY(parameters_size > 65536)) {
1087 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001088 return false;
1089 }
1090
1091 for (uint32_t j = 0; j < parameters_size; j++) {
1092 uint32_t parameter_name = DecodeUnsignedLeb128(&ptr_);
1093 if (parameter_name != 0) {
1094 parameter_name--;
1095 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1096 return false;
1097 }
1098 }
1099 }
1100
1101 while (true) {
1102 uint8_t opcode = *(ptr_++);
1103 switch (opcode) {
1104 case DexFile::DBG_END_SEQUENCE: {
1105 return true;
1106 }
1107 case DexFile::DBG_ADVANCE_PC: {
1108 DecodeUnsignedLeb128(&ptr_);
1109 break;
1110 }
1111 case DexFile::DBG_ADVANCE_LINE: {
1112 DecodeSignedLeb128(&ptr_);
1113 break;
1114 }
1115 case DexFile::DBG_START_LOCAL: {
1116 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001117 if (UNLIKELY(reg_num >= 65536)) {
1118 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001119 return false;
1120 }
1121 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1122 if (name_idx != 0) {
1123 name_idx--;
1124 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1125 return false;
1126 }
1127 }
1128 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
1129 if (type_idx != 0) {
1130 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001131 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001132 return false;
1133 }
1134 }
1135 break;
1136 }
1137 case DexFile::DBG_END_LOCAL:
1138 case DexFile::DBG_RESTART_LOCAL: {
1139 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001140 if (UNLIKELY(reg_num >= 65536)) {
1141 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001142 return false;
1143 }
1144 break;
1145 }
1146 case DexFile::DBG_START_LOCAL_EXTENDED: {
1147 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001148 if (UNLIKELY(reg_num >= 65536)) {
1149 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001150 return false;
1151 }
1152 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1153 if (name_idx != 0) {
1154 name_idx--;
1155 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1156 return false;
1157 }
1158 }
1159 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
1160 if (type_idx != 0) {
1161 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001162 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001163 return false;
1164 }
1165 }
1166 uint32_t sig_idx = DecodeUnsignedLeb128(&ptr_);
1167 if (sig_idx != 0) {
1168 sig_idx--;
1169 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1170 return false;
1171 }
1172 }
1173 break;
1174 }
1175 case DexFile::DBG_SET_FILE: {
1176 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1177 if (name_idx != 0) {
1178 name_idx--;
1179 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1180 return false;
1181 }
1182 }
1183 break;
1184 }
1185 }
1186 }
1187}
1188
1189bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001190 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001191 return false;
1192 }
1193
1194 // Check visibility
1195 switch (*(ptr_++)) {
1196 case DexFile::kDexVisibilityBuild:
1197 case DexFile::kDexVisibilityRuntime:
1198 case DexFile::kDexVisibilitySystem:
1199 break;
1200 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001201 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001202 return false;
1203 }
1204
1205 if (!CheckEncodedAnnotation()) {
1206 return false;
1207 }
1208
1209 return true;
1210}
1211
1212bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1213 const DexFile::AnnotationsDirectoryItem* item =
1214 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001215 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001216 return false;
1217 }
1218
1219 // Field annotations follow immediately after the annotations directory.
1220 const DexFile::FieldAnnotationsItem* field_item =
1221 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1222 uint32_t field_count = item->fields_size_;
1223 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1224 return false;
1225 }
1226
1227 uint32_t last_idx = 0;
1228 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001229 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1230 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001231 return false;
1232 }
1233 last_idx = field_item->field_idx_;
1234 field_item++;
1235 }
1236
1237 // Method annotations follow immediately after field annotations.
1238 const DexFile::MethodAnnotationsItem* method_item =
1239 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1240 uint32_t method_count = item->methods_size_;
1241 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1242 return false;
1243 }
1244
1245 last_idx = 0;
1246 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001247 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1248 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1249 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001250 return false;
1251 }
1252 last_idx = method_item->method_idx_;
1253 method_item++;
1254 }
1255
1256 // Parameter annotations follow immediately after method annotations.
1257 const DexFile::ParameterAnnotationsItem* parameter_item =
1258 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1259 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001260 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001261 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001262 return false;
1263 }
1264
1265 last_idx = 0;
1266 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001267 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1268 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1269 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001270 return false;
1271 }
1272 last_idx = parameter_item->method_idx_;
1273 parameter_item++;
1274 }
1275
1276 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001277 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001278 return true;
1279}
1280
Andreas Gampeb061cc12014-09-02 10:22:20 -07001281bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
1282 uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001283 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001284 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001285 switch (type) {
1286 case DexFile::kDexTypeClassDataItem:
1287 case DexFile::kDexTypeStringDataItem:
1288 case DexFile::kDexTypeDebugInfoItem:
1289 case DexFile::kDexTypeAnnotationItem:
1290 case DexFile::kDexTypeEncodedArrayItem:
1291 alignment_mask = sizeof(uint8_t) - 1;
1292 break;
1293 default:
1294 alignment_mask = sizeof(uint32_t) - 1;
1295 break;
1296 }
1297
1298 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001299 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001300 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001301
1302 // Check the padding between items.
1303 if (!CheckPadding(offset, aligned_offset)) {
1304 return false;
1305 }
1306
1307 // Check depending on the section type.
1308 switch (type) {
1309 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001310 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001311 return false;
1312 }
1313 ptr_ += sizeof(DexFile::StringId);
1314 break;
1315 }
1316 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001317 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001318 return false;
1319 }
1320 ptr_ += sizeof(DexFile::TypeId);
1321 break;
1322 }
1323 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001324 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001325 return false;
1326 }
1327 ptr_ += sizeof(DexFile::ProtoId);
1328 break;
1329 }
1330 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001331 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001332 return false;
1333 }
1334 ptr_ += sizeof(DexFile::FieldId);
1335 break;
1336 }
1337 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001338 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001339 return false;
1340 }
1341 ptr_ += sizeof(DexFile::MethodId);
1342 break;
1343 }
1344 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001345 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001346 return false;
1347 }
1348 ptr_ += sizeof(DexFile::ClassDef);
1349 break;
1350 }
1351 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001352 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001353 return false;
1354 }
jeffhao10037c82012-01-23 15:06:23 -08001355 break;
1356 }
1357 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001358 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001359 return false;
1360 }
jeffhao10037c82012-01-23 15:06:23 -08001361 break;
1362 }
1363 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001364 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001365 return false;
1366 }
jeffhao10037c82012-01-23 15:06:23 -08001367 break;
1368 }
1369 case DexFile::kDexTypeClassDataItem: {
1370 if (!CheckIntraClassDataItem()) {
1371 return false;
1372 }
1373 break;
1374 }
1375 case DexFile::kDexTypeCodeItem: {
1376 if (!CheckIntraCodeItem()) {
1377 return false;
1378 }
1379 break;
1380 }
1381 case DexFile::kDexTypeStringDataItem: {
1382 if (!CheckIntraStringDataItem()) {
1383 return false;
1384 }
1385 break;
1386 }
1387 case DexFile::kDexTypeDebugInfoItem: {
1388 if (!CheckIntraDebugInfoItem()) {
1389 return false;
1390 }
1391 break;
1392 }
1393 case DexFile::kDexTypeAnnotationItem: {
1394 if (!CheckIntraAnnotationItem()) {
1395 return false;
1396 }
1397 break;
1398 }
1399 case DexFile::kDexTypeEncodedArrayItem: {
1400 if (!CheckEncodedArray()) {
1401 return false;
1402 }
1403 break;
1404 }
1405 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1406 if (!CheckIntraAnnotationsDirectoryItem()) {
1407 return false;
1408 }
1409 break;
1410 }
1411 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001412 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001413 return false;
1414 }
1415
1416 if (IsDataSectionType(type)) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07001417 offset_to_type_map_.Put(aligned_offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001418 }
1419
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001420 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001421 if (UNLIKELY(aligned_offset > size_)) {
1422 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001423 return false;
1424 }
1425
1426 offset = aligned_offset;
1427 }
1428
1429 return true;
1430}
1431
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001432bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001433 uint32_t expected_offset;
1434 uint32_t expected_size;
1435
1436 // Get the expected offset and size from the header.
1437 switch (type) {
1438 case DexFile::kDexTypeStringIdItem:
1439 expected_offset = header_->string_ids_off_;
1440 expected_size = header_->string_ids_size_;
1441 break;
1442 case DexFile::kDexTypeTypeIdItem:
1443 expected_offset = header_->type_ids_off_;
1444 expected_size = header_->type_ids_size_;
1445 break;
1446 case DexFile::kDexTypeProtoIdItem:
1447 expected_offset = header_->proto_ids_off_;
1448 expected_size = header_->proto_ids_size_;
1449 break;
1450 case DexFile::kDexTypeFieldIdItem:
1451 expected_offset = header_->field_ids_off_;
1452 expected_size = header_->field_ids_size_;
1453 break;
1454 case DexFile::kDexTypeMethodIdItem:
1455 expected_offset = header_->method_ids_off_;
1456 expected_size = header_->method_ids_size_;
1457 break;
1458 case DexFile::kDexTypeClassDefItem:
1459 expected_offset = header_->class_defs_off_;
1460 expected_size = header_->class_defs_size_;
1461 break;
1462 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001463 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001464 return false;
1465 }
1466
1467 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001468 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001469 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001470 return false;
1471 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001472 if (UNLIKELY(count != expected_size)) {
1473 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001474 return false;
1475 }
1476
1477 return CheckIntraSectionIterate(offset, count, type);
1478}
1479
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001480bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count, uint16_t type) {
1481 size_t data_start = header_->data_off_;
1482 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001483
1484 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001485 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001486 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001487 return false;
1488 }
1489
1490 if (!CheckIntraSectionIterate(offset, count, type)) {
1491 return false;
1492 }
1493
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001494 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001495 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001496 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001497 return false;
1498 }
1499
1500 return true;
1501}
1502
1503bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001504 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001505 const DexFile::MapItem* item = map->list_;
1506
1507 uint32_t count = map->size_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001508 size_t offset = 0;
Ian Rogers30fab402012-01-23 15:43:46 -08001509 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001510
1511 // Check the items listed in the map.
1512 while (count--) {
1513 uint32_t section_offset = item->offset_;
1514 uint32_t section_count = item->size_;
1515 uint16_t type = item->type_;
1516
1517 // Check for padding and overlap between items.
1518 if (!CheckPadding(offset, section_offset)) {
1519 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001520 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001521 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001522 return false;
1523 }
1524
1525 // Check each item based on its type.
1526 switch (type) {
1527 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001528 if (UNLIKELY(section_count != 1)) {
1529 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001530 return false;
1531 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001532 if (UNLIKELY(section_offset != 0)) {
1533 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001534 return false;
1535 }
Ian Rogers30fab402012-01-23 15:43:46 -08001536 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001537 offset = header_->header_size_;
1538 break;
1539 case DexFile::kDexTypeStringIdItem:
1540 case DexFile::kDexTypeTypeIdItem:
1541 case DexFile::kDexTypeProtoIdItem:
1542 case DexFile::kDexTypeFieldIdItem:
1543 case DexFile::kDexTypeMethodIdItem:
1544 case DexFile::kDexTypeClassDefItem:
1545 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1546 return false;
1547 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001548 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001549 break;
1550 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001551 if (UNLIKELY(section_count != 1)) {
1552 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001553 return false;
1554 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001555 if (UNLIKELY(section_offset != header_->map_off_)) {
1556 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1557 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001558 return false;
1559 }
1560 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1561 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1562 break;
1563 case DexFile::kDexTypeTypeList:
1564 case DexFile::kDexTypeAnnotationSetRefList:
1565 case DexFile::kDexTypeAnnotationSetItem:
1566 case DexFile::kDexTypeClassDataItem:
1567 case DexFile::kDexTypeCodeItem:
1568 case DexFile::kDexTypeStringDataItem:
1569 case DexFile::kDexTypeDebugInfoItem:
1570 case DexFile::kDexTypeAnnotationItem:
1571 case DexFile::kDexTypeEncodedArrayItem:
1572 case DexFile::kDexTypeAnnotationsDirectoryItem:
1573 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1574 return false;
1575 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001576 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001577 break;
1578 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001579 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001580 return false;
1581 }
1582
1583 item++;
1584 }
1585
1586 return true;
1587}
1588
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001589bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001590 auto it = offset_to_type_map_.find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001591 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001592 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001593 return false;
1594 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001595 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001596 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001597 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001598 return false;
1599 }
1600 return true;
1601}
1602
Ian Rogers13735952014-10-08 12:43:28 -07001603uint16_t DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001604 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001605 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001606
1607 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001608 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
1609 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001610 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001611 }
1612
1613 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001614 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
1615 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001616 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001617 }
1618
1619 return DexFile::kDexNoIndex16;
1620}
1621
Ian Rogers13735952014-10-08 12:43:28 -07001622uint16_t DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001623 const DexFile::AnnotationsDirectoryItem* item =
1624 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001625 *success = true;
1626
jeffhao10037c82012-01-23 15:06:23 -08001627 if (item->fields_size_ != 0) {
1628 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001629 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
1630 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001631 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001632 }
1633
1634 if (item->methods_size_ != 0) {
1635 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001636 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001637 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001638 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001639 }
1640
1641 if (item->parameters_size_ != 0) {
1642 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001643 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001644 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001645 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001646 }
1647
1648 return DexFile::kDexNoIndex16;
1649}
1650
1651bool DexFileVerifier::CheckInterStringIdItem() {
1652 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1653
1654 // Check the map to make sure it has the right offset->type.
1655 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1656 return false;
1657 }
1658
1659 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001660 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001661 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1662 const char* prev_str = dex_file_->GetStringData(*prev_item);
1663 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001664 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1665 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001666 return false;
1667 }
1668 }
1669
1670 ptr_ += sizeof(DexFile::StringId);
1671 return true;
1672}
1673
1674bool DexFileVerifier::CheckInterTypeIdItem() {
1675 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001676
1677 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001678
1679 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001680 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1681 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001682 return false;
1683 }
1684
1685 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001686 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001687 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001688 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1689 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
1690 prev_item->descriptor_idx_, item->descriptor_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001691 return false;
1692 }
1693 }
1694
1695 ptr_ += sizeof(DexFile::TypeId);
1696 return true;
1697}
1698
1699bool DexFileVerifier::CheckInterProtoIdItem() {
1700 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001701
1702 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1703
jeffhao10037c82012-01-23 15:06:23 -08001704 if (item->parameters_off_ != 0 &&
1705 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1706 return false;
1707 }
1708
1709 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001710 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1711 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001712 return false;
1713 }
1714 shorty++;
1715
1716 DexFileParameterIterator it(*dex_file_, *item);
1717 while (it.HasNext() && *shorty != '\0') {
Andreas Gampebb836e12014-06-13 15:31:40 -07001718 if (!CheckIndex(it.GetTypeIdx(), dex_file_->NumTypeIds(),
1719 "inter_proto_id_item shorty type_idx")) {
1720 return false;
1721 }
jeffhao10037c82012-01-23 15:06:23 -08001722 const char* descriptor = it.GetDescriptor();
1723 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1724 return false;
1725 }
1726 it.Next();
1727 shorty++;
1728 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001729 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1730 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001731 return false;
1732 }
1733
1734 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001735 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001736 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001737 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1738 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001739 return false;
1740 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1741 DexFileParameterIterator curr_it(*dex_file_, *item);
1742 DexFileParameterIterator prev_it(*dex_file_, *prev);
1743
1744 while (curr_it.HasNext() && prev_it.HasNext()) {
1745 uint16_t prev_idx = prev_it.GetTypeIdx();
1746 uint16_t curr_idx = curr_it.GetTypeIdx();
1747 if (prev_idx == DexFile::kDexNoIndex16) {
1748 break;
1749 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001750 if (UNLIKELY(curr_idx == DexFile::kDexNoIndex16)) {
1751 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001752 return false;
1753 }
1754
1755 if (prev_idx < curr_idx) {
1756 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001757 } else if (UNLIKELY(prev_idx > curr_idx)) {
1758 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001759 return false;
1760 }
1761
1762 prev_it.Next();
1763 curr_it.Next();
1764 }
1765 }
1766 }
1767
1768 ptr_ += sizeof(DexFile::ProtoId);
1769 return true;
1770}
1771
1772bool DexFileVerifier::CheckInterFieldIdItem() {
1773 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1774
1775 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001776 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1777 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1778 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001779 return false;
1780 }
1781
1782 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001783 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1784 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1785 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001786 return false;
1787 }
1788
1789 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001790 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001791 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1792 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001793 return false;
1794 }
1795
1796 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001797 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001798 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001799 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1800 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001801 return false;
1802 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001803 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1804 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001805 return false;
1806 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001807 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
1808 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001809 return false;
1810 }
1811 }
1812 }
1813 }
1814
1815 ptr_ += sizeof(DexFile::FieldId);
1816 return true;
1817}
1818
1819bool DexFileVerifier::CheckInterMethodIdItem() {
1820 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
1821
1822 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001823 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
1824 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
1825 class_descriptor[0] != '['))) {
1826 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001827 return false;
1828 }
1829
1830 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07001831 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001832 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1833 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001834 return false;
1835 }
1836
Andreas Gampedf10b322014-06-11 21:46:05 -07001837 // Check that the proto id is valid.
1838 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
1839 "inter_method_id_item proto_idx"))) {
1840 return false;
1841 }
1842
jeffhao10037c82012-01-23 15:06:23 -08001843 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001844 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001845 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001846 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1847 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001848 return false;
1849 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001850 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1851 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001852 return false;
1853 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001854 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
1855 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001856 return false;
1857 }
1858 }
1859 }
1860 }
1861
1862 ptr_ += sizeof(DexFile::MethodId);
1863 return true;
1864}
1865
1866bool DexFileVerifier::CheckInterClassDefItem() {
1867 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001868
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001869 // Check for duplicate class def.
1870 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
1871 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_);
1872 return false;
1873 }
1874 defined_classes_.insert(item->class_idx_);
1875
Andreas Gampee09269c2014-06-06 18:45:35 -07001876 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
1877 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1878 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001879 return false;
1880 }
1881
Andreas Gampeacc2bb62014-07-17 19:26:50 -07001882 // Only allow non-runtime modifiers.
1883 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
1884 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
1885 return false;
1886 }
1887
jeffhao10037c82012-01-23 15:06:23 -08001888 if (item->interfaces_off_ != 0 &&
1889 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
1890 return false;
1891 }
1892 if (item->annotations_off_ != 0 &&
1893 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
1894 return false;
1895 }
1896 if (item->class_data_off_ != 0 &&
1897 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
1898 return false;
1899 }
1900 if (item->static_values_off_ != 0 &&
1901 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
1902 return false;
1903 }
1904
1905 if (item->superclass_idx_ != DexFile::kDexNoIndex16) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001906 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
1907 "inter_class_def_item superclass_idx")
1908 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
1909 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001910 return false;
1911 }
1912 }
1913
1914 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001915 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001916 uint32_t size = interfaces->Size();
1917
1918 // Ensure that all interfaces refer to classes (not arrays or primitives).
1919 for (uint32_t i = 0; i < size; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001920 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
1921 "inter_class_def_item interface type_idx")
1922 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
1923 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001924 return false;
1925 }
1926 }
1927
1928 /*
1929 * Ensure that there are no duplicates. This is an O(N^2) test, but in
1930 * practice the number of interfaces implemented by any given class is low.
1931 */
1932 for (uint32_t i = 1; i < size; i++) {
1933 uint32_t idx1 = interfaces->GetTypeItem(i).type_idx_;
1934 for (uint32_t j =0; j < i; j++) {
1935 uint32_t idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001936 if (UNLIKELY(idx1 == idx2)) {
1937 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08001938 return false;
1939 }
1940 }
1941 }
1942 }
1943
1944 // Check that references in class_data_item are to the right class.
1945 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001946 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001947 bool success;
1948 uint16_t data_definer = FindFirstClassDataDefiner(data, &success);
1949 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001950 return false;
1951 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001952 if (UNLIKELY((data_definer != item->class_idx_) && (data_definer != DexFile::kDexNoIndex16))) {
1953 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08001954 return false;
1955 }
1956 }
1957
1958 // Check that references in annotations_directory_item are to right class.
1959 if (item->annotations_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001960 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001961 bool success;
1962 uint16_t annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
1963 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001964 return false;
1965 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001966 if (UNLIKELY((annotations_definer != item->class_idx_) &&
1967 (annotations_definer != DexFile::kDexNoIndex16))) {
1968 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08001969 return false;
1970 }
1971 }
1972
1973 ptr_ += sizeof(DexFile::ClassDef);
1974 return true;
1975}
1976
1977bool DexFileVerifier::CheckInterAnnotationSetRefList() {
1978 const DexFile::AnnotationSetRefList* list =
1979 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
1980 const DexFile::AnnotationSetRefItem* item = list->list_;
1981 uint32_t count = list->size_;
1982
1983 while (count--) {
1984 if (item->annotations_off_ != 0 &&
1985 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
1986 return false;
1987 }
1988 item++;
1989 }
1990
Ian Rogers13735952014-10-08 12:43:28 -07001991 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08001992 return true;
1993}
1994
1995bool DexFileVerifier::CheckInterAnnotationSetItem() {
1996 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
1997 const uint32_t* offsets = set->entries_;
1998 uint32_t count = set->size_;
1999 uint32_t last_idx = 0;
2000
2001 for (uint32_t i = 0; i < count; i++) {
2002 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2003 return false;
2004 }
2005
2006 // Get the annotation from the offset and the type index for the annotation.
2007 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002008 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002009 const uint8_t* data = annotation->annotation_;
2010 uint32_t idx = DecodeUnsignedLeb128(&data);
2011
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002012 if (UNLIKELY(last_idx >= idx && i != 0)) {
2013 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002014 return false;
2015 }
2016
2017 last_idx = idx;
2018 offsets++;
2019 }
2020
Ian Rogers13735952014-10-08 12:43:28 -07002021 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002022 return true;
2023}
2024
2025bool DexFileVerifier::CheckInterClassDataItem() {
2026 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002027 bool success;
2028 uint16_t defining_class = FindFirstClassDataDefiner(ptr_, &success);
2029 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002030 return false;
2031 }
jeffhao10037c82012-01-23 15:06:23 -08002032
2033 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002034 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002035 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002036 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002037 return false;
2038 }
2039 }
2040 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2041 uint32_t code_off = it.GetMethodCodeItemOffset();
2042 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2043 return false;
2044 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002045 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002046 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002047 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002048 return false;
2049 }
2050 }
2051
2052 ptr_ = it.EndDataPointer();
2053 return true;
2054}
2055
2056bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2057 const DexFile::AnnotationsDirectoryItem* item =
2058 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002059 bool success;
2060 uint16_t defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
2061 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002062 return false;
2063 }
jeffhao10037c82012-01-23 15:06:23 -08002064
2065 if (item->class_annotations_off_ != 0 &&
2066 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2067 return false;
2068 }
2069
2070 // Field annotations follow immediately after the annotations directory.
2071 const DexFile::FieldAnnotationsItem* field_item =
2072 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2073 uint32_t field_count = item->fields_size_;
2074 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002075 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2076 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002077 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002078 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002079 return false;
2080 }
2081 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2082 return false;
2083 }
2084 field_item++;
2085 }
2086
2087 // Method annotations follow immediately after field annotations.
2088 const DexFile::MethodAnnotationsItem* method_item =
2089 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2090 uint32_t method_count = item->methods_size_;
2091 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002092 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002093 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002094 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002095 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002096 return false;
2097 }
2098 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2099 return false;
2100 }
2101 method_item++;
2102 }
2103
2104 // Parameter annotations follow immediately after method annotations.
2105 const DexFile::ParameterAnnotationsItem* parameter_item =
2106 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2107 uint32_t parameter_count = item->parameters_size_;
2108 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002109 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002110 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002111 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002112 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002113 return false;
2114 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002115 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2116 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002117 return false;
2118 }
2119 parameter_item++;
2120 }
2121
Ian Rogers13735952014-10-08 12:43:28 -07002122 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002123 return true;
2124}
2125
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002126bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002127 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002128 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002129 switch (type) {
2130 case DexFile::kDexTypeClassDataItem:
2131 alignment_mask = sizeof(uint8_t) - 1;
2132 break;
2133 default:
2134 alignment_mask = sizeof(uint32_t) - 1;
2135 break;
2136 }
2137
2138 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002139 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002140 for (uint32_t i = 0; i < count; i++) {
2141 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002142 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002143 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002144
2145 // Check depending on the section type.
2146 switch (type) {
2147 case DexFile::kDexTypeStringIdItem: {
2148 if (!CheckInterStringIdItem()) {
2149 return false;
2150 }
2151 break;
2152 }
2153 case DexFile::kDexTypeTypeIdItem: {
2154 if (!CheckInterTypeIdItem()) {
2155 return false;
2156 }
2157 break;
2158 }
2159 case DexFile::kDexTypeProtoIdItem: {
2160 if (!CheckInterProtoIdItem()) {
2161 return false;
2162 }
2163 break;
2164 }
2165 case DexFile::kDexTypeFieldIdItem: {
2166 if (!CheckInterFieldIdItem()) {
2167 return false;
2168 }
2169 break;
2170 }
2171 case DexFile::kDexTypeMethodIdItem: {
2172 if (!CheckInterMethodIdItem()) {
2173 return false;
2174 }
2175 break;
2176 }
2177 case DexFile::kDexTypeClassDefItem: {
2178 if (!CheckInterClassDefItem()) {
2179 return false;
2180 }
2181 break;
2182 }
2183 case DexFile::kDexTypeAnnotationSetRefList: {
2184 if (!CheckInterAnnotationSetRefList()) {
2185 return false;
2186 }
2187 break;
2188 }
2189 case DexFile::kDexTypeAnnotationSetItem: {
2190 if (!CheckInterAnnotationSetItem()) {
2191 return false;
2192 }
2193 break;
2194 }
2195 case DexFile::kDexTypeClassDataItem: {
2196 if (!CheckInterClassDataItem()) {
2197 return false;
2198 }
2199 break;
2200 }
2201 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2202 if (!CheckInterAnnotationsDirectoryItem()) {
2203 return false;
2204 }
2205 break;
2206 }
2207 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002208 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002209 return false;
2210 }
2211
2212 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002213 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002214 }
2215
2216 return true;
2217}
2218
2219bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002220 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002221 const DexFile::MapItem* item = map->list_;
2222 uint32_t count = map->size_;
2223
2224 // Cross check the items listed in the map.
2225 while (count--) {
2226 uint32_t section_offset = item->offset_;
2227 uint32_t section_count = item->size_;
2228 uint16_t type = item->type_;
2229
2230 switch (type) {
2231 case DexFile::kDexTypeHeaderItem:
2232 case DexFile::kDexTypeMapList:
2233 case DexFile::kDexTypeTypeList:
2234 case DexFile::kDexTypeCodeItem:
2235 case DexFile::kDexTypeStringDataItem:
2236 case DexFile::kDexTypeDebugInfoItem:
2237 case DexFile::kDexTypeAnnotationItem:
2238 case DexFile::kDexTypeEncodedArrayItem:
2239 break;
2240 case DexFile::kDexTypeStringIdItem:
2241 case DexFile::kDexTypeTypeIdItem:
2242 case DexFile::kDexTypeProtoIdItem:
2243 case DexFile::kDexTypeFieldIdItem:
2244 case DexFile::kDexTypeMethodIdItem:
2245 case DexFile::kDexTypeClassDefItem:
2246 case DexFile::kDexTypeAnnotationSetRefList:
2247 case DexFile::kDexTypeAnnotationSetItem:
2248 case DexFile::kDexTypeClassDataItem:
2249 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2250 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2251 return false;
2252 }
2253 break;
2254 }
2255 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002256 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002257 return false;
2258 }
2259
2260 item++;
2261 }
2262
2263 return true;
2264}
2265
2266bool DexFileVerifier::Verify() {
2267 // Check the header.
2268 if (!CheckHeader()) {
2269 return false;
2270 }
2271
2272 // Check the map section.
2273 if (!CheckMap()) {
2274 return false;
2275 }
2276
2277 // Check structure within remaining sections.
2278 if (!CheckIntraSection()) {
2279 return false;
2280 }
2281
2282 // Check references from one section to another.
2283 if (!CheckInterSection()) {
2284 return false;
2285 }
2286
2287 return true;
2288}
2289
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002290void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2291 va_list ap;
2292 va_start(ap, fmt);
2293 DCHECK(failure_reason_.empty()) << failure_reason_;
2294 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2295 StringAppendV(&failure_reason_, fmt, ap);
2296 va_end(ap);
2297}
2298
Andreas Gampee6215c02015-08-31 18:54:38 -07002299// Fields and methods may have only one of public/protected/private.
2300static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2301 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2302 (((flags & kAccProtected) == 0) ? 0 : 1) +
2303 (((flags & kAccPrivate) == 0) ? 0 : 1);
2304 return count <= 1;
2305}
2306
2307bool DexFileVerifier::CheckFieldAccessFlags(uint32_t field_access_flags,
2308 uint32_t class_access_flags,
2309 std::string* error_msg) {
2310 // Generally sort out >16-bit flags.
2311 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
2312 *error_msg = StringPrintf("Bad class_data_item field access_flags %x", field_access_flags);
2313 return false;
2314 }
2315
2316 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2317 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2318 kAccPrivate |
2319 kAccProtected |
2320 kAccStatic |
2321 kAccFinal |
2322 kAccVolatile |
2323 kAccTransient |
2324 kAccSynthetic |
2325 kAccEnum;
2326
2327 // Fields may have only one of public/protected/final.
2328 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
2329 *error_msg = StringPrintf("Field may have only one of public/protected/private, %x",
2330 field_access_flags);
2331 return false;
2332 }
2333
2334 // Interfaces have a pretty restricted list.
2335 if ((class_access_flags & kAccInterface) != 0) {
2336 // Interface fields must be public final static.
2337 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2338 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
2339 *error_msg = StringPrintf("Interface field is not public final static: %x",
2340 field_access_flags);
2341 return false;
2342 }
2343 // Interface fields may be synthetic, but may not have other flags.
2344 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2345 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
2346 *error_msg = StringPrintf("Interface field has disallowed flag: %x", field_access_flags);
2347 return false;
2348 }
2349 return true;
2350 }
2351
2352 // Volatile fields may not be final.
2353 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2354 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
2355 *error_msg = "Fields may not be volatile and final";
2356 return false;
2357 }
2358
2359 return true;
2360}
2361
2362// Try to find the name of the method with the given index. We do not want to rely on DexFile
2363// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
2364// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
2365// (flagged by the return value), otherwise error_msg will contain an error string.
2366static bool FindMethodName(uint32_t method_index,
2367 const uint8_t* begin,
2368 const DexFile::Header* header,
2369 const char** str,
2370 std::string* error_msg) {
2371 if (method_index >= header->method_ids_size_) {
2372 *error_msg = "Method index not available for method flags verification";
2373 return false;
2374 }
2375 uint32_t string_idx =
2376 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
2377 method_index)->name_idx_;
2378 if (string_idx >= header->string_ids_size_) {
2379 *error_msg = "String index not available for method flags verification";
2380 return false;
2381 }
2382 uint32_t string_off =
2383 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
2384 string_data_off_;
2385 if (string_off >= header->file_size_) {
2386 *error_msg = "String offset out of bounds for method flags verification";
2387 return false;
2388 }
2389 const uint8_t* str_data_ptr = begin + string_off;
2390 DecodeUnsignedLeb128(&str_data_ptr);
2391 *str = reinterpret_cast<const char*>(str_data_ptr);
2392 return true;
2393}
2394
2395bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2396 uint32_t method_access_flags,
2397 uint32_t class_access_flags,
2398 bool has_code,
2399 bool expect_direct,
2400 std::string* error_msg) {
2401 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2402 constexpr uint32_t kAllMethodFlags =
2403 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2404 if ((method_access_flags & ~kAllMethodFlags) != 0) {
2405 *error_msg = StringPrintf("Bad class_data_item method access_flags %x", method_access_flags);
2406 return false;
2407 }
2408
2409 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2410 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2411 kAccPrivate |
2412 kAccProtected |
2413 kAccStatic |
2414 kAccFinal |
2415 kAccSynthetic |
2416 kAccSynchronized |
2417 kAccBridge |
2418 kAccVarargs |
2419 kAccNative |
2420 kAccAbstract |
2421 kAccStrict;
2422
2423 // Methods may have only one of public/protected/final.
2424 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
2425 *error_msg = StringPrintf("Method may have only one of public/protected/private, %x",
2426 method_access_flags);
2427 return false;
2428 }
2429
2430 // Try to find the name, to check for constructor properties.
2431 const char* str;
2432 if (!FindMethodName(method_index, begin_, header_, &str, error_msg)) {
2433 return false;
2434 }
2435 bool is_init_by_name = false;
2436 constexpr const char* kInitName = "<init>";
2437 size_t str_offset = (reinterpret_cast<const uint8_t*>(str) - begin_);
2438 if (header_->file_size_ - str_offset >= sizeof(kInitName)) {
2439 is_init_by_name = strcmp(kInitName, str) == 0;
2440 }
2441 bool is_clinit_by_name = false;
2442 constexpr const char* kClinitName = "<clinit>";
2443 if (header_->file_size_ - str_offset >= sizeof(kClinitName)) {
2444 is_clinit_by_name = strcmp(kClinitName, str) == 0;
2445 }
2446 bool is_constructor = is_init_by_name || is_clinit_by_name;
2447
2448 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2449 // the reverse for backwards compatibility reasons.
2450 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor) {
2451 *error_msg = StringPrintf("Method %" PRIu32 " is marked constructor, but doesn't match name",
2452 method_index);
2453 return false;
2454 }
2455 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2456 // instance constructor is called "<init>".
2457 if (is_constructor) {
2458 bool is_static = (method_access_flags & kAccStatic) != 0;
2459 if (is_static ^ is_clinit_by_name) {
2460 *error_msg = StringPrintf("Constructor %" PRIu32 " is not flagged correctly wrt/ static.",
2461 method_index);
2462 return false;
2463 }
2464 }
2465 // Check that static and private methods, as well as constructors, are in the direct methods list,
2466 // and other methods in the virtual methods list.
2467 bool is_direct = (method_access_flags & (kAccStatic | kAccPrivate)) != 0 || is_constructor;
2468 if (is_direct != expect_direct) {
2469 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 " not in expected list %d",
2470 method_index,
2471 expect_direct);
2472 return false;
2473 }
2474
2475
2476 // From here on out it is easier to mask out the bits we're supposed to ignore.
2477 method_access_flags &= kMethodAccessFlags;
2478
2479 // If there aren't any instructions, make sure that's expected.
2480 if (!has_code) {
2481 // Only native or abstract methods may not have code.
2482 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
2483 *error_msg = StringPrintf("Method %" PRIu32 " has no code, but is not marked native or "
2484 "abstract",
2485 method_index);
2486 return false;
2487 }
2488 // Constructors must always have code.
2489 if (is_constructor) {
2490 *error_msg = StringPrintf("Constructor %u must not be abstract or native", method_index);
2491 return false;
2492 }
2493 if ((method_access_flags & kAccAbstract) != 0) {
2494 // Abstract methods are not allowed to have the following flags.
2495 constexpr uint32_t kForbidden =
2496 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2497 if ((method_access_flags & kForbidden) != 0) {
2498 *error_msg = StringPrintf("Abstract method %" PRIu32 " has disallowed access flags %x",
2499 method_index,
2500 method_access_flags);
2501 return false;
2502 }
2503 // Abstract methods must be in an abstract class or interface.
2504 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
2505 *error_msg = StringPrintf("Method %" PRIu32 " is abstract, but the declaring class "
2506 "is neither abstract nor an interface", method_index);
2507 return false;
2508 }
2509 }
2510 // Interfaces are special.
2511 if ((class_access_flags & kAccInterface) != 0) {
2512 // Interface methods must be public and abstract.
2513 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
2514 *error_msg = StringPrintf("Interface method %" PRIu32 " is not public and abstract",
2515 method_index);
2516 return false;
2517 }
2518 // At this point, we know the method is public and abstract. This means that all the checks
2519 // for invalid combinations above applies. In addition, interface methods must not be
2520 // protected. This is caught by the check for only-one-of-public-protected-private.
2521 }
2522 return true;
2523 }
2524
2525 // When there's code, the method must not be native or abstract.
2526 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
2527 *error_msg = StringPrintf("Method %" PRIu32 " has code, but is marked native or abstract",
2528 method_index);
2529 return false;
2530 }
2531
2532 // Only the static initializer may have code in an interface.
2533 if (((class_access_flags & kAccInterface) != 0) && !is_clinit_by_name) {
2534 *error_msg = StringPrintf("Non-clinit interface method %" PRIu32 " should not have code",
2535 method_index);
2536 return false;
2537 }
2538
2539 // Instance constructors must not be synchronized and a few other flags.
2540 if (is_init_by_name) {
2541 static constexpr uint32_t kInitAllowed =
2542 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2543 if ((method_access_flags & ~kInitAllowed) != 0) {
2544 *error_msg = StringPrintf("Constructor %" PRIu32 " flagged inappropriately %x",
2545 method_index,
2546 method_access_flags);
2547 return false;
2548 }
2549 }
2550
2551 return true;
2552}
2553
jeffhao10037c82012-01-23 15:06:23 -08002554} // namespace art