blob: 727f4fc65908966ccb0c7606506cc3905c3f54e5 [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)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001419 if (aligned_offset == 0u) {
1420 ErrorStringPrintf("Item %d offset is 0", i);
1421 return false;
1422 }
1423 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1424 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001425 }
1426
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001427 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001428 if (UNLIKELY(aligned_offset > size_)) {
1429 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001430 return false;
1431 }
1432
1433 offset = aligned_offset;
1434 }
1435
1436 return true;
1437}
1438
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001439bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001440 uint32_t expected_offset;
1441 uint32_t expected_size;
1442
1443 // Get the expected offset and size from the header.
1444 switch (type) {
1445 case DexFile::kDexTypeStringIdItem:
1446 expected_offset = header_->string_ids_off_;
1447 expected_size = header_->string_ids_size_;
1448 break;
1449 case DexFile::kDexTypeTypeIdItem:
1450 expected_offset = header_->type_ids_off_;
1451 expected_size = header_->type_ids_size_;
1452 break;
1453 case DexFile::kDexTypeProtoIdItem:
1454 expected_offset = header_->proto_ids_off_;
1455 expected_size = header_->proto_ids_size_;
1456 break;
1457 case DexFile::kDexTypeFieldIdItem:
1458 expected_offset = header_->field_ids_off_;
1459 expected_size = header_->field_ids_size_;
1460 break;
1461 case DexFile::kDexTypeMethodIdItem:
1462 expected_offset = header_->method_ids_off_;
1463 expected_size = header_->method_ids_size_;
1464 break;
1465 case DexFile::kDexTypeClassDefItem:
1466 expected_offset = header_->class_defs_off_;
1467 expected_size = header_->class_defs_size_;
1468 break;
1469 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001470 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001471 return false;
1472 }
1473
1474 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001475 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001476 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001477 return false;
1478 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001479 if (UNLIKELY(count != expected_size)) {
1480 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001481 return false;
1482 }
1483
1484 return CheckIntraSectionIterate(offset, count, type);
1485}
1486
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001487bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count, uint16_t type) {
1488 size_t data_start = header_->data_off_;
1489 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001490
1491 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001492 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001493 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001494 return false;
1495 }
1496
1497 if (!CheckIntraSectionIterate(offset, count, type)) {
1498 return false;
1499 }
1500
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001501 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001502 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001503 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001504 return false;
1505 }
1506
1507 return true;
1508}
1509
1510bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001511 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001512 const DexFile::MapItem* item = map->list_;
1513
1514 uint32_t count = map->size_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001515 size_t offset = 0;
Ian Rogers30fab402012-01-23 15:43:46 -08001516 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001517
1518 // Check the items listed in the map.
1519 while (count--) {
1520 uint32_t section_offset = item->offset_;
1521 uint32_t section_count = item->size_;
1522 uint16_t type = item->type_;
1523
1524 // Check for padding and overlap between items.
1525 if (!CheckPadding(offset, section_offset)) {
1526 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001527 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001528 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001529 return false;
1530 }
1531
1532 // Check each item based on its type.
1533 switch (type) {
1534 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001535 if (UNLIKELY(section_count != 1)) {
1536 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001537 return false;
1538 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001539 if (UNLIKELY(section_offset != 0)) {
1540 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001541 return false;
1542 }
Ian Rogers30fab402012-01-23 15:43:46 -08001543 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001544 offset = header_->header_size_;
1545 break;
1546 case DexFile::kDexTypeStringIdItem:
1547 case DexFile::kDexTypeTypeIdItem:
1548 case DexFile::kDexTypeProtoIdItem:
1549 case DexFile::kDexTypeFieldIdItem:
1550 case DexFile::kDexTypeMethodIdItem:
1551 case DexFile::kDexTypeClassDefItem:
1552 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1553 return false;
1554 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001555 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001556 break;
1557 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001558 if (UNLIKELY(section_count != 1)) {
1559 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001560 return false;
1561 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001562 if (UNLIKELY(section_offset != header_->map_off_)) {
1563 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1564 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001565 return false;
1566 }
1567 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1568 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1569 break;
1570 case DexFile::kDexTypeTypeList:
1571 case DexFile::kDexTypeAnnotationSetRefList:
1572 case DexFile::kDexTypeAnnotationSetItem:
1573 case DexFile::kDexTypeClassDataItem:
1574 case DexFile::kDexTypeCodeItem:
1575 case DexFile::kDexTypeStringDataItem:
1576 case DexFile::kDexTypeDebugInfoItem:
1577 case DexFile::kDexTypeAnnotationItem:
1578 case DexFile::kDexTypeEncodedArrayItem:
1579 case DexFile::kDexTypeAnnotationsDirectoryItem:
1580 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1581 return false;
1582 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001583 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001584 break;
1585 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001586 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001587 return false;
1588 }
1589
1590 item++;
1591 }
1592
1593 return true;
1594}
1595
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001596bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001597 DCHECK_NE(offset, 0u);
1598 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001599 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001600 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001601 return false;
1602 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001603 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001604 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001605 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001606 return false;
1607 }
1608 return true;
1609}
1610
Ian Rogers13735952014-10-08 12:43:28 -07001611uint16_t DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001612 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001613 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001614
1615 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001616 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
1617 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001618 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001619 }
1620
1621 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001622 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
1623 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001624 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001625 }
1626
1627 return DexFile::kDexNoIndex16;
1628}
1629
Ian Rogers13735952014-10-08 12:43:28 -07001630uint16_t DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001631 const DexFile::AnnotationsDirectoryItem* item =
1632 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001633 *success = true;
1634
jeffhao10037c82012-01-23 15:06:23 -08001635 if (item->fields_size_ != 0) {
1636 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001637 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
1638 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001639 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001640 }
1641
1642 if (item->methods_size_ != 0) {
1643 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001644 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001645 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001646 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001647 }
1648
1649 if (item->parameters_size_ != 0) {
1650 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001651 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001652 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001653 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001654 }
1655
1656 return DexFile::kDexNoIndex16;
1657}
1658
1659bool DexFileVerifier::CheckInterStringIdItem() {
1660 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1661
1662 // Check the map to make sure it has the right offset->type.
1663 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1664 return false;
1665 }
1666
1667 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001668 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001669 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1670 const char* prev_str = dex_file_->GetStringData(*prev_item);
1671 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001672 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1673 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001674 return false;
1675 }
1676 }
1677
1678 ptr_ += sizeof(DexFile::StringId);
1679 return true;
1680}
1681
1682bool DexFileVerifier::CheckInterTypeIdItem() {
1683 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001684
1685 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001686
1687 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001688 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1689 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001690 return false;
1691 }
1692
1693 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001694 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001695 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001696 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1697 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
1698 prev_item->descriptor_idx_, item->descriptor_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001699 return false;
1700 }
1701 }
1702
1703 ptr_ += sizeof(DexFile::TypeId);
1704 return true;
1705}
1706
1707bool DexFileVerifier::CheckInterProtoIdItem() {
1708 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001709
1710 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1711
jeffhao10037c82012-01-23 15:06:23 -08001712 if (item->parameters_off_ != 0 &&
1713 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1714 return false;
1715 }
1716
1717 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001718 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1719 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001720 return false;
1721 }
1722 shorty++;
1723
1724 DexFileParameterIterator it(*dex_file_, *item);
1725 while (it.HasNext() && *shorty != '\0') {
Andreas Gampebb836e12014-06-13 15:31:40 -07001726 if (!CheckIndex(it.GetTypeIdx(), dex_file_->NumTypeIds(),
1727 "inter_proto_id_item shorty type_idx")) {
1728 return false;
1729 }
jeffhao10037c82012-01-23 15:06:23 -08001730 const char* descriptor = it.GetDescriptor();
1731 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1732 return false;
1733 }
1734 it.Next();
1735 shorty++;
1736 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001737 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1738 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001739 return false;
1740 }
1741
1742 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001743 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001744 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001745 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1746 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001747 return false;
1748 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1749 DexFileParameterIterator curr_it(*dex_file_, *item);
1750 DexFileParameterIterator prev_it(*dex_file_, *prev);
1751
1752 while (curr_it.HasNext() && prev_it.HasNext()) {
1753 uint16_t prev_idx = prev_it.GetTypeIdx();
1754 uint16_t curr_idx = curr_it.GetTypeIdx();
1755 if (prev_idx == DexFile::kDexNoIndex16) {
1756 break;
1757 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001758 if (UNLIKELY(curr_idx == DexFile::kDexNoIndex16)) {
1759 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001760 return false;
1761 }
1762
1763 if (prev_idx < curr_idx) {
1764 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001765 } else if (UNLIKELY(prev_idx > curr_idx)) {
1766 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001767 return false;
1768 }
1769
1770 prev_it.Next();
1771 curr_it.Next();
1772 }
1773 }
1774 }
1775
1776 ptr_ += sizeof(DexFile::ProtoId);
1777 return true;
1778}
1779
1780bool DexFileVerifier::CheckInterFieldIdItem() {
1781 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1782
1783 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001784 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1785 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1786 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001787 return false;
1788 }
1789
1790 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001791 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1792 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1793 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001794 return false;
1795 }
1796
1797 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001798 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001799 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1800 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001801 return false;
1802 }
1803
1804 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001805 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001806 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001807 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1808 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001809 return false;
1810 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001811 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1812 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001813 return false;
1814 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001815 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
1816 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001817 return false;
1818 }
1819 }
1820 }
1821 }
1822
1823 ptr_ += sizeof(DexFile::FieldId);
1824 return true;
1825}
1826
1827bool DexFileVerifier::CheckInterMethodIdItem() {
1828 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
1829
1830 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001831 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
1832 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
1833 class_descriptor[0] != '['))) {
1834 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001835 return false;
1836 }
1837
1838 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07001839 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001840 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1841 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001842 return false;
1843 }
1844
Andreas Gampedf10b322014-06-11 21:46:05 -07001845 // Check that the proto id is valid.
1846 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
1847 "inter_method_id_item proto_idx"))) {
1848 return false;
1849 }
1850
jeffhao10037c82012-01-23 15:06:23 -08001851 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001852 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001853 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001854 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1855 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001856 return false;
1857 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001858 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1859 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001860 return false;
1861 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001862 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
1863 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001864 return false;
1865 }
1866 }
1867 }
1868 }
1869
1870 ptr_ += sizeof(DexFile::MethodId);
1871 return true;
1872}
1873
1874bool DexFileVerifier::CheckInterClassDefItem() {
1875 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001876
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001877 // Check for duplicate class def.
1878 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
1879 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_);
1880 return false;
1881 }
1882 defined_classes_.insert(item->class_idx_);
1883
Andreas Gampee09269c2014-06-06 18:45:35 -07001884 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
1885 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1886 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001887 return false;
1888 }
1889
Andreas Gampeacc2bb62014-07-17 19:26:50 -07001890 // Only allow non-runtime modifiers.
1891 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
1892 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
1893 return false;
1894 }
1895
jeffhao10037c82012-01-23 15:06:23 -08001896 if (item->interfaces_off_ != 0 &&
1897 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
1898 return false;
1899 }
1900 if (item->annotations_off_ != 0 &&
1901 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
1902 return false;
1903 }
1904 if (item->class_data_off_ != 0 &&
1905 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
1906 return false;
1907 }
1908 if (item->static_values_off_ != 0 &&
1909 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
1910 return false;
1911 }
1912
1913 if (item->superclass_idx_ != DexFile::kDexNoIndex16) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001914 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
1915 "inter_class_def_item superclass_idx")
1916 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
1917 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001918 return false;
1919 }
1920 }
1921
1922 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001923 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001924 uint32_t size = interfaces->Size();
1925
1926 // Ensure that all interfaces refer to classes (not arrays or primitives).
1927 for (uint32_t i = 0; i < size; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001928 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
1929 "inter_class_def_item interface type_idx")
1930 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
1931 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001932 return false;
1933 }
1934 }
1935
1936 /*
1937 * Ensure that there are no duplicates. This is an O(N^2) test, but in
1938 * practice the number of interfaces implemented by any given class is low.
1939 */
1940 for (uint32_t i = 1; i < size; i++) {
1941 uint32_t idx1 = interfaces->GetTypeItem(i).type_idx_;
1942 for (uint32_t j =0; j < i; j++) {
1943 uint32_t idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001944 if (UNLIKELY(idx1 == idx2)) {
1945 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08001946 return false;
1947 }
1948 }
1949 }
1950 }
1951
1952 // Check that references in class_data_item are to the right class.
1953 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001954 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001955 bool success;
1956 uint16_t data_definer = FindFirstClassDataDefiner(data, &success);
1957 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001958 return false;
1959 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001960 if (UNLIKELY((data_definer != item->class_idx_) && (data_definer != DexFile::kDexNoIndex16))) {
1961 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08001962 return false;
1963 }
1964 }
1965
1966 // Check that references in annotations_directory_item are to right class.
1967 if (item->annotations_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001968 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001969 bool success;
1970 uint16_t annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
1971 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001972 return false;
1973 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001974 if (UNLIKELY((annotations_definer != item->class_idx_) &&
1975 (annotations_definer != DexFile::kDexNoIndex16))) {
1976 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08001977 return false;
1978 }
1979 }
1980
1981 ptr_ += sizeof(DexFile::ClassDef);
1982 return true;
1983}
1984
1985bool DexFileVerifier::CheckInterAnnotationSetRefList() {
1986 const DexFile::AnnotationSetRefList* list =
1987 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
1988 const DexFile::AnnotationSetRefItem* item = list->list_;
1989 uint32_t count = list->size_;
1990
1991 while (count--) {
1992 if (item->annotations_off_ != 0 &&
1993 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
1994 return false;
1995 }
1996 item++;
1997 }
1998
Ian Rogers13735952014-10-08 12:43:28 -07001999 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002000 return true;
2001}
2002
2003bool DexFileVerifier::CheckInterAnnotationSetItem() {
2004 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2005 const uint32_t* offsets = set->entries_;
2006 uint32_t count = set->size_;
2007 uint32_t last_idx = 0;
2008
2009 for (uint32_t i = 0; i < count; i++) {
2010 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2011 return false;
2012 }
2013
2014 // Get the annotation from the offset and the type index for the annotation.
2015 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002016 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002017 const uint8_t* data = annotation->annotation_;
2018 uint32_t idx = DecodeUnsignedLeb128(&data);
2019
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002020 if (UNLIKELY(last_idx >= idx && i != 0)) {
2021 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002022 return false;
2023 }
2024
2025 last_idx = idx;
2026 offsets++;
2027 }
2028
Ian Rogers13735952014-10-08 12:43:28 -07002029 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002030 return true;
2031}
2032
2033bool DexFileVerifier::CheckInterClassDataItem() {
2034 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002035 bool success;
2036 uint16_t defining_class = FindFirstClassDataDefiner(ptr_, &success);
2037 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002038 return false;
2039 }
jeffhao10037c82012-01-23 15:06:23 -08002040
2041 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002042 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002043 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002044 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002045 return false;
2046 }
2047 }
2048 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2049 uint32_t code_off = it.GetMethodCodeItemOffset();
2050 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2051 return false;
2052 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002053 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002054 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002055 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002056 return false;
2057 }
2058 }
2059
2060 ptr_ = it.EndDataPointer();
2061 return true;
2062}
2063
2064bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2065 const DexFile::AnnotationsDirectoryItem* item =
2066 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002067 bool success;
2068 uint16_t defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
2069 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002070 return false;
2071 }
jeffhao10037c82012-01-23 15:06:23 -08002072
2073 if (item->class_annotations_off_ != 0 &&
2074 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2075 return false;
2076 }
2077
2078 // Field annotations follow immediately after the annotations directory.
2079 const DexFile::FieldAnnotationsItem* field_item =
2080 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2081 uint32_t field_count = item->fields_size_;
2082 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002083 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2084 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002085 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002086 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002087 return false;
2088 }
2089 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2090 return false;
2091 }
2092 field_item++;
2093 }
2094
2095 // Method annotations follow immediately after field annotations.
2096 const DexFile::MethodAnnotationsItem* method_item =
2097 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2098 uint32_t method_count = item->methods_size_;
2099 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002100 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002101 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002102 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002103 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002104 return false;
2105 }
2106 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2107 return false;
2108 }
2109 method_item++;
2110 }
2111
2112 // Parameter annotations follow immediately after method annotations.
2113 const DexFile::ParameterAnnotationsItem* parameter_item =
2114 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2115 uint32_t parameter_count = item->parameters_size_;
2116 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002117 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002118 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002119 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002120 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002121 return false;
2122 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002123 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2124 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002125 return false;
2126 }
2127 parameter_item++;
2128 }
2129
Ian Rogers13735952014-10-08 12:43:28 -07002130 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002131 return true;
2132}
2133
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002134bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002135 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002136 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002137 switch (type) {
2138 case DexFile::kDexTypeClassDataItem:
2139 alignment_mask = sizeof(uint8_t) - 1;
2140 break;
2141 default:
2142 alignment_mask = sizeof(uint32_t) - 1;
2143 break;
2144 }
2145
2146 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002147 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002148 for (uint32_t i = 0; i < count; i++) {
2149 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002150 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002151 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002152
2153 // Check depending on the section type.
2154 switch (type) {
2155 case DexFile::kDexTypeStringIdItem: {
2156 if (!CheckInterStringIdItem()) {
2157 return false;
2158 }
2159 break;
2160 }
2161 case DexFile::kDexTypeTypeIdItem: {
2162 if (!CheckInterTypeIdItem()) {
2163 return false;
2164 }
2165 break;
2166 }
2167 case DexFile::kDexTypeProtoIdItem: {
2168 if (!CheckInterProtoIdItem()) {
2169 return false;
2170 }
2171 break;
2172 }
2173 case DexFile::kDexTypeFieldIdItem: {
2174 if (!CheckInterFieldIdItem()) {
2175 return false;
2176 }
2177 break;
2178 }
2179 case DexFile::kDexTypeMethodIdItem: {
2180 if (!CheckInterMethodIdItem()) {
2181 return false;
2182 }
2183 break;
2184 }
2185 case DexFile::kDexTypeClassDefItem: {
2186 if (!CheckInterClassDefItem()) {
2187 return false;
2188 }
2189 break;
2190 }
2191 case DexFile::kDexTypeAnnotationSetRefList: {
2192 if (!CheckInterAnnotationSetRefList()) {
2193 return false;
2194 }
2195 break;
2196 }
2197 case DexFile::kDexTypeAnnotationSetItem: {
2198 if (!CheckInterAnnotationSetItem()) {
2199 return false;
2200 }
2201 break;
2202 }
2203 case DexFile::kDexTypeClassDataItem: {
2204 if (!CheckInterClassDataItem()) {
2205 return false;
2206 }
2207 break;
2208 }
2209 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2210 if (!CheckInterAnnotationsDirectoryItem()) {
2211 return false;
2212 }
2213 break;
2214 }
2215 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002216 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002217 return false;
2218 }
2219
2220 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002221 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002222 }
2223
2224 return true;
2225}
2226
2227bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002228 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002229 const DexFile::MapItem* item = map->list_;
2230 uint32_t count = map->size_;
2231
2232 // Cross check the items listed in the map.
2233 while (count--) {
2234 uint32_t section_offset = item->offset_;
2235 uint32_t section_count = item->size_;
2236 uint16_t type = item->type_;
2237
2238 switch (type) {
2239 case DexFile::kDexTypeHeaderItem:
2240 case DexFile::kDexTypeMapList:
2241 case DexFile::kDexTypeTypeList:
2242 case DexFile::kDexTypeCodeItem:
2243 case DexFile::kDexTypeStringDataItem:
2244 case DexFile::kDexTypeDebugInfoItem:
2245 case DexFile::kDexTypeAnnotationItem:
2246 case DexFile::kDexTypeEncodedArrayItem:
2247 break;
2248 case DexFile::kDexTypeStringIdItem:
2249 case DexFile::kDexTypeTypeIdItem:
2250 case DexFile::kDexTypeProtoIdItem:
2251 case DexFile::kDexTypeFieldIdItem:
2252 case DexFile::kDexTypeMethodIdItem:
2253 case DexFile::kDexTypeClassDefItem:
2254 case DexFile::kDexTypeAnnotationSetRefList:
2255 case DexFile::kDexTypeAnnotationSetItem:
2256 case DexFile::kDexTypeClassDataItem:
2257 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2258 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2259 return false;
2260 }
2261 break;
2262 }
2263 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002264 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002265 return false;
2266 }
2267
2268 item++;
2269 }
2270
2271 return true;
2272}
2273
2274bool DexFileVerifier::Verify() {
2275 // Check the header.
2276 if (!CheckHeader()) {
2277 return false;
2278 }
2279
2280 // Check the map section.
2281 if (!CheckMap()) {
2282 return false;
2283 }
2284
2285 // Check structure within remaining sections.
2286 if (!CheckIntraSection()) {
2287 return false;
2288 }
2289
2290 // Check references from one section to another.
2291 if (!CheckInterSection()) {
2292 return false;
2293 }
2294
2295 return true;
2296}
2297
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002298void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2299 va_list ap;
2300 va_start(ap, fmt);
2301 DCHECK(failure_reason_.empty()) << failure_reason_;
2302 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2303 StringAppendV(&failure_reason_, fmt, ap);
2304 va_end(ap);
2305}
2306
Andreas Gampee6215c02015-08-31 18:54:38 -07002307// Fields and methods may have only one of public/protected/private.
2308static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2309 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2310 (((flags & kAccProtected) == 0) ? 0 : 1) +
2311 (((flags & kAccPrivate) == 0) ? 0 : 1);
2312 return count <= 1;
2313}
2314
2315bool DexFileVerifier::CheckFieldAccessFlags(uint32_t field_access_flags,
2316 uint32_t class_access_flags,
2317 std::string* error_msg) {
2318 // Generally sort out >16-bit flags.
2319 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
2320 *error_msg = StringPrintf("Bad class_data_item field access_flags %x", field_access_flags);
2321 return false;
2322 }
2323
2324 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2325 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2326 kAccPrivate |
2327 kAccProtected |
2328 kAccStatic |
2329 kAccFinal |
2330 kAccVolatile |
2331 kAccTransient |
2332 kAccSynthetic |
2333 kAccEnum;
2334
2335 // Fields may have only one of public/protected/final.
2336 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
2337 *error_msg = StringPrintf("Field may have only one of public/protected/private, %x",
2338 field_access_flags);
2339 return false;
2340 }
2341
2342 // Interfaces have a pretty restricted list.
2343 if ((class_access_flags & kAccInterface) != 0) {
2344 // Interface fields must be public final static.
2345 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2346 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
2347 *error_msg = StringPrintf("Interface field is not public final static: %x",
2348 field_access_flags);
2349 return false;
2350 }
2351 // Interface fields may be synthetic, but may not have other flags.
2352 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2353 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
2354 *error_msg = StringPrintf("Interface field has disallowed flag: %x", field_access_flags);
2355 return false;
2356 }
2357 return true;
2358 }
2359
2360 // Volatile fields may not be final.
2361 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2362 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
2363 *error_msg = "Fields may not be volatile and final";
2364 return false;
2365 }
2366
2367 return true;
2368}
2369
2370// Try to find the name of the method with the given index. We do not want to rely on DexFile
2371// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
2372// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
2373// (flagged by the return value), otherwise error_msg will contain an error string.
2374static bool FindMethodName(uint32_t method_index,
2375 const uint8_t* begin,
2376 const DexFile::Header* header,
2377 const char** str,
2378 std::string* error_msg) {
2379 if (method_index >= header->method_ids_size_) {
2380 *error_msg = "Method index not available for method flags verification";
2381 return false;
2382 }
2383 uint32_t string_idx =
2384 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
2385 method_index)->name_idx_;
2386 if (string_idx >= header->string_ids_size_) {
2387 *error_msg = "String index not available for method flags verification";
2388 return false;
2389 }
2390 uint32_t string_off =
2391 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
2392 string_data_off_;
2393 if (string_off >= header->file_size_) {
2394 *error_msg = "String offset out of bounds for method flags verification";
2395 return false;
2396 }
2397 const uint8_t* str_data_ptr = begin + string_off;
2398 DecodeUnsignedLeb128(&str_data_ptr);
2399 *str = reinterpret_cast<const char*>(str_data_ptr);
2400 return true;
2401}
2402
2403bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2404 uint32_t method_access_flags,
2405 uint32_t class_access_flags,
2406 bool has_code,
2407 bool expect_direct,
2408 std::string* error_msg) {
2409 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2410 constexpr uint32_t kAllMethodFlags =
2411 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2412 if ((method_access_flags & ~kAllMethodFlags) != 0) {
2413 *error_msg = StringPrintf("Bad class_data_item method access_flags %x", method_access_flags);
2414 return false;
2415 }
2416
2417 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2418 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2419 kAccPrivate |
2420 kAccProtected |
2421 kAccStatic |
2422 kAccFinal |
2423 kAccSynthetic |
2424 kAccSynchronized |
2425 kAccBridge |
2426 kAccVarargs |
2427 kAccNative |
2428 kAccAbstract |
2429 kAccStrict;
2430
2431 // Methods may have only one of public/protected/final.
2432 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
2433 *error_msg = StringPrintf("Method may have only one of public/protected/private, %x",
2434 method_access_flags);
2435 return false;
2436 }
2437
2438 // Try to find the name, to check for constructor properties.
2439 const char* str;
2440 if (!FindMethodName(method_index, begin_, header_, &str, error_msg)) {
2441 return false;
2442 }
2443 bool is_init_by_name = false;
2444 constexpr const char* kInitName = "<init>";
2445 size_t str_offset = (reinterpret_cast<const uint8_t*>(str) - begin_);
2446 if (header_->file_size_ - str_offset >= sizeof(kInitName)) {
2447 is_init_by_name = strcmp(kInitName, str) == 0;
2448 }
2449 bool is_clinit_by_name = false;
2450 constexpr const char* kClinitName = "<clinit>";
2451 if (header_->file_size_ - str_offset >= sizeof(kClinitName)) {
2452 is_clinit_by_name = strcmp(kClinitName, str) == 0;
2453 }
2454 bool is_constructor = is_init_by_name || is_clinit_by_name;
2455
2456 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2457 // the reverse for backwards compatibility reasons.
2458 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor) {
2459 *error_msg = StringPrintf("Method %" PRIu32 " is marked constructor, but doesn't match name",
2460 method_index);
2461 return false;
2462 }
2463 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2464 // instance constructor is called "<init>".
2465 if (is_constructor) {
2466 bool is_static = (method_access_flags & kAccStatic) != 0;
2467 if (is_static ^ is_clinit_by_name) {
2468 *error_msg = StringPrintf("Constructor %" PRIu32 " is not flagged correctly wrt/ static.",
2469 method_index);
2470 return false;
2471 }
2472 }
2473 // Check that static and private methods, as well as constructors, are in the direct methods list,
2474 // and other methods in the virtual methods list.
2475 bool is_direct = (method_access_flags & (kAccStatic | kAccPrivate)) != 0 || is_constructor;
2476 if (is_direct != expect_direct) {
2477 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 " not in expected list %d",
2478 method_index,
2479 expect_direct);
2480 return false;
2481 }
2482
2483
2484 // From here on out it is easier to mask out the bits we're supposed to ignore.
2485 method_access_flags &= kMethodAccessFlags;
2486
2487 // If there aren't any instructions, make sure that's expected.
2488 if (!has_code) {
2489 // Only native or abstract methods may not have code.
2490 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
2491 *error_msg = StringPrintf("Method %" PRIu32 " has no code, but is not marked native or "
2492 "abstract",
2493 method_index);
2494 return false;
2495 }
2496 // Constructors must always have code.
2497 if (is_constructor) {
2498 *error_msg = StringPrintf("Constructor %u must not be abstract or native", method_index);
2499 return false;
2500 }
2501 if ((method_access_flags & kAccAbstract) != 0) {
2502 // Abstract methods are not allowed to have the following flags.
2503 constexpr uint32_t kForbidden =
2504 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2505 if ((method_access_flags & kForbidden) != 0) {
2506 *error_msg = StringPrintf("Abstract method %" PRIu32 " has disallowed access flags %x",
2507 method_index,
2508 method_access_flags);
2509 return false;
2510 }
Andreas Gampe97b11352015-12-10 16:23:41 -08002511 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07002512 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampe97b11352015-12-10 16:23:41 -08002513 LOG(WARNING) << "Method " << PrettyMethod(method_index, *dex_file_)
2514 << " is abstract, but the declaring class is neither abstract nor an "
2515 << "interface in dex file "
2516 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07002517 }
2518 }
2519 // Interfaces are special.
2520 if ((class_access_flags & kAccInterface) != 0) {
2521 // Interface methods must be public and abstract.
2522 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
2523 *error_msg = StringPrintf("Interface method %" PRIu32 " is not public and abstract",
2524 method_index);
2525 return false;
2526 }
2527 // At this point, we know the method is public and abstract. This means that all the checks
2528 // for invalid combinations above applies. In addition, interface methods must not be
2529 // protected. This is caught by the check for only-one-of-public-protected-private.
2530 }
2531 return true;
2532 }
2533
2534 // When there's code, the method must not be native or abstract.
2535 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
2536 *error_msg = StringPrintf("Method %" PRIu32 " has code, but is marked native or abstract",
2537 method_index);
2538 return false;
2539 }
2540
2541 // Only the static initializer may have code in an interface.
Alex Lighteb7c1442015-08-31 13:17:42 -07002542 // TODO We should have some way determine whether to allow this experimental flag without the
2543 // runtime being started.
2544 // We assume experimental flags are enabled when running without a runtime to enable tools like
2545 // dexdump to handle dex files with these features.
2546 if (((class_access_flags & kAccInterface) != 0)
2547 && !is_clinit_by_name
2548 && Runtime::Current() != nullptr
2549 && !Runtime::Current()->AreExperimentalFlagsEnabled(ExperimentalFlags::kDefaultMethods)) {
Andreas Gampee6215c02015-08-31 18:54:38 -07002550 *error_msg = StringPrintf("Non-clinit interface method %" PRIu32 " should not have code",
2551 method_index);
2552 return false;
2553 }
2554
2555 // Instance constructors must not be synchronized and a few other flags.
2556 if (is_init_by_name) {
2557 static constexpr uint32_t kInitAllowed =
2558 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2559 if ((method_access_flags & ~kInitAllowed) != 0) {
2560 *error_msg = StringPrintf("Constructor %" PRIu32 " flagged inappropriately %x",
2561 method_index,
2562 method_access_flags);
2563 return false;
2564 }
2565 }
2566
2567 return true;
2568}
2569
jeffhao10037c82012-01-23 15:06:23 -08002570} // namespace art