blob: a5f9d0990073806b7755bcb489c97edd38558c81 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
jeffhao10037c82012-01-23 15:06:23 -080016
17#include "dex_file_verifier.h"
18
Andreas Gampee6215c02015-08-31 18:54:38 -070019#include <inttypes.h>
Narayan Kamath92572be2013-11-28 14:06:24 +000020#include <zlib.h>
Andreas Gampee6215c02015-08-31 18:54:38 -070021
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Narayan Kamath92572be2013-11-28 14:06:24 +000023
Elliott Hughese222ee02012-12-13 14:41:43 -080024#include "base/stringprintf.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070025#include "dex_file-inl.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070026#include "experimental_flags.h"
jeffhao10037c82012-01-23 15:06:23 -080027#include "leb128.h"
Alex Lighteb7c1442015-08-31 13:17:42 -070028#include "runtime.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070029#include "safe_map.h"
Ian Rogersa6724902013-09-23 09:23:37 -070030#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "utils.h"
jeffhao10037c82012-01-23 15:06:23 -080032
33namespace art {
34
35static uint32_t MapTypeToBitMask(uint32_t map_type) {
36 switch (map_type) {
37 case DexFile::kDexTypeHeaderItem: return 1 << 0;
38 case DexFile::kDexTypeStringIdItem: return 1 << 1;
39 case DexFile::kDexTypeTypeIdItem: return 1 << 2;
40 case DexFile::kDexTypeProtoIdItem: return 1 << 3;
41 case DexFile::kDexTypeFieldIdItem: return 1 << 4;
42 case DexFile::kDexTypeMethodIdItem: return 1 << 5;
43 case DexFile::kDexTypeClassDefItem: return 1 << 6;
44 case DexFile::kDexTypeMapList: return 1 << 7;
45 case DexFile::kDexTypeTypeList: return 1 << 8;
46 case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9;
47 case DexFile::kDexTypeAnnotationSetItem: return 1 << 10;
48 case DexFile::kDexTypeClassDataItem: return 1 << 11;
49 case DexFile::kDexTypeCodeItem: return 1 << 12;
50 case DexFile::kDexTypeStringDataItem: return 1 << 13;
51 case DexFile::kDexTypeDebugInfoItem: return 1 << 14;
52 case DexFile::kDexTypeAnnotationItem: return 1 << 15;
53 case DexFile::kDexTypeEncodedArrayItem: return 1 << 16;
54 case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17;
55 }
56 return 0;
57}
58
59static bool IsDataSectionType(uint32_t map_type) {
60 switch (map_type) {
61 case DexFile::kDexTypeHeaderItem:
62 case DexFile::kDexTypeStringIdItem:
63 case DexFile::kDexTypeTypeIdItem:
64 case DexFile::kDexTypeProtoIdItem:
65 case DexFile::kDexTypeFieldIdItem:
66 case DexFile::kDexTypeMethodIdItem:
67 case DexFile::kDexTypeClassDefItem:
68 return false;
69 }
70 return true;
71}
72
Andreas Gampee09269c2014-06-06 18:45:35 -070073const char* DexFileVerifier::CheckLoadStringByIdx(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070074 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumStringIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070075 return nullptr;
76 }
77 return dex_file_->StringDataByIdx(idx);
78}
79
80const char* DexFileVerifier::CheckLoadStringByTypeIdx(uint32_t type_idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070081 if (UNLIKELY(!CheckIndex(type_idx, dex_file_->NumTypeIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070082 return nullptr;
83 }
84 const DexFile::TypeId& type_id = dex_file_->GetTypeId(type_idx);
85 uint32_t idx = type_id.descriptor_idx_;
86 return CheckLoadStringByIdx(idx, error_string);
87}
88
89const DexFile::FieldId* DexFileVerifier::CheckLoadFieldId(uint32_t idx, const char* error_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070090 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumFieldIds(), error_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070091 return nullptr;
92 }
93 return &dex_file_->GetFieldId(idx);
94}
95
96const DexFile::MethodId* DexFileVerifier::CheckLoadMethodId(uint32_t idx, const char* err_string) {
Andreas Gampedf10b322014-06-11 21:46:05 -070097 if (UNLIKELY(!CheckIndex(idx, dex_file_->NumMethodIds(), err_string))) {
Andreas Gampee09269c2014-06-06 18:45:35 -070098 return nullptr;
99 }
100 return &dex_file_->GetMethodId(idx);
101}
102
103// Helper macro to load string and return false on error.
104#define LOAD_STRING(var, idx, error) \
105 const char* var = CheckLoadStringByIdx(idx, error); \
Andreas Gampedf10b322014-06-11 21:46:05 -0700106 if (UNLIKELY(var == nullptr)) { \
Andreas Gampee09269c2014-06-06 18:45:35 -0700107 return false; \
108 }
109
110// Helper macro to load string by type idx and return false on error.
111#define LOAD_STRING_BY_TYPE(var, type_idx, error) \
112 const char* var = CheckLoadStringByTypeIdx(type_idx, error); \
Andreas Gampedf10b322014-06-11 21:46:05 -0700113 if (UNLIKELY(var == nullptr)) { \
Andreas Gampee09269c2014-06-06 18:45:35 -0700114 return false; \
115 }
116
117// Helper macro to load method id. Return last parameter on error.
Andreas Gampe5e31dda2014-06-13 11:35:12 -0700118#define LOAD_METHOD(var, idx, error_string, error_stmt) \
Andreas Gampee09269c2014-06-06 18:45:35 -0700119 const DexFile::MethodId* var = CheckLoadMethodId(idx, error_string); \
Andreas Gampedf10b322014-06-11 21:46:05 -0700120 if (UNLIKELY(var == nullptr)) { \
Andreas Gampe5e31dda2014-06-13 11:35:12 -0700121 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700122 }
123
124// Helper macro to load method id. Return last parameter on error.
Andreas Gampe5e31dda2014-06-13 11:35:12 -0700125#define LOAD_FIELD(var, idx, fmt, error_stmt) \
Andreas Gampee09269c2014-06-06 18:45:35 -0700126 const DexFile::FieldId* var = CheckLoadFieldId(idx, fmt); \
Andreas Gampedf10b322014-06-11 21:46:05 -0700127 if (UNLIKELY(var == nullptr)) { \
Andreas Gampe5e31dda2014-06-13 11:35:12 -0700128 error_stmt; \
Andreas Gampee09269c2014-06-06 18:45:35 -0700129 }
130
Ian Rogers13735952014-10-08 12:43:28 -0700131bool DexFileVerifier::Verify(const DexFile* dex_file, const uint8_t* begin, size_t size,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700132 const char* location, std::string* error_msg) {
Ian Rogers700a4022014-05-19 16:49:03 -0700133 std::unique_ptr<DexFileVerifier> verifier(new DexFileVerifier(dex_file, begin, size, location));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700134 if (!verifier->Verify()) {
135 *error_msg = verifier->FailureReason();
136 return false;
137 }
138 return true;
139}
140
141bool DexFileVerifier::CheckShortyDescriptorMatch(char shorty_char, const char* descriptor,
142 bool is_return_type) {
jeffhao10037c82012-01-23 15:06:23 -0800143 switch (shorty_char) {
144 case 'V':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700145 if (UNLIKELY(!is_return_type)) {
146 ErrorStringPrintf("Invalid use of void");
jeffhao10037c82012-01-23 15:06:23 -0800147 return false;
148 }
Ian Rogersfc787ec2014-10-09 21:56:44 -0700149 FALLTHROUGH_INTENDED;
jeffhao10037c82012-01-23 15:06:23 -0800150 case 'B':
151 case 'C':
152 case 'D':
153 case 'F':
154 case 'I':
155 case 'J':
156 case 'S':
157 case 'Z':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700158 if (UNLIKELY((descriptor[0] != shorty_char) || (descriptor[1] != '\0'))) {
159 ErrorStringPrintf("Shorty vs. primitive type mismatch: '%c', '%s'",
160 shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800161 return false;
162 }
163 break;
164 case 'L':
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700165 if (UNLIKELY((descriptor[0] != 'L') && (descriptor[0] != '['))) {
166 ErrorStringPrintf("Shorty vs. type mismatch: '%c', '%s'", shorty_char, descriptor);
jeffhao10037c82012-01-23 15:06:23 -0800167 return false;
168 }
169 break;
170 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700171 ErrorStringPrintf("Bad shorty character: '%c'", shorty_char);
jeffhao10037c82012-01-23 15:06:23 -0800172 return false;
173 }
174 return true;
175}
176
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700177bool DexFileVerifier::CheckListSize(const void* start, size_t count, size_t elem_size,
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700178 const char* label) {
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700179 // Check that size is not 0.
180 CHECK_NE(elem_size, 0U);
181
Ian Rogers13735952014-10-08 12:43:28 -0700182 const uint8_t* range_start = reinterpret_cast<const uint8_t*>(start);
183 const uint8_t* file_start = reinterpret_cast<const uint8_t*>(begin_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700184
185 // Check for overflow.
186 uintptr_t max = 0 - 1;
187 size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
188 size_t max_count = available_bytes_till_end_of_mem / elem_size;
189 if (max_count < count) {
190 ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
191 static_cast<size_t>(range_start - file_start),
192 count, elem_size);
193 return false;
194 }
195
Ian Rogers13735952014-10-08 12:43:28 -0700196 const uint8_t* range_end = range_start + count * elem_size;
197 const uint8_t* file_end = file_start + size_;
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700198 if (UNLIKELY((range_start < file_start) || (range_end > file_end))) {
199 // Note: these two tests are enough as we make sure above that there's no overflow.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800200 ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
Ian Rogerse3d55812014-06-11 13:00:44 -0700201 static_cast<size_t>(range_start - file_start),
202 static_cast<size_t>(range_end - file_start));
jeffhao10037c82012-01-23 15:06:23 -0800203 return false;
204 }
205 return true;
206}
207
Ian Rogers13735952014-10-08 12:43:28 -0700208bool DexFileVerifier::CheckList(size_t element_size, const char* label, const uint8_t* *ptr) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700209 // Check that the list is available. The first 4B are the count.
210 if (!CheckListSize(*ptr, 1, 4U, label)) {
211 return false;
212 }
213
214 uint32_t count = *reinterpret_cast<const uint32_t*>(*ptr);
215 if (count > 0) {
216 if (!CheckListSize(*ptr + 4, count, element_size, label)) {
217 return false;
218 }
219 }
220
221 *ptr += 4 + count * element_size;
222 return true;
223}
224
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700225bool DexFileVerifier::CheckIndex(uint32_t field, uint32_t limit, const char* label) {
226 if (UNLIKELY(field >= limit)) {
227 ErrorStringPrintf("Bad index for %s: %x >= %x", label, field, limit);
jeffhao10037c82012-01-23 15:06:23 -0800228 return false;
229 }
230 return true;
231}
232
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700233bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset, uint32_t size, const char* label) {
234 if (size == 0) {
235 if (offset != 0) {
236 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
237 return false;
238 }
239 }
240 if (size_ <= offset) {
241 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
242 return false;
243 }
244 return true;
245}
246
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700247bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800248 // Check file size from the header.
249 uint32_t expected_size = header_->file_size_;
250 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700251 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800252 return false;
253 }
254
255 // Compute and verify the checksum in the header.
256 uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
257 const uint32_t non_sum = sizeof(header_->magic_) + sizeof(header_->checksum_);
Ian Rogers13735952014-10-08 12:43:28 -0700258 const uint8_t* non_sum_ptr = reinterpret_cast<const uint8_t*>(header_) + non_sum;
jeffhaof6174e82012-01-31 16:14:17 -0800259 adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
jeffhao10037c82012-01-23 15:06:23 -0800260 if (adler_checksum != header_->checksum_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700261 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
jeffhao10037c82012-01-23 15:06:23 -0800262 return false;
263 }
264
265 // Check the contents of the header.
266 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700267 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800268 return false;
269 }
270
271 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700272 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800273 return false;
274 }
275
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700276 // Check that all offsets are inside the file.
277 bool result =
278 CheckValidOffsetAndSize(header_->link_off_, header_->link_size_, "link") &&
279 CheckValidOffsetAndSize(header_->map_off_, header_->map_off_, "map") &&
280 CheckValidOffsetAndSize(header_->string_ids_off_, header_->string_ids_size_, "string-ids") &&
281 CheckValidOffsetAndSize(header_->type_ids_off_, header_->type_ids_size_, "type-ids") &&
282 CheckValidOffsetAndSize(header_->proto_ids_off_, header_->proto_ids_size_, "proto-ids") &&
283 CheckValidOffsetAndSize(header_->field_ids_off_, header_->field_ids_size_, "field-ids") &&
284 CheckValidOffsetAndSize(header_->method_ids_off_, header_->method_ids_size_, "method-ids") &&
285 CheckValidOffsetAndSize(header_->class_defs_off_, header_->class_defs_size_, "class-defs") &&
286 CheckValidOffsetAndSize(header_->data_off_, header_->data_size_, "data");
287
288 return result;
jeffhao10037c82012-01-23 15:06:23 -0800289}
290
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700291bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700292 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
293 header_->map_off_);
294 // Check that map list content is available.
295 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
296 return false;
297 }
298
jeffhao10037c82012-01-23 15:06:23 -0800299 const DexFile::MapItem* item = map->list_;
300
301 uint32_t count = map->size_;
302 uint32_t last_offset = 0;
303 uint32_t data_item_count = 0;
304 uint32_t data_items_left = header_->data_size_;
305 uint32_t used_bits = 0;
306
307 // Sanity check the size of the map list.
308 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
309 return false;
310 }
311
312 // Check the items listed in the map.
313 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700314 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
315 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800316 return false;
317 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700318 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
319 ErrorStringPrintf("Map item after end of file: %x, size %x",
320 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800321 return false;
322 }
323
324 if (IsDataSectionType(item->type_)) {
325 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700326 if (UNLIKELY(icount > data_items_left)) {
327 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800328 return false;
329 }
330 data_items_left -= icount;
331 data_item_count += icount;
332 }
333
334 uint32_t bit = MapTypeToBitMask(item->type_);
335
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700336 if (UNLIKELY(bit == 0)) {
337 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800338 return false;
339 }
340
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700341 if (UNLIKELY((used_bits & bit) != 0)) {
342 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800343 return false;
344 }
345
346 used_bits |= bit;
347 last_offset = item->offset_;
348 item++;
349 }
350
351 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700352 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
353 ErrorStringPrintf("Map is missing header entry");
jeffhao10037c82012-01-23 15:06:23 -0800354 return false;
355 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700356 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
357 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800358 return false;
359 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700360 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
361 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
362 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800363 return false;
364 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700365 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
366 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
367 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800368 return false;
369 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700370 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
371 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
372 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800373 return false;
374 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700375 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
376 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
377 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800378 return false;
379 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700380 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
381 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
382 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800383 return false;
384 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700385 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
386 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
387 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800388 return false;
389 }
jeffhao10037c82012-01-23 15:06:23 -0800390 return true;
391}
392
393uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
394 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700395 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700396 for (uint32_t i = 0; i < size; i++) {
397 result |= ((uint32_t) *(ptr_++)) << (i * 8);
398 }
jeffhao10037c82012-01-23 15:06:23 -0800399 }
jeffhao10037c82012-01-23 15:06:23 -0800400 return result;
401}
402
403bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700404 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700405 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800406
407 for (uint32_t i = 0; i < handlers_size; i++) {
408 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800409 size_t offset = ptr_ - handlers_base;
jeffhao10037c82012-01-23 15:06:23 -0800410 int32_t size = DecodeSignedLeb128(&ptr_);
411
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700412 if (UNLIKELY((size < -65536) || (size > 65536))) {
413 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800414 return false;
415 }
416
417 if (size <= 0) {
418 catch_all = true;
419 size = -size;
420 } else {
421 catch_all = false;
422 }
423
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800424 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800425
426 while (size-- > 0) {
427 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
428 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
429 return false;
430 }
431
432 uint32_t addr = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700433 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
434 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800435 return false;
436 }
437 }
438
439 if (catch_all) {
440 uint32_t addr = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700441 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
442 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800443 return false;
444 }
445 }
446 }
447
448 return true;
449}
450
Andreas Gampee6215c02015-08-31 18:54:38 -0700451bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
452 uint32_t access_flags,
453 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700454 uint16_t class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700455 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700456 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800457 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
458 return false;
459 }
460
Andreas Gampee6215c02015-08-31 18:54:38 -0700461 // Check that it's the right class.
462 uint16_t my_class_index =
463 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
464 class_idx_;
465 if (class_type_index != my_class_index) {
466 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
467 my_class_index,
468 class_type_index);
469 return false;
470 }
471
472 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800473 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700474 if (UNLIKELY(is_static != expect_static)) {
475 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800476 return false;
477 }
478
Andreas Gampee6215c02015-08-31 18:54:38 -0700479 // Check field access flags.
480 std::string error_msg;
481 if (!CheckFieldAccessFlags(access_flags, class_access_flags, &error_msg)) {
482 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800483 return false;
484 }
485
486 return true;
487}
488
Andreas Gampee6215c02015-08-31 18:54:38 -0700489bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
490 uint32_t access_flags,
491 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700492 uint16_t class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700493 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700494 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700495 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700496 DCHECK(direct_method_indexes != nullptr);
497 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800498 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
499 return false;
500 }
501
Andreas Gampee6215c02015-08-31 18:54:38 -0700502 // Check that it's the right class.
503 uint16_t my_class_index =
504 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
505 class_idx_;
506 if (class_type_index != my_class_index) {
507 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 "vs %" PRIu16,
508 my_class_index,
509 class_type_index);
jeffhao10037c82012-01-23 15:06:23 -0800510 return false;
511 }
512
Andreas Gampee6215c02015-08-31 18:54:38 -0700513 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700514 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700515 direct_method_indexes->insert(idx);
516 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700517 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
518 return false;
519 }
520
Andreas Gampee6215c02015-08-31 18:54:38 -0700521 // Check method access flags.
522 bool has_code = (code_offset != 0);
523 std::string error_msg;
524 if (!CheckMethodAccessFlags(idx,
525 access_flags,
526 class_access_flags,
527 has_code,
528 expect_direct,
529 &error_msg)) {
530 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800531 return false;
532 }
533
534 return true;
535}
536
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800537bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800538 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700539 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800540 return false;
541 }
542 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700543 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800544 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800545 return false;
546 }
547 ptr_++;
548 offset++;
549 }
550 }
551 return true;
552}
553
554bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700555 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800556 return false;
557 }
558
559 uint8_t header_byte = *(ptr_++);
560 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
561 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
562
563 switch (value_type) {
564 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700565 if (UNLIKELY(value_arg != 0)) {
566 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800567 return false;
568 }
569 ptr_++;
570 break;
571 case DexFile::kDexAnnotationShort:
572 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700573 if (UNLIKELY(value_arg > 1)) {
574 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800575 return false;
576 }
577 ptr_ += value_arg + 1;
578 break;
579 case DexFile::kDexAnnotationInt:
580 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700581 if (UNLIKELY(value_arg > 3)) {
582 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800583 return false;
584 }
585 ptr_ += value_arg + 1;
586 break;
587 case DexFile::kDexAnnotationLong:
588 case DexFile::kDexAnnotationDouble:
589 ptr_ += value_arg + 1;
590 break;
591 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700592 if (UNLIKELY(value_arg > 3)) {
593 ErrorStringPrintf("Bad encoded_value string size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800594 return false;
595 }
596 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
597 if (!CheckIndex(idx, header_->string_ids_size_, "encoded_value string")) {
598 return false;
599 }
600 break;
601 }
602 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700603 if (UNLIKELY(value_arg > 3)) {
604 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800605 return false;
606 }
607 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
608 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
609 return false;
610 }
611 break;
612 }
613 case DexFile::kDexAnnotationField:
614 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700615 if (UNLIKELY(value_arg > 3)) {
616 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800617 return false;
618 }
619 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
620 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
621 return false;
622 }
623 break;
624 }
625 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700626 if (UNLIKELY(value_arg > 3)) {
627 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800628 return false;
629 }
630 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
631 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
632 return false;
633 }
634 break;
635 }
636 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700637 if (UNLIKELY(value_arg != 0)) {
638 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800639 return false;
640 }
641 if (!CheckEncodedArray()) {
642 return false;
643 }
644 break;
645 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700646 if (UNLIKELY(value_arg != 0)) {
647 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800648 return false;
649 }
650 if (!CheckEncodedAnnotation()) {
651 return false;
652 }
653 break;
654 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700655 if (UNLIKELY(value_arg != 0)) {
656 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800657 return false;
658 }
659 break;
660 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700661 if (UNLIKELY(value_arg > 1)) {
662 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800663 return false;
664 }
665 break;
666 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700667 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800668 return false;
669 }
670
671 return true;
672}
673
674bool DexFileVerifier::CheckEncodedArray() {
675 uint32_t size = DecodeUnsignedLeb128(&ptr_);
676
677 while (size--) {
678 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700679 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800680 return false;
681 }
682 }
683 return true;
684}
685
686bool DexFileVerifier::CheckEncodedAnnotation() {
687 uint32_t idx = DecodeUnsignedLeb128(&ptr_);
688 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
689 return false;
690 }
691
692 uint32_t size = DecodeUnsignedLeb128(&ptr_);
693 uint32_t last_idx = 0;
694
695 for (uint32_t i = 0; i < size; i++) {
696 idx = DecodeUnsignedLeb128(&ptr_);
697 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
698 return false;
699 }
700
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700701 if (UNLIKELY(last_idx >= idx && i != 0)) {
702 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
703 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800704 return false;
705 }
706
707 if (!CheckEncodedValue()) {
708 return false;
709 }
710
711 last_idx = idx;
712 }
713 return true;
714}
715
Andreas Gampee6215c02015-08-31 18:54:38 -0700716bool DexFileVerifier::FindClassFlags(uint32_t index,
717 bool is_field,
718 uint16_t* class_type_index,
719 uint32_t* class_access_flags) {
720 DCHECK(class_type_index != nullptr);
721 DCHECK(class_access_flags != nullptr);
722
723 // First check if the index is valid.
724 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
725 return false;
726 }
727
728 // Next get the type index.
729 if (is_field) {
730 *class_type_index =
731 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
732 class_idx_;
733 } else {
734 *class_type_index =
735 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
736 class_idx_;
737 }
738
739 // Check if that is valid.
740 if (*class_type_index >= header_->type_ids_size_) {
741 return false;
742 }
743
744 // Now search for the class def. This is basically a specialized version of the DexFile code, as
745 // we should not trust that this is a valid DexFile just yet.
746 const DexFile::ClassDef* class_def_begin =
747 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
748 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
749 const DexFile::ClassDef* class_def = class_def_begin + i;
750 if (class_def->class_idx_ == *class_type_index) {
751 *class_access_flags = class_def->access_flags_;
752 return true;
753 }
754 }
755
756 // Didn't find the class-def, not defined here...
757 return false;
758}
759
760bool DexFileVerifier::CheckOrderAndGetClassFlags(bool is_field,
761 const char* type_descr,
762 uint32_t curr_index,
763 uint32_t prev_index,
764 bool* have_class,
765 uint16_t* class_type_index,
766 uint32_t* class_access_flags) {
767 if (curr_index < prev_index) {
768 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
769 type_descr,
770 prev_index,
771 curr_index);
772 return false;
773 }
774
775 if (!*have_class) {
776 *have_class = FindClassFlags(curr_index, is_field, class_type_index, class_access_flags);
777 if (!*have_class) {
778 // Should have really found one.
779 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
780 type_descr,
781 curr_index);
782 return false;
783 }
784 }
785 return true;
786}
787
788template <bool kStatic>
789bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
790 bool* have_class,
791 uint16_t* class_type_index,
792 uint32_t* class_access_flags) {
793 DCHECK(it != nullptr);
794 // These calls use the raw access flags to check whether the whole dex field is valid.
795 uint32_t prev_index = 0;
796 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
797 uint32_t curr_index = it->GetMemberIndex();
798 if (!CheckOrderAndGetClassFlags(true,
799 kStatic ? "static field" : "instance field",
800 curr_index,
801 prev_index,
802 have_class,
803 class_type_index,
804 class_access_flags)) {
805 return false;
806 }
807 prev_index = curr_index;
808
809 if (!CheckClassDataItemField(curr_index,
810 it->GetRawMemberAccessFlags(),
811 *class_access_flags,
812 *class_type_index,
813 kStatic)) {
814 return false;
815 }
816 }
817
818 return true;
819}
820
821template <bool kDirect>
822bool DexFileVerifier::CheckIntraClassDataItemMethods(
823 ClassDataItemIterator* it,
824 std::unordered_set<uint32_t>* direct_method_indexes,
825 bool* have_class,
826 uint16_t* class_type_index,
827 uint32_t* class_access_flags) {
828 uint32_t prev_index = 0;
829 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
830 uint32_t curr_index = it->GetMemberIndex();
831 if (!CheckOrderAndGetClassFlags(false,
832 kDirect ? "direct method" : "virtual method",
833 curr_index,
834 prev_index,
835 have_class,
836 class_type_index,
837 class_access_flags)) {
838 return false;
839 }
840 prev_index = curr_index;
841
842 if (!CheckClassDataItemMethod(curr_index,
843 it->GetRawMemberAccessFlags(),
844 *class_access_flags,
845 *class_type_index,
846 it->GetMethodCodeItemOffset(),
847 direct_method_indexes,
848 kDirect)) {
849 return false;
850 }
851 }
852
853 return true;
854}
855
jeffhao10037c82012-01-23 15:06:23 -0800856bool DexFileVerifier::CheckIntraClassDataItem() {
857 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -0700858 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -0800859
Andreas Gampee6215c02015-08-31 18:54:38 -0700860 // This code is complicated by the fact that we don't directly know which class this belongs to.
861 // So we need to explicitly search with the first item we find (either field or method), and then,
862 // as the lookup is expensive, cache the result.
863 bool have_class = false;
864 uint16_t class_type_index;
865 uint32_t class_access_flags;
866
867 // Check fields.
868 if (!CheckIntraClassDataItemFields<true>(&it,
869 &have_class,
870 &class_type_index,
871 &class_access_flags)) {
872 return false;
jeffhao10037c82012-01-23 15:06:23 -0800873 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700874 if (!CheckIntraClassDataItemFields<false>(&it,
875 &have_class,
876 &class_type_index,
877 &class_access_flags)) {
878 return false;
jeffhao10037c82012-01-23 15:06:23 -0800879 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700880
881 // Check methods.
882 if (!CheckIntraClassDataItemMethods<true>(&it,
883 &direct_method_indexes,
884 &have_class,
885 &class_type_index,
886 &class_access_flags)) {
887 return false;
jeffhao10037c82012-01-23 15:06:23 -0800888 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700889 if (!CheckIntraClassDataItemMethods<false>(&it,
890 &direct_method_indexes,
891 &have_class,
892 &class_type_index,
893 &class_access_flags)) {
894 return false;
jeffhao10037c82012-01-23 15:06:23 -0800895 }
896
897 ptr_ = it.EndDataPointer();
898 return true;
899}
900
901bool DexFileVerifier::CheckIntraCodeItem() {
902 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700903 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -0800904 return false;
905 }
906
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700907 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
908 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
909 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800910 return false;
911 }
912
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700913 if (UNLIKELY((code_item->outs_size_ > 5) &&
914 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -0800915 /*
916 * outs_size can be up to 5, even if registers_size is smaller, since the
917 * short forms of method invocation allow repetitions of a register multiple
918 * times within a single parameter list. However, longer parameter lists
919 * need to be represented in-order in the register file.
920 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700921 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
922 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800923 return false;
924 }
925
926 const uint16_t* insns = code_item->insns_;
927 uint32_t insns_size = code_item->insns_size_in_code_units_;
928 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
929 return false;
930 }
931
932 // Grab the end of the insns if there are no try_items.
933 uint32_t try_items_size = code_item->tries_size_;
934 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -0700935 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -0800936 return true;
937 }
938
939 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800940 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700941 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -0800942 return false;
943 }
944
945 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800946 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
947 return false;
948 }
949
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -0500950 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
951 uint32_t handlers_size = DecodeUnsignedLeb128(&ptr_);
952
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700953 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
954 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -0800955 return false;
956 }
957
Ian Rogers700a4022014-05-19 16:49:03 -0700958 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -0700959 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -0800960 return false;
961 }
962
963 uint32_t last_addr = 0;
964 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700965 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
966 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -0800967 return false;
968 }
969
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700970 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
971 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -0800972 return false;
973 }
974
975 uint32_t i;
976 for (i = 0; i < handlers_size; i++) {
977 if (try_items->handler_off_ == handler_offsets[i]) {
978 break;
979 }
980 }
981
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700982 if (UNLIKELY(i == handlers_size)) {
983 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -0800984 return false;
985 }
986
987 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700988 if (UNLIKELY(last_addr > insns_size)) {
989 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -0800990 return false;
991 }
992
993 try_items++;
994 }
995
996 return true;
997}
998
999bool DexFileVerifier::CheckIntraStringDataItem() {
1000 uint32_t size = DecodeUnsignedLeb128(&ptr_);
Ian Rogers13735952014-10-08 12:43:28 -07001001 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001002
1003 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001004 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001005 if (UNLIKELY(ptr_ >= file_end)) {
1006 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001007 return false;
1008 }
1009
1010 uint8_t byte = *(ptr_++);
1011
1012 // Switch on the high 4 bits.
1013 switch (byte >> 4) {
1014 case 0x00:
1015 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001016 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001017 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001018 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001019 return false;
1020 }
1021 break;
1022 case 0x01:
1023 case 0x02:
1024 case 0x03:
1025 case 0x04:
1026 case 0x05:
1027 case 0x06:
1028 case 0x07:
1029 // No extra checks necessary for bit pattern 0xxx.
1030 break;
1031 case 0x08:
1032 case 0x09:
1033 case 0x0a:
1034 case 0x0b:
1035 case 0x0f:
1036 // Illegal bit patterns 10xx or 1111.
1037 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001038 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001039 return false;
1040 case 0x0c:
1041 case 0x0d: {
1042 // Bit pattern 110x has an additional byte.
1043 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001044 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1045 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001046 return false;
1047 }
1048 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001049 if (UNLIKELY((value != 0) && (value < 0x80))) {
1050 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001051 return false;
1052 }
1053 break;
1054 }
1055 case 0x0e: {
1056 // Bit pattern 1110 has 2 additional bytes.
1057 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001058 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1059 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001060 return false;
1061 }
1062 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001063 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1064 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001065 return false;
1066 }
1067 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001068 if (UNLIKELY(value < 0x800)) {
1069 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001070 return false;
1071 }
1072 break;
1073 }
1074 }
1075 }
1076
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001077 if (UNLIKELY(*(ptr_++) != '\0')) {
1078 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001079 return false;
1080 }
1081
1082 return true;
1083}
1084
1085bool DexFileVerifier::CheckIntraDebugInfoItem() {
1086 DecodeUnsignedLeb128(&ptr_);
1087 uint32_t parameters_size = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001088 if (UNLIKELY(parameters_size > 65536)) {
1089 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001090 return false;
1091 }
1092
1093 for (uint32_t j = 0; j < parameters_size; j++) {
1094 uint32_t parameter_name = DecodeUnsignedLeb128(&ptr_);
1095 if (parameter_name != 0) {
1096 parameter_name--;
1097 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1098 return false;
1099 }
1100 }
1101 }
1102
1103 while (true) {
1104 uint8_t opcode = *(ptr_++);
1105 switch (opcode) {
1106 case DexFile::DBG_END_SEQUENCE: {
1107 return true;
1108 }
1109 case DexFile::DBG_ADVANCE_PC: {
1110 DecodeUnsignedLeb128(&ptr_);
1111 break;
1112 }
1113 case DexFile::DBG_ADVANCE_LINE: {
1114 DecodeSignedLeb128(&ptr_);
1115 break;
1116 }
1117 case DexFile::DBG_START_LOCAL: {
1118 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001119 if (UNLIKELY(reg_num >= 65536)) {
1120 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001121 return false;
1122 }
1123 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1124 if (name_idx != 0) {
1125 name_idx--;
1126 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1127 return false;
1128 }
1129 }
1130 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
1131 if (type_idx != 0) {
1132 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001133 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001134 return false;
1135 }
1136 }
1137 break;
1138 }
1139 case DexFile::DBG_END_LOCAL:
1140 case DexFile::DBG_RESTART_LOCAL: {
1141 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001142 if (UNLIKELY(reg_num >= 65536)) {
1143 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001144 return false;
1145 }
1146 break;
1147 }
1148 case DexFile::DBG_START_LOCAL_EXTENDED: {
1149 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001150 if (UNLIKELY(reg_num >= 65536)) {
1151 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001152 return false;
1153 }
1154 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1155 if (name_idx != 0) {
1156 name_idx--;
1157 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1158 return false;
1159 }
1160 }
1161 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
1162 if (type_idx != 0) {
1163 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001164 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001165 return false;
1166 }
1167 }
1168 uint32_t sig_idx = DecodeUnsignedLeb128(&ptr_);
1169 if (sig_idx != 0) {
1170 sig_idx--;
1171 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1172 return false;
1173 }
1174 }
1175 break;
1176 }
1177 case DexFile::DBG_SET_FILE: {
1178 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1179 if (name_idx != 0) {
1180 name_idx--;
1181 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1182 return false;
1183 }
1184 }
1185 break;
1186 }
1187 }
1188 }
1189}
1190
1191bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001192 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001193 return false;
1194 }
1195
1196 // Check visibility
1197 switch (*(ptr_++)) {
1198 case DexFile::kDexVisibilityBuild:
1199 case DexFile::kDexVisibilityRuntime:
1200 case DexFile::kDexVisibilitySystem:
1201 break;
1202 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001203 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001204 return false;
1205 }
1206
1207 if (!CheckEncodedAnnotation()) {
1208 return false;
1209 }
1210
1211 return true;
1212}
1213
1214bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1215 const DexFile::AnnotationsDirectoryItem* item =
1216 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001217 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001218 return false;
1219 }
1220
1221 // Field annotations follow immediately after the annotations directory.
1222 const DexFile::FieldAnnotationsItem* field_item =
1223 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1224 uint32_t field_count = item->fields_size_;
1225 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1226 return false;
1227 }
1228
1229 uint32_t last_idx = 0;
1230 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001231 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1232 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001233 return false;
1234 }
1235 last_idx = field_item->field_idx_;
1236 field_item++;
1237 }
1238
1239 // Method annotations follow immediately after field annotations.
1240 const DexFile::MethodAnnotationsItem* method_item =
1241 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1242 uint32_t method_count = item->methods_size_;
1243 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1244 return false;
1245 }
1246
1247 last_idx = 0;
1248 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001249 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1250 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1251 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001252 return false;
1253 }
1254 last_idx = method_item->method_idx_;
1255 method_item++;
1256 }
1257
1258 // Parameter annotations follow immediately after method annotations.
1259 const DexFile::ParameterAnnotationsItem* parameter_item =
1260 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1261 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001262 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001263 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001264 return false;
1265 }
1266
1267 last_idx = 0;
1268 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001269 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1270 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1271 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001272 return false;
1273 }
1274 last_idx = parameter_item->method_idx_;
1275 parameter_item++;
1276 }
1277
1278 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001279 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001280 return true;
1281}
1282
Andreas Gampeb061cc12014-09-02 10:22:20 -07001283bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
1284 uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001285 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001286 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001287 switch (type) {
1288 case DexFile::kDexTypeClassDataItem:
1289 case DexFile::kDexTypeStringDataItem:
1290 case DexFile::kDexTypeDebugInfoItem:
1291 case DexFile::kDexTypeAnnotationItem:
1292 case DexFile::kDexTypeEncodedArrayItem:
1293 alignment_mask = sizeof(uint8_t) - 1;
1294 break;
1295 default:
1296 alignment_mask = sizeof(uint32_t) - 1;
1297 break;
1298 }
1299
1300 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001301 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001302 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001303
1304 // Check the padding between items.
1305 if (!CheckPadding(offset, aligned_offset)) {
1306 return false;
1307 }
1308
1309 // Check depending on the section type.
1310 switch (type) {
1311 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001312 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001313 return false;
1314 }
1315 ptr_ += sizeof(DexFile::StringId);
1316 break;
1317 }
1318 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001319 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001320 return false;
1321 }
1322 ptr_ += sizeof(DexFile::TypeId);
1323 break;
1324 }
1325 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001326 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001327 return false;
1328 }
1329 ptr_ += sizeof(DexFile::ProtoId);
1330 break;
1331 }
1332 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001333 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001334 return false;
1335 }
1336 ptr_ += sizeof(DexFile::FieldId);
1337 break;
1338 }
1339 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001340 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001341 return false;
1342 }
1343 ptr_ += sizeof(DexFile::MethodId);
1344 break;
1345 }
1346 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001347 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001348 return false;
1349 }
1350 ptr_ += sizeof(DexFile::ClassDef);
1351 break;
1352 }
1353 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001354 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001355 return false;
1356 }
jeffhao10037c82012-01-23 15:06:23 -08001357 break;
1358 }
1359 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001360 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001361 return false;
1362 }
jeffhao10037c82012-01-23 15:06:23 -08001363 break;
1364 }
1365 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001366 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001367 return false;
1368 }
jeffhao10037c82012-01-23 15:06:23 -08001369 break;
1370 }
1371 case DexFile::kDexTypeClassDataItem: {
1372 if (!CheckIntraClassDataItem()) {
1373 return false;
1374 }
1375 break;
1376 }
1377 case DexFile::kDexTypeCodeItem: {
1378 if (!CheckIntraCodeItem()) {
1379 return false;
1380 }
1381 break;
1382 }
1383 case DexFile::kDexTypeStringDataItem: {
1384 if (!CheckIntraStringDataItem()) {
1385 return false;
1386 }
1387 break;
1388 }
1389 case DexFile::kDexTypeDebugInfoItem: {
1390 if (!CheckIntraDebugInfoItem()) {
1391 return false;
1392 }
1393 break;
1394 }
1395 case DexFile::kDexTypeAnnotationItem: {
1396 if (!CheckIntraAnnotationItem()) {
1397 return false;
1398 }
1399 break;
1400 }
1401 case DexFile::kDexTypeEncodedArrayItem: {
1402 if (!CheckEncodedArray()) {
1403 return false;
1404 }
1405 break;
1406 }
1407 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1408 if (!CheckIntraAnnotationsDirectoryItem()) {
1409 return false;
1410 }
1411 break;
1412 }
1413 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001414 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001415 return false;
1416 }
1417
1418 if (IsDataSectionType(type)) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07001419 offset_to_type_map_.Put(aligned_offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001420 }
1421
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001422 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001423 if (UNLIKELY(aligned_offset > size_)) {
1424 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001425 return false;
1426 }
1427
1428 offset = aligned_offset;
1429 }
1430
1431 return true;
1432}
1433
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001434bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001435 uint32_t expected_offset;
1436 uint32_t expected_size;
1437
1438 // Get the expected offset and size from the header.
1439 switch (type) {
1440 case DexFile::kDexTypeStringIdItem:
1441 expected_offset = header_->string_ids_off_;
1442 expected_size = header_->string_ids_size_;
1443 break;
1444 case DexFile::kDexTypeTypeIdItem:
1445 expected_offset = header_->type_ids_off_;
1446 expected_size = header_->type_ids_size_;
1447 break;
1448 case DexFile::kDexTypeProtoIdItem:
1449 expected_offset = header_->proto_ids_off_;
1450 expected_size = header_->proto_ids_size_;
1451 break;
1452 case DexFile::kDexTypeFieldIdItem:
1453 expected_offset = header_->field_ids_off_;
1454 expected_size = header_->field_ids_size_;
1455 break;
1456 case DexFile::kDexTypeMethodIdItem:
1457 expected_offset = header_->method_ids_off_;
1458 expected_size = header_->method_ids_size_;
1459 break;
1460 case DexFile::kDexTypeClassDefItem:
1461 expected_offset = header_->class_defs_off_;
1462 expected_size = header_->class_defs_size_;
1463 break;
1464 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001465 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001466 return false;
1467 }
1468
1469 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001470 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001471 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001472 return false;
1473 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001474 if (UNLIKELY(count != expected_size)) {
1475 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001476 return false;
1477 }
1478
1479 return CheckIntraSectionIterate(offset, count, type);
1480}
1481
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001482bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count, uint16_t type) {
1483 size_t data_start = header_->data_off_;
1484 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001485
1486 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001487 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001488 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001489 return false;
1490 }
1491
1492 if (!CheckIntraSectionIterate(offset, count, type)) {
1493 return false;
1494 }
1495
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001496 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001497 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001498 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001499 return false;
1500 }
1501
1502 return true;
1503}
1504
1505bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001506 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001507 const DexFile::MapItem* item = map->list_;
1508
1509 uint32_t count = map->size_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001510 size_t offset = 0;
Ian Rogers30fab402012-01-23 15:43:46 -08001511 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001512
1513 // Check the items listed in the map.
1514 while (count--) {
1515 uint32_t section_offset = item->offset_;
1516 uint32_t section_count = item->size_;
1517 uint16_t type = item->type_;
1518
1519 // Check for padding and overlap between items.
1520 if (!CheckPadding(offset, section_offset)) {
1521 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001522 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001523 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001524 return false;
1525 }
1526
1527 // Check each item based on its type.
1528 switch (type) {
1529 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001530 if (UNLIKELY(section_count != 1)) {
1531 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001532 return false;
1533 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001534 if (UNLIKELY(section_offset != 0)) {
1535 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001536 return false;
1537 }
Ian Rogers30fab402012-01-23 15:43:46 -08001538 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001539 offset = header_->header_size_;
1540 break;
1541 case DexFile::kDexTypeStringIdItem:
1542 case DexFile::kDexTypeTypeIdItem:
1543 case DexFile::kDexTypeProtoIdItem:
1544 case DexFile::kDexTypeFieldIdItem:
1545 case DexFile::kDexTypeMethodIdItem:
1546 case DexFile::kDexTypeClassDefItem:
1547 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1548 return false;
1549 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001550 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001551 break;
1552 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001553 if (UNLIKELY(section_count != 1)) {
1554 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001555 return false;
1556 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001557 if (UNLIKELY(section_offset != header_->map_off_)) {
1558 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1559 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001560 return false;
1561 }
1562 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1563 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1564 break;
1565 case DexFile::kDexTypeTypeList:
1566 case DexFile::kDexTypeAnnotationSetRefList:
1567 case DexFile::kDexTypeAnnotationSetItem:
1568 case DexFile::kDexTypeClassDataItem:
1569 case DexFile::kDexTypeCodeItem:
1570 case DexFile::kDexTypeStringDataItem:
1571 case DexFile::kDexTypeDebugInfoItem:
1572 case DexFile::kDexTypeAnnotationItem:
1573 case DexFile::kDexTypeEncodedArrayItem:
1574 case DexFile::kDexTypeAnnotationsDirectoryItem:
1575 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1576 return false;
1577 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001578 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001579 break;
1580 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001581 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001582 return false;
1583 }
1584
1585 item++;
1586 }
1587
1588 return true;
1589}
1590
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001591bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001592 auto it = offset_to_type_map_.find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001593 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001594 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001595 return false;
1596 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001597 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001598 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001599 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001600 return false;
1601 }
1602 return true;
1603}
1604
Ian Rogers13735952014-10-08 12:43:28 -07001605uint16_t DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001606 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001607 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001608
1609 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001610 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
1611 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001612 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001613 }
1614
1615 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001616 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
1617 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001618 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001619 }
1620
1621 return DexFile::kDexNoIndex16;
1622}
1623
Ian Rogers13735952014-10-08 12:43:28 -07001624uint16_t DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001625 const DexFile::AnnotationsDirectoryItem* item =
1626 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001627 *success = true;
1628
jeffhao10037c82012-01-23 15:06:23 -08001629 if (item->fields_size_ != 0) {
1630 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001631 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
1632 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001633 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001634 }
1635
1636 if (item->methods_size_ != 0) {
1637 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001638 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001639 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001640 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001641 }
1642
1643 if (item->parameters_size_ != 0) {
1644 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001645 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001646 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001647 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001648 }
1649
1650 return DexFile::kDexNoIndex16;
1651}
1652
1653bool DexFileVerifier::CheckInterStringIdItem() {
1654 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1655
1656 // Check the map to make sure it has the right offset->type.
1657 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1658 return false;
1659 }
1660
1661 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001662 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001663 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1664 const char* prev_str = dex_file_->GetStringData(*prev_item);
1665 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001666 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1667 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001668 return false;
1669 }
1670 }
1671
1672 ptr_ += sizeof(DexFile::StringId);
1673 return true;
1674}
1675
1676bool DexFileVerifier::CheckInterTypeIdItem() {
1677 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001678
1679 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001680
1681 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001682 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1683 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001684 return false;
1685 }
1686
1687 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001688 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001689 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001690 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1691 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
1692 prev_item->descriptor_idx_, item->descriptor_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001693 return false;
1694 }
1695 }
1696
1697 ptr_ += sizeof(DexFile::TypeId);
1698 return true;
1699}
1700
1701bool DexFileVerifier::CheckInterProtoIdItem() {
1702 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001703
1704 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1705
jeffhao10037c82012-01-23 15:06:23 -08001706 if (item->parameters_off_ != 0 &&
1707 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1708 return false;
1709 }
1710
1711 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001712 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1713 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001714 return false;
1715 }
1716 shorty++;
1717
1718 DexFileParameterIterator it(*dex_file_, *item);
1719 while (it.HasNext() && *shorty != '\0') {
Andreas Gampebb836e12014-06-13 15:31:40 -07001720 if (!CheckIndex(it.GetTypeIdx(), dex_file_->NumTypeIds(),
1721 "inter_proto_id_item shorty type_idx")) {
1722 return false;
1723 }
jeffhao10037c82012-01-23 15:06:23 -08001724 const char* descriptor = it.GetDescriptor();
1725 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1726 return false;
1727 }
1728 it.Next();
1729 shorty++;
1730 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001731 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1732 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001733 return false;
1734 }
1735
1736 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001737 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001738 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001739 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1740 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001741 return false;
1742 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1743 DexFileParameterIterator curr_it(*dex_file_, *item);
1744 DexFileParameterIterator prev_it(*dex_file_, *prev);
1745
1746 while (curr_it.HasNext() && prev_it.HasNext()) {
1747 uint16_t prev_idx = prev_it.GetTypeIdx();
1748 uint16_t curr_idx = curr_it.GetTypeIdx();
1749 if (prev_idx == DexFile::kDexNoIndex16) {
1750 break;
1751 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001752 if (UNLIKELY(curr_idx == DexFile::kDexNoIndex16)) {
1753 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001754 return false;
1755 }
1756
1757 if (prev_idx < curr_idx) {
1758 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001759 } else if (UNLIKELY(prev_idx > curr_idx)) {
1760 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001761 return false;
1762 }
1763
1764 prev_it.Next();
1765 curr_it.Next();
1766 }
1767 }
1768 }
1769
1770 ptr_ += sizeof(DexFile::ProtoId);
1771 return true;
1772}
1773
1774bool DexFileVerifier::CheckInterFieldIdItem() {
1775 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1776
1777 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001778 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1779 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1780 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001781 return false;
1782 }
1783
1784 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001785 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1786 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1787 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001788 return false;
1789 }
1790
1791 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001792 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001793 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1794 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001795 return false;
1796 }
1797
1798 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001799 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001800 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001801 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1802 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001803 return false;
1804 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001805 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1806 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001807 return false;
1808 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001809 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
1810 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001811 return false;
1812 }
1813 }
1814 }
1815 }
1816
1817 ptr_ += sizeof(DexFile::FieldId);
1818 return true;
1819}
1820
1821bool DexFileVerifier::CheckInterMethodIdItem() {
1822 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
1823
1824 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001825 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
1826 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
1827 class_descriptor[0] != '['))) {
1828 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001829 return false;
1830 }
1831
1832 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07001833 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001834 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1835 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001836 return false;
1837 }
1838
Andreas Gampedf10b322014-06-11 21:46:05 -07001839 // Check that the proto id is valid.
1840 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
1841 "inter_method_id_item proto_idx"))) {
1842 return false;
1843 }
1844
jeffhao10037c82012-01-23 15:06:23 -08001845 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001846 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001847 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001848 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1849 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001850 return false;
1851 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001852 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1853 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001854 return false;
1855 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001856 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
1857 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001858 return false;
1859 }
1860 }
1861 }
1862 }
1863
1864 ptr_ += sizeof(DexFile::MethodId);
1865 return true;
1866}
1867
1868bool DexFileVerifier::CheckInterClassDefItem() {
1869 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001870
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001871 // Check for duplicate class def.
1872 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
1873 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_);
1874 return false;
1875 }
1876 defined_classes_.insert(item->class_idx_);
1877
Andreas Gampee09269c2014-06-06 18:45:35 -07001878 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
1879 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1880 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001881 return false;
1882 }
1883
Andreas Gampeacc2bb62014-07-17 19:26:50 -07001884 // Only allow non-runtime modifiers.
1885 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
1886 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
1887 return false;
1888 }
1889
jeffhao10037c82012-01-23 15:06:23 -08001890 if (item->interfaces_off_ != 0 &&
1891 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
1892 return false;
1893 }
1894 if (item->annotations_off_ != 0 &&
1895 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
1896 return false;
1897 }
1898 if (item->class_data_off_ != 0 &&
1899 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
1900 return false;
1901 }
1902 if (item->static_values_off_ != 0 &&
1903 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
1904 return false;
1905 }
1906
1907 if (item->superclass_idx_ != DexFile::kDexNoIndex16) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001908 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
1909 "inter_class_def_item superclass_idx")
1910 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
1911 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001912 return false;
1913 }
1914 }
1915
1916 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001917 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001918 uint32_t size = interfaces->Size();
1919
1920 // Ensure that all interfaces refer to classes (not arrays or primitives).
1921 for (uint32_t i = 0; i < size; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001922 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
1923 "inter_class_def_item interface type_idx")
1924 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
1925 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001926 return false;
1927 }
1928 }
1929
1930 /*
1931 * Ensure that there are no duplicates. This is an O(N^2) test, but in
1932 * practice the number of interfaces implemented by any given class is low.
1933 */
1934 for (uint32_t i = 1; i < size; i++) {
1935 uint32_t idx1 = interfaces->GetTypeItem(i).type_idx_;
1936 for (uint32_t j =0; j < i; j++) {
1937 uint32_t idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001938 if (UNLIKELY(idx1 == idx2)) {
1939 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08001940 return false;
1941 }
1942 }
1943 }
1944 }
1945
1946 // Check that references in class_data_item are to the right class.
1947 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001948 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001949 bool success;
1950 uint16_t data_definer = FindFirstClassDataDefiner(data, &success);
1951 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001952 return false;
1953 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001954 if (UNLIKELY((data_definer != item->class_idx_) && (data_definer != DexFile::kDexNoIndex16))) {
1955 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08001956 return false;
1957 }
1958 }
1959
1960 // Check that references in annotations_directory_item are to right class.
1961 if (item->annotations_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001962 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001963 bool success;
1964 uint16_t annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
1965 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001966 return false;
1967 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001968 if (UNLIKELY((annotations_definer != item->class_idx_) &&
1969 (annotations_definer != DexFile::kDexNoIndex16))) {
1970 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08001971 return false;
1972 }
1973 }
1974
1975 ptr_ += sizeof(DexFile::ClassDef);
1976 return true;
1977}
1978
1979bool DexFileVerifier::CheckInterAnnotationSetRefList() {
1980 const DexFile::AnnotationSetRefList* list =
1981 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
1982 const DexFile::AnnotationSetRefItem* item = list->list_;
1983 uint32_t count = list->size_;
1984
1985 while (count--) {
1986 if (item->annotations_off_ != 0 &&
1987 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
1988 return false;
1989 }
1990 item++;
1991 }
1992
Ian Rogers13735952014-10-08 12:43:28 -07001993 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08001994 return true;
1995}
1996
1997bool DexFileVerifier::CheckInterAnnotationSetItem() {
1998 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
1999 const uint32_t* offsets = set->entries_;
2000 uint32_t count = set->size_;
2001 uint32_t last_idx = 0;
2002
2003 for (uint32_t i = 0; i < count; i++) {
2004 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2005 return false;
2006 }
2007
2008 // Get the annotation from the offset and the type index for the annotation.
2009 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002010 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002011 const uint8_t* data = annotation->annotation_;
2012 uint32_t idx = DecodeUnsignedLeb128(&data);
2013
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002014 if (UNLIKELY(last_idx >= idx && i != 0)) {
2015 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002016 return false;
2017 }
2018
2019 last_idx = idx;
2020 offsets++;
2021 }
2022
Ian Rogers13735952014-10-08 12:43:28 -07002023 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002024 return true;
2025}
2026
2027bool DexFileVerifier::CheckInterClassDataItem() {
2028 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002029 bool success;
2030 uint16_t defining_class = FindFirstClassDataDefiner(ptr_, &success);
2031 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002032 return false;
2033 }
jeffhao10037c82012-01-23 15:06:23 -08002034
2035 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002036 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002037 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002038 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002039 return false;
2040 }
2041 }
2042 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2043 uint32_t code_off = it.GetMethodCodeItemOffset();
2044 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2045 return false;
2046 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002047 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002048 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002049 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002050 return false;
2051 }
2052 }
2053
2054 ptr_ = it.EndDataPointer();
2055 return true;
2056}
2057
2058bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2059 const DexFile::AnnotationsDirectoryItem* item =
2060 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002061 bool success;
2062 uint16_t defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
2063 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002064 return false;
2065 }
jeffhao10037c82012-01-23 15:06:23 -08002066
2067 if (item->class_annotations_off_ != 0 &&
2068 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2069 return false;
2070 }
2071
2072 // Field annotations follow immediately after the annotations directory.
2073 const DexFile::FieldAnnotationsItem* field_item =
2074 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2075 uint32_t field_count = item->fields_size_;
2076 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002077 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2078 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002079 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002080 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002081 return false;
2082 }
2083 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2084 return false;
2085 }
2086 field_item++;
2087 }
2088
2089 // Method annotations follow immediately after field annotations.
2090 const DexFile::MethodAnnotationsItem* method_item =
2091 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2092 uint32_t method_count = item->methods_size_;
2093 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002094 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002095 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002096 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002097 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002098 return false;
2099 }
2100 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2101 return false;
2102 }
2103 method_item++;
2104 }
2105
2106 // Parameter annotations follow immediately after method annotations.
2107 const DexFile::ParameterAnnotationsItem* parameter_item =
2108 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2109 uint32_t parameter_count = item->parameters_size_;
2110 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002111 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002112 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002113 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002114 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002115 return false;
2116 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002117 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2118 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002119 return false;
2120 }
2121 parameter_item++;
2122 }
2123
Ian Rogers13735952014-10-08 12:43:28 -07002124 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002125 return true;
2126}
2127
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002128bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002129 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002130 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002131 switch (type) {
2132 case DexFile::kDexTypeClassDataItem:
2133 alignment_mask = sizeof(uint8_t) - 1;
2134 break;
2135 default:
2136 alignment_mask = sizeof(uint32_t) - 1;
2137 break;
2138 }
2139
2140 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002141 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002142 for (uint32_t i = 0; i < count; i++) {
2143 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002144 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002145 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002146
2147 // Check depending on the section type.
2148 switch (type) {
2149 case DexFile::kDexTypeStringIdItem: {
2150 if (!CheckInterStringIdItem()) {
2151 return false;
2152 }
2153 break;
2154 }
2155 case DexFile::kDexTypeTypeIdItem: {
2156 if (!CheckInterTypeIdItem()) {
2157 return false;
2158 }
2159 break;
2160 }
2161 case DexFile::kDexTypeProtoIdItem: {
2162 if (!CheckInterProtoIdItem()) {
2163 return false;
2164 }
2165 break;
2166 }
2167 case DexFile::kDexTypeFieldIdItem: {
2168 if (!CheckInterFieldIdItem()) {
2169 return false;
2170 }
2171 break;
2172 }
2173 case DexFile::kDexTypeMethodIdItem: {
2174 if (!CheckInterMethodIdItem()) {
2175 return false;
2176 }
2177 break;
2178 }
2179 case DexFile::kDexTypeClassDefItem: {
2180 if (!CheckInterClassDefItem()) {
2181 return false;
2182 }
2183 break;
2184 }
2185 case DexFile::kDexTypeAnnotationSetRefList: {
2186 if (!CheckInterAnnotationSetRefList()) {
2187 return false;
2188 }
2189 break;
2190 }
2191 case DexFile::kDexTypeAnnotationSetItem: {
2192 if (!CheckInterAnnotationSetItem()) {
2193 return false;
2194 }
2195 break;
2196 }
2197 case DexFile::kDexTypeClassDataItem: {
2198 if (!CheckInterClassDataItem()) {
2199 return false;
2200 }
2201 break;
2202 }
2203 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2204 if (!CheckInterAnnotationsDirectoryItem()) {
2205 return false;
2206 }
2207 break;
2208 }
2209 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002210 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002211 return false;
2212 }
2213
2214 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002215 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002216 }
2217
2218 return true;
2219}
2220
2221bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002222 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002223 const DexFile::MapItem* item = map->list_;
2224 uint32_t count = map->size_;
2225
2226 // Cross check the items listed in the map.
2227 while (count--) {
2228 uint32_t section_offset = item->offset_;
2229 uint32_t section_count = item->size_;
2230 uint16_t type = item->type_;
2231
2232 switch (type) {
2233 case DexFile::kDexTypeHeaderItem:
2234 case DexFile::kDexTypeMapList:
2235 case DexFile::kDexTypeTypeList:
2236 case DexFile::kDexTypeCodeItem:
2237 case DexFile::kDexTypeStringDataItem:
2238 case DexFile::kDexTypeDebugInfoItem:
2239 case DexFile::kDexTypeAnnotationItem:
2240 case DexFile::kDexTypeEncodedArrayItem:
2241 break;
2242 case DexFile::kDexTypeStringIdItem:
2243 case DexFile::kDexTypeTypeIdItem:
2244 case DexFile::kDexTypeProtoIdItem:
2245 case DexFile::kDexTypeFieldIdItem:
2246 case DexFile::kDexTypeMethodIdItem:
2247 case DexFile::kDexTypeClassDefItem:
2248 case DexFile::kDexTypeAnnotationSetRefList:
2249 case DexFile::kDexTypeAnnotationSetItem:
2250 case DexFile::kDexTypeClassDataItem:
2251 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2252 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2253 return false;
2254 }
2255 break;
2256 }
2257 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002258 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002259 return false;
2260 }
2261
2262 item++;
2263 }
2264
2265 return true;
2266}
2267
2268bool DexFileVerifier::Verify() {
2269 // Check the header.
2270 if (!CheckHeader()) {
2271 return false;
2272 }
2273
2274 // Check the map section.
2275 if (!CheckMap()) {
2276 return false;
2277 }
2278
2279 // Check structure within remaining sections.
2280 if (!CheckIntraSection()) {
2281 return false;
2282 }
2283
2284 // Check references from one section to another.
2285 if (!CheckInterSection()) {
2286 return false;
2287 }
2288
2289 return true;
2290}
2291
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002292void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2293 va_list ap;
2294 va_start(ap, fmt);
2295 DCHECK(failure_reason_.empty()) << failure_reason_;
2296 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2297 StringAppendV(&failure_reason_, fmt, ap);
2298 va_end(ap);
2299}
2300
Andreas Gampee6215c02015-08-31 18:54:38 -07002301// Fields and methods may have only one of public/protected/private.
2302static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2303 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2304 (((flags & kAccProtected) == 0) ? 0 : 1) +
2305 (((flags & kAccPrivate) == 0) ? 0 : 1);
2306 return count <= 1;
2307}
2308
2309bool DexFileVerifier::CheckFieldAccessFlags(uint32_t field_access_flags,
2310 uint32_t class_access_flags,
2311 std::string* error_msg) {
2312 // Generally sort out >16-bit flags.
2313 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
2314 *error_msg = StringPrintf("Bad class_data_item field access_flags %x", field_access_flags);
2315 return false;
2316 }
2317
2318 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2319 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2320 kAccPrivate |
2321 kAccProtected |
2322 kAccStatic |
2323 kAccFinal |
2324 kAccVolatile |
2325 kAccTransient |
2326 kAccSynthetic |
2327 kAccEnum;
2328
2329 // Fields may have only one of public/protected/final.
2330 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
2331 *error_msg = StringPrintf("Field may have only one of public/protected/private, %x",
2332 field_access_flags);
2333 return false;
2334 }
2335
2336 // Interfaces have a pretty restricted list.
2337 if ((class_access_flags & kAccInterface) != 0) {
2338 // Interface fields must be public final static.
2339 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2340 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
2341 *error_msg = StringPrintf("Interface field is not public final static: %x",
2342 field_access_flags);
2343 return false;
2344 }
2345 // Interface fields may be synthetic, but may not have other flags.
2346 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2347 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
2348 *error_msg = StringPrintf("Interface field has disallowed flag: %x", field_access_flags);
2349 return false;
2350 }
2351 return true;
2352 }
2353
2354 // Volatile fields may not be final.
2355 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2356 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
2357 *error_msg = "Fields may not be volatile and final";
2358 return false;
2359 }
2360
2361 return true;
2362}
2363
2364// Try to find the name of the method with the given index. We do not want to rely on DexFile
2365// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
2366// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
2367// (flagged by the return value), otherwise error_msg will contain an error string.
2368static bool FindMethodName(uint32_t method_index,
2369 const uint8_t* begin,
2370 const DexFile::Header* header,
2371 const char** str,
2372 std::string* error_msg) {
2373 if (method_index >= header->method_ids_size_) {
2374 *error_msg = "Method index not available for method flags verification";
2375 return false;
2376 }
2377 uint32_t string_idx =
2378 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
2379 method_index)->name_idx_;
2380 if (string_idx >= header->string_ids_size_) {
2381 *error_msg = "String index not available for method flags verification";
2382 return false;
2383 }
2384 uint32_t string_off =
2385 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
2386 string_data_off_;
2387 if (string_off >= header->file_size_) {
2388 *error_msg = "String offset out of bounds for method flags verification";
2389 return false;
2390 }
2391 const uint8_t* str_data_ptr = begin + string_off;
2392 DecodeUnsignedLeb128(&str_data_ptr);
2393 *str = reinterpret_cast<const char*>(str_data_ptr);
2394 return true;
2395}
2396
2397bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2398 uint32_t method_access_flags,
2399 uint32_t class_access_flags,
2400 bool has_code,
2401 bool expect_direct,
2402 std::string* error_msg) {
2403 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2404 constexpr uint32_t kAllMethodFlags =
2405 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2406 if ((method_access_flags & ~kAllMethodFlags) != 0) {
2407 *error_msg = StringPrintf("Bad class_data_item method access_flags %x", method_access_flags);
2408 return false;
2409 }
2410
2411 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2412 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2413 kAccPrivate |
2414 kAccProtected |
2415 kAccStatic |
2416 kAccFinal |
2417 kAccSynthetic |
2418 kAccSynchronized |
2419 kAccBridge |
2420 kAccVarargs |
2421 kAccNative |
2422 kAccAbstract |
2423 kAccStrict;
2424
2425 // Methods may have only one of public/protected/final.
2426 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
2427 *error_msg = StringPrintf("Method may have only one of public/protected/private, %x",
2428 method_access_flags);
2429 return false;
2430 }
2431
2432 // Try to find the name, to check for constructor properties.
2433 const char* str;
2434 if (!FindMethodName(method_index, begin_, header_, &str, error_msg)) {
2435 return false;
2436 }
2437 bool is_init_by_name = false;
2438 constexpr const char* kInitName = "<init>";
2439 size_t str_offset = (reinterpret_cast<const uint8_t*>(str) - begin_);
2440 if (header_->file_size_ - str_offset >= sizeof(kInitName)) {
2441 is_init_by_name = strcmp(kInitName, str) == 0;
2442 }
2443 bool is_clinit_by_name = false;
2444 constexpr const char* kClinitName = "<clinit>";
2445 if (header_->file_size_ - str_offset >= sizeof(kClinitName)) {
2446 is_clinit_by_name = strcmp(kClinitName, str) == 0;
2447 }
2448 bool is_constructor = is_init_by_name || is_clinit_by_name;
2449
2450 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2451 // the reverse for backwards compatibility reasons.
2452 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor) {
2453 *error_msg = StringPrintf("Method %" PRIu32 " is marked constructor, but doesn't match name",
2454 method_index);
2455 return false;
2456 }
2457 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2458 // instance constructor is called "<init>".
2459 if (is_constructor) {
2460 bool is_static = (method_access_flags & kAccStatic) != 0;
2461 if (is_static ^ is_clinit_by_name) {
2462 *error_msg = StringPrintf("Constructor %" PRIu32 " is not flagged correctly wrt/ static.",
2463 method_index);
2464 return false;
2465 }
2466 }
2467 // Check that static and private methods, as well as constructors, are in the direct methods list,
2468 // and other methods in the virtual methods list.
2469 bool is_direct = (method_access_flags & (kAccStatic | kAccPrivate)) != 0 || is_constructor;
2470 if (is_direct != expect_direct) {
2471 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 " not in expected list %d",
2472 method_index,
2473 expect_direct);
2474 return false;
2475 }
2476
2477
2478 // From here on out it is easier to mask out the bits we're supposed to ignore.
2479 method_access_flags &= kMethodAccessFlags;
2480
2481 // If there aren't any instructions, make sure that's expected.
2482 if (!has_code) {
2483 // Only native or abstract methods may not have code.
2484 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
2485 *error_msg = StringPrintf("Method %" PRIu32 " has no code, but is not marked native or "
2486 "abstract",
2487 method_index);
2488 return false;
2489 }
2490 // Constructors must always have code.
2491 if (is_constructor) {
2492 *error_msg = StringPrintf("Constructor %u must not be abstract or native", method_index);
2493 return false;
2494 }
2495 if ((method_access_flags & kAccAbstract) != 0) {
2496 // Abstract methods are not allowed to have the following flags.
2497 constexpr uint32_t kForbidden =
2498 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2499 if ((method_access_flags & kForbidden) != 0) {
2500 *error_msg = StringPrintf("Abstract method %" PRIu32 " has disallowed access flags %x",
2501 method_index,
2502 method_access_flags);
2503 return false;
2504 }
2505 // Abstract methods must be in an abstract class or interface.
2506 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
2507 *error_msg = StringPrintf("Method %" PRIu32 " is abstract, but the declaring class "
2508 "is neither abstract nor an interface", method_index);
2509 return false;
2510 }
2511 }
2512 // Interfaces are special.
2513 if ((class_access_flags & kAccInterface) != 0) {
2514 // Interface methods must be public and abstract.
2515 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
2516 *error_msg = StringPrintf("Interface method %" PRIu32 " is not public and abstract",
2517 method_index);
2518 return false;
2519 }
2520 // At this point, we know the method is public and abstract. This means that all the checks
2521 // for invalid combinations above applies. In addition, interface methods must not be
2522 // protected. This is caught by the check for only-one-of-public-protected-private.
2523 }
2524 return true;
2525 }
2526
2527 // When there's code, the method must not be native or abstract.
2528 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
2529 *error_msg = StringPrintf("Method %" PRIu32 " has code, but is marked native or abstract",
2530 method_index);
2531 return false;
2532 }
2533
2534 // Only the static initializer may have code in an interface.
Alex Lighteb7c1442015-08-31 13:17:42 -07002535 // TODO We should have some way determine whether to allow this experimental flag without the
2536 // runtime being started.
2537 // We assume experimental flags are enabled when running without a runtime to enable tools like
2538 // dexdump to handle dex files with these features.
2539 if (((class_access_flags & kAccInterface) != 0)
2540 && !is_clinit_by_name
2541 && Runtime::Current() != nullptr
2542 && !Runtime::Current()->AreExperimentalFlagsEnabled(ExperimentalFlags::kDefaultMethods)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07002543 *error_msg = StringPrintf("Non-clinit interface method %" PRIu32 " should not have code",
2544 method_index);
2545 return false;
2546 }
2547
2548 // Instance constructors must not be synchronized and a few other flags.
2549 if (is_init_by_name) {
2550 static constexpr uint32_t kInitAllowed =
2551 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2552 if ((method_access_flags & ~kInitAllowed) != 0) {
2553 *error_msg = StringPrintf("Constructor %" PRIu32 " flagged inappropriately %x",
2554 method_index,
2555 method_access_flags);
2556 return false;
2557 }
2558 }
2559
2560 return true;
2561}
2562
jeffhao10037c82012-01-23 15:06:23 -08002563} // namespace art