blob: 3df4e98c84ebb4477356d1b948cc34b994fc5f09 [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 Gampeb512c0e2016-02-19 19:45:34 -0800233bool DexFileVerifier::CheckValidOffsetAndSize(uint32_t offset,
234 uint32_t size,
235 size_t alignment,
236 const char* label) {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700237 if (size == 0) {
238 if (offset != 0) {
239 ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
240 return false;
241 }
242 }
243 if (size_ <= offset) {
244 ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, size_, label);
245 return false;
246 }
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800247 if (alignment != 0 && !IsAlignedParam(offset, alignment)) {
248 ErrorStringPrintf("Offset(%d) should be aligned by %zu for %s.", offset, alignment, label);
249 return false;
250 }
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700251 return true;
252}
253
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700254bool DexFileVerifier::CheckHeader() {
jeffhaof6174e82012-01-31 16:14:17 -0800255 // Check file size from the header.
256 uint32_t expected_size = header_->file_size_;
257 if (size_ != expected_size) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700258 ErrorStringPrintf("Bad file size (%zd, expected %ud)", size_, expected_size);
jeffhao10037c82012-01-23 15:06:23 -0800259 return false;
260 }
261
262 // Compute and verify the checksum in the header.
263 uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
264 const uint32_t non_sum = sizeof(header_->magic_) + sizeof(header_->checksum_);
Ian Rogers13735952014-10-08 12:43:28 -0700265 const uint8_t* non_sum_ptr = reinterpret_cast<const uint8_t*>(header_) + non_sum;
jeffhaof6174e82012-01-31 16:14:17 -0800266 adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
jeffhao10037c82012-01-23 15:06:23 -0800267 if (adler_checksum != header_->checksum_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700268 ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, header_->checksum_);
jeffhao10037c82012-01-23 15:06:23 -0800269 return false;
270 }
271
272 // Check the contents of the header.
273 if (header_->endian_tag_ != DexFile::kDexEndianConstant) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700274 ErrorStringPrintf("Unexpected endian_tag: %x", header_->endian_tag_);
jeffhao10037c82012-01-23 15:06:23 -0800275 return false;
276 }
277
278 if (header_->header_size_ != sizeof(DexFile::Header)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700279 ErrorStringPrintf("Bad header size: %ud", header_->header_size_);
jeffhao10037c82012-01-23 15:06:23 -0800280 return false;
281 }
282
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700283 // Check that all offsets are inside the file.
284 bool result =
Andreas Gampeb512c0e2016-02-19 19:45:34 -0800285 CheckValidOffsetAndSize(header_->link_off_,
286 header_->link_size_,
287 0 /* unaligned */,
288 "link") &&
289 CheckValidOffsetAndSize(header_->map_off_,
290 header_->map_off_,
291 4,
292 "map") &&
293 CheckValidOffsetAndSize(header_->string_ids_off_,
294 header_->string_ids_size_,
295 4,
296 "string-ids") &&
297 CheckValidOffsetAndSize(header_->type_ids_off_,
298 header_->type_ids_size_,
299 4,
300 "type-ids") &&
301 CheckValidOffsetAndSize(header_->proto_ids_off_,
302 header_->proto_ids_size_,
303 4,
304 "proto-ids") &&
305 CheckValidOffsetAndSize(header_->field_ids_off_,
306 header_->field_ids_size_,
307 4,
308 "field-ids") &&
309 CheckValidOffsetAndSize(header_->method_ids_off_,
310 header_->method_ids_size_,
311 4,
312 "method-ids") &&
313 CheckValidOffsetAndSize(header_->class_defs_off_,
314 header_->class_defs_size_,
315 4,
316 "class-defs") &&
317 CheckValidOffsetAndSize(header_->data_off_,
318 header_->data_size_,
319 0, // Unaligned, spec doesn't talk about it, even though size
320 // is supposed to be a multiple of 4.
321 "data");
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700322 return result;
jeffhao10037c82012-01-23 15:06:23 -0800323}
324
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700325bool DexFileVerifier::CheckMap() {
Andreas Gamped4ae41f2014-09-02 11:17:34 -0700326 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ +
327 header_->map_off_);
328 // Check that map list content is available.
329 if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
330 return false;
331 }
332
jeffhao10037c82012-01-23 15:06:23 -0800333 const DexFile::MapItem* item = map->list_;
334
335 uint32_t count = map->size_;
336 uint32_t last_offset = 0;
337 uint32_t data_item_count = 0;
338 uint32_t data_items_left = header_->data_size_;
339 uint32_t used_bits = 0;
340
341 // Sanity check the size of the map list.
342 if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
343 return false;
344 }
345
346 // Check the items listed in the map.
347 for (uint32_t i = 0; i < count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700348 if (UNLIKELY(last_offset >= item->offset_ && i != 0)) {
349 ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->offset_);
jeffhao10037c82012-01-23 15:06:23 -0800350 return false;
351 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700352 if (UNLIKELY(item->offset_ >= header_->file_size_)) {
353 ErrorStringPrintf("Map item after end of file: %x, size %x",
354 item->offset_, header_->file_size_);
jeffhao10037c82012-01-23 15:06:23 -0800355 return false;
356 }
357
358 if (IsDataSectionType(item->type_)) {
359 uint32_t icount = item->size_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700360 if (UNLIKELY(icount > data_items_left)) {
361 ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
jeffhao10037c82012-01-23 15:06:23 -0800362 return false;
363 }
364 data_items_left -= icount;
365 data_item_count += icount;
366 }
367
368 uint32_t bit = MapTypeToBitMask(item->type_);
369
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700370 if (UNLIKELY(bit == 0)) {
371 ErrorStringPrintf("Unknown map section type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800372 return false;
373 }
374
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700375 if (UNLIKELY((used_bits & bit) != 0)) {
376 ErrorStringPrintf("Duplicate map section of type %x", item->type_);
jeffhao10037c82012-01-23 15:06:23 -0800377 return false;
378 }
379
380 used_bits |= bit;
381 last_offset = item->offset_;
382 item++;
383 }
384
385 // Check for missing sections in the map.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700386 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0)) {
387 ErrorStringPrintf("Map is missing header entry");
jeffhao10037c82012-01-23 15:06:23 -0800388 return false;
389 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700390 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0)) {
391 ErrorStringPrintf("Map is missing map_list entry");
jeffhao10037c82012-01-23 15:06:23 -0800392 return false;
393 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700394 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
395 ((header_->string_ids_off_ != 0) || (header_->string_ids_size_ != 0)))) {
396 ErrorStringPrintf("Map is missing string_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800397 return false;
398 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700399 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
400 ((header_->type_ids_off_ != 0) || (header_->type_ids_size_ != 0)))) {
401 ErrorStringPrintf("Map is missing type_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800402 return false;
403 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700404 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
405 ((header_->proto_ids_off_ != 0) || (header_->proto_ids_size_ != 0)))) {
406 ErrorStringPrintf("Map is missing proto_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800407 return false;
408 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700409 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
410 ((header_->field_ids_off_ != 0) || (header_->field_ids_size_ != 0)))) {
411 ErrorStringPrintf("Map is missing field_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800412 return false;
413 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700414 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
415 ((header_->method_ids_off_ != 0) || (header_->method_ids_size_ != 0)))) {
416 ErrorStringPrintf("Map is missing method_ids entry");
jeffhao10037c82012-01-23 15:06:23 -0800417 return false;
418 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700419 if (UNLIKELY((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
420 ((header_->class_defs_off_ != 0) || (header_->class_defs_size_ != 0)))) {
421 ErrorStringPrintf("Map is missing class_defs entry");
jeffhao10037c82012-01-23 15:06:23 -0800422 return false;
423 }
jeffhao10037c82012-01-23 15:06:23 -0800424 return true;
425}
426
427uint32_t DexFileVerifier::ReadUnsignedLittleEndian(uint32_t size) {
428 uint32_t result = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700429 if (LIKELY(CheckListSize(ptr_, size, sizeof(uint8_t), "encoded_value"))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700430 for (uint32_t i = 0; i < size; i++) {
431 result |= ((uint32_t) *(ptr_++)) << (i * 8);
432 }
jeffhao10037c82012-01-23 15:06:23 -0800433 }
jeffhao10037c82012-01-23 15:06:23 -0800434 return result;
435}
436
437bool DexFileVerifier::CheckAndGetHandlerOffsets(const DexFile::CodeItem* code_item,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700438 uint32_t* handler_offsets, uint32_t handlers_size) {
Ian Rogers13735952014-10-08 12:43:28 -0700439 const uint8_t* handlers_base = DexFile::GetCatchHandlerData(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800440
441 for (uint32_t i = 0; i < handlers_size; i++) {
442 bool catch_all;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800443 size_t offset = ptr_ - handlers_base;
jeffhao10037c82012-01-23 15:06:23 -0800444 int32_t size = DecodeSignedLeb128(&ptr_);
445
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700446 if (UNLIKELY((size < -65536) || (size > 65536))) {
447 ErrorStringPrintf("Invalid exception handler size: %d", size);
jeffhao10037c82012-01-23 15:06:23 -0800448 return false;
449 }
450
451 if (size <= 0) {
452 catch_all = true;
453 size = -size;
454 } else {
455 catch_all = false;
456 }
457
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800458 handler_offsets[i] = static_cast<uint32_t>(offset);
jeffhao10037c82012-01-23 15:06:23 -0800459
460 while (size-- > 0) {
461 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
462 if (!CheckIndex(type_idx, header_->type_ids_size_, "handler type_idx")) {
463 return false;
464 }
465
466 uint32_t addr = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700467 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
468 ErrorStringPrintf("Invalid handler addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800469 return false;
470 }
471 }
472
473 if (catch_all) {
474 uint32_t addr = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700475 if (UNLIKELY(addr >= code_item->insns_size_in_code_units_)) {
476 ErrorStringPrintf("Invalid handler catch_all_addr: %x", addr);
jeffhao10037c82012-01-23 15:06:23 -0800477 return false;
478 }
479 }
480 }
481
482 return true;
483}
484
Andreas Gampee6215c02015-08-31 18:54:38 -0700485bool DexFileVerifier::CheckClassDataItemField(uint32_t idx,
486 uint32_t access_flags,
487 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700488 uint16_t class_type_index,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700489 bool expect_static) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700490 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800491 if (!CheckIndex(idx, header_->field_ids_size_, "class_data_item field_idx")) {
492 return false;
493 }
494
Andreas Gampee6215c02015-08-31 18:54:38 -0700495 // Check that it's the right class.
496 uint16_t my_class_index =
497 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + idx)->
498 class_idx_;
499 if (class_type_index != my_class_index) {
500 ErrorStringPrintf("Field's class index unexpected, %" PRIu16 "vs %" PRIu16,
501 my_class_index,
502 class_type_index);
503 return false;
504 }
505
506 // Check that it falls into the right class-data list.
jeffhao10037c82012-01-23 15:06:23 -0800507 bool is_static = (access_flags & kAccStatic) != 0;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700508 if (UNLIKELY(is_static != expect_static)) {
509 ErrorStringPrintf("Static/instance field not in expected list");
jeffhao10037c82012-01-23 15:06:23 -0800510 return false;
511 }
512
Andreas Gampee6215c02015-08-31 18:54:38 -0700513 // Check field access flags.
514 std::string error_msg;
Andreas Gampec9f0ba12016-02-09 09:21:04 -0800515 if (!CheckFieldAccessFlags(idx, access_flags, class_access_flags, &error_msg)) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700516 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800517 return false;
518 }
519
520 return true;
521}
522
Andreas Gampee6215c02015-08-31 18:54:38 -0700523bool DexFileVerifier::CheckClassDataItemMethod(uint32_t idx,
524 uint32_t access_flags,
525 uint32_t class_access_flags,
Andreas Gampe1a973572015-09-10 20:09:11 -0700526 uint16_t class_type_index,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700527 uint32_t code_offset,
Andreas Gampee6215c02015-08-31 18:54:38 -0700528 std::unordered_set<uint32_t>* direct_method_indexes,
Jeff Haoa574b0e2015-06-04 18:12:26 -0700529 bool expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700530 DCHECK(direct_method_indexes != nullptr);
531 // Check for overflow.
jeffhao10037c82012-01-23 15:06:23 -0800532 if (!CheckIndex(idx, header_->method_ids_size_, "class_data_item method_idx")) {
533 return false;
534 }
535
Andreas Gampee6215c02015-08-31 18:54:38 -0700536 // Check that it's the right class.
537 uint16_t my_class_index =
538 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + idx)->
539 class_idx_;
540 if (class_type_index != my_class_index) {
541 ErrorStringPrintf("Method's class index unexpected, %" PRIu16 "vs %" PRIu16,
542 my_class_index,
543 class_type_index);
jeffhao10037c82012-01-23 15:06:23 -0800544 return false;
545 }
546
Andreas Gampee6215c02015-08-31 18:54:38 -0700547 // Check that it's not defined as both direct and virtual.
Jeff Haoa574b0e2015-06-04 18:12:26 -0700548 if (expect_direct) {
Andreas Gampee6215c02015-08-31 18:54:38 -0700549 direct_method_indexes->insert(idx);
550 } else if (direct_method_indexes->find(idx) != direct_method_indexes->end()) {
Jeff Haoa574b0e2015-06-04 18:12:26 -0700551 ErrorStringPrintf("Found virtual method with same index as direct method: %d", idx);
552 return false;
553 }
554
Andreas Gampee6215c02015-08-31 18:54:38 -0700555 // Check method access flags.
556 bool has_code = (code_offset != 0);
557 std::string error_msg;
558 if (!CheckMethodAccessFlags(idx,
559 access_flags,
560 class_access_flags,
561 has_code,
562 expect_direct,
563 &error_msg)) {
564 ErrorStringPrintf("%s", error_msg.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800565 return false;
566 }
567
568 return true;
569}
570
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800571bool DexFileVerifier::CheckPadding(size_t offset, uint32_t aligned_offset) {
jeffhao10037c82012-01-23 15:06:23 -0800572 if (offset < aligned_offset) {
Ian Rogers13735952014-10-08 12:43:28 -0700573 if (!CheckListSize(begin_ + offset, aligned_offset - offset, sizeof(uint8_t), "section")) {
jeffhao10037c82012-01-23 15:06:23 -0800574 return false;
575 }
576 while (offset < aligned_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700577 if (UNLIKELY(*ptr_ != '\0')) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800578 ErrorStringPrintf("Non-zero padding %x before section start at %zx", *ptr_, offset);
jeffhao10037c82012-01-23 15:06:23 -0800579 return false;
580 }
581 ptr_++;
582 offset++;
583 }
584 }
585 return true;
586}
587
588bool DexFileVerifier::CheckEncodedValue() {
Ian Rogers13735952014-10-08 12:43:28 -0700589 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "encoded_value header")) {
jeffhao10037c82012-01-23 15:06:23 -0800590 return false;
591 }
592
593 uint8_t header_byte = *(ptr_++);
594 uint32_t value_type = header_byte & DexFile::kDexAnnotationValueTypeMask;
595 uint32_t value_arg = header_byte >> DexFile::kDexAnnotationValueArgShift;
596
597 switch (value_type) {
598 case DexFile::kDexAnnotationByte:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700599 if (UNLIKELY(value_arg != 0)) {
600 ErrorStringPrintf("Bad encoded_value byte size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800601 return false;
602 }
603 ptr_++;
604 break;
605 case DexFile::kDexAnnotationShort:
606 case DexFile::kDexAnnotationChar:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700607 if (UNLIKELY(value_arg > 1)) {
608 ErrorStringPrintf("Bad encoded_value char/short size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800609 return false;
610 }
611 ptr_ += value_arg + 1;
612 break;
613 case DexFile::kDexAnnotationInt:
614 case DexFile::kDexAnnotationFloat:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700615 if (UNLIKELY(value_arg > 3)) {
616 ErrorStringPrintf("Bad encoded_value int/float size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800617 return false;
618 }
619 ptr_ += value_arg + 1;
620 break;
621 case DexFile::kDexAnnotationLong:
622 case DexFile::kDexAnnotationDouble:
623 ptr_ += value_arg + 1;
624 break;
625 case DexFile::kDexAnnotationString: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700626 if (UNLIKELY(value_arg > 3)) {
627 ErrorStringPrintf("Bad encoded_value string 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_->string_ids_size_, "encoded_value string")) {
632 return false;
633 }
634 break;
635 }
636 case DexFile::kDexAnnotationType: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700637 if (UNLIKELY(value_arg > 3)) {
638 ErrorStringPrintf("Bad encoded_value type size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800639 return false;
640 }
641 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
642 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_value type")) {
643 return false;
644 }
645 break;
646 }
647 case DexFile::kDexAnnotationField:
648 case DexFile::kDexAnnotationEnum: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700649 if (UNLIKELY(value_arg > 3)) {
650 ErrorStringPrintf("Bad encoded_value field/enum size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800651 return false;
652 }
653 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
654 if (!CheckIndex(idx, header_->field_ids_size_, "encoded_value field")) {
655 return false;
656 }
657 break;
658 }
659 case DexFile::kDexAnnotationMethod: {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700660 if (UNLIKELY(value_arg > 3)) {
661 ErrorStringPrintf("Bad encoded_value method size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800662 return false;
663 }
664 uint32_t idx = ReadUnsignedLittleEndian(value_arg + 1);
665 if (!CheckIndex(idx, header_->method_ids_size_, "encoded_value method")) {
666 return false;
667 }
668 break;
669 }
670 case DexFile::kDexAnnotationArray:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700671 if (UNLIKELY(value_arg != 0)) {
672 ErrorStringPrintf("Bad encoded_value array value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800673 return false;
674 }
675 if (!CheckEncodedArray()) {
676 return false;
677 }
678 break;
679 case DexFile::kDexAnnotationAnnotation:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700680 if (UNLIKELY(value_arg != 0)) {
681 ErrorStringPrintf("Bad encoded_value annotation value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800682 return false;
683 }
684 if (!CheckEncodedAnnotation()) {
685 return false;
686 }
687 break;
688 case DexFile::kDexAnnotationNull:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700689 if (UNLIKELY(value_arg != 0)) {
690 ErrorStringPrintf("Bad encoded_value null value_arg %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800691 return false;
692 }
693 break;
694 case DexFile::kDexAnnotationBoolean:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700695 if (UNLIKELY(value_arg > 1)) {
696 ErrorStringPrintf("Bad encoded_value boolean size %x", value_arg);
jeffhao10037c82012-01-23 15:06:23 -0800697 return false;
698 }
699 break;
700 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700701 ErrorStringPrintf("Bogus encoded_value value_type %x", value_type);
jeffhao10037c82012-01-23 15:06:23 -0800702 return false;
703 }
704
705 return true;
706}
707
708bool DexFileVerifier::CheckEncodedArray() {
709 uint32_t size = DecodeUnsignedLeb128(&ptr_);
710
711 while (size--) {
712 if (!CheckEncodedValue()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700713 failure_reason_ = StringPrintf("Bad encoded_array value: %s", failure_reason_.c_str());
jeffhao10037c82012-01-23 15:06:23 -0800714 return false;
715 }
716 }
717 return true;
718}
719
720bool DexFileVerifier::CheckEncodedAnnotation() {
721 uint32_t idx = DecodeUnsignedLeb128(&ptr_);
722 if (!CheckIndex(idx, header_->type_ids_size_, "encoded_annotation type_idx")) {
723 return false;
724 }
725
726 uint32_t size = DecodeUnsignedLeb128(&ptr_);
727 uint32_t last_idx = 0;
728
729 for (uint32_t i = 0; i < size; i++) {
730 idx = DecodeUnsignedLeb128(&ptr_);
731 if (!CheckIndex(idx, header_->string_ids_size_, "annotation_element name_idx")) {
732 return false;
733 }
734
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700735 if (UNLIKELY(last_idx >= idx && i != 0)) {
736 ErrorStringPrintf("Out-of-order annotation_element name_idx: %x then %x",
737 last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -0800738 return false;
739 }
740
741 if (!CheckEncodedValue()) {
742 return false;
743 }
744
745 last_idx = idx;
746 }
747 return true;
748}
749
Andreas Gampee6215c02015-08-31 18:54:38 -0700750bool DexFileVerifier::FindClassFlags(uint32_t index,
751 bool is_field,
752 uint16_t* class_type_index,
753 uint32_t* class_access_flags) {
754 DCHECK(class_type_index != nullptr);
755 DCHECK(class_access_flags != nullptr);
756
757 // First check if the index is valid.
758 if (index >= (is_field ? header_->field_ids_size_ : header_->method_ids_size_)) {
759 return false;
760 }
761
762 // Next get the type index.
763 if (is_field) {
764 *class_type_index =
765 (reinterpret_cast<const DexFile::FieldId*>(begin_ + header_->field_ids_off_) + index)->
766 class_idx_;
767 } else {
768 *class_type_index =
769 (reinterpret_cast<const DexFile::MethodId*>(begin_ + header_->method_ids_off_) + index)->
770 class_idx_;
771 }
772
773 // Check if that is valid.
774 if (*class_type_index >= header_->type_ids_size_) {
775 return false;
776 }
777
778 // Now search for the class def. This is basically a specialized version of the DexFile code, as
779 // we should not trust that this is a valid DexFile just yet.
780 const DexFile::ClassDef* class_def_begin =
781 reinterpret_cast<const DexFile::ClassDef*>(begin_ + header_->class_defs_off_);
782 for (size_t i = 0; i < header_->class_defs_size_; ++i) {
783 const DexFile::ClassDef* class_def = class_def_begin + i;
784 if (class_def->class_idx_ == *class_type_index) {
785 *class_access_flags = class_def->access_flags_;
786 return true;
787 }
788 }
789
790 // Didn't find the class-def, not defined here...
791 return false;
792}
793
794bool DexFileVerifier::CheckOrderAndGetClassFlags(bool is_field,
795 const char* type_descr,
796 uint32_t curr_index,
797 uint32_t prev_index,
798 bool* have_class,
799 uint16_t* class_type_index,
800 uint32_t* class_access_flags) {
801 if (curr_index < prev_index) {
802 ErrorStringPrintf("out-of-order %s indexes %" PRIu32 " and %" PRIu32,
803 type_descr,
804 prev_index,
805 curr_index);
806 return false;
807 }
808
809 if (!*have_class) {
810 *have_class = FindClassFlags(curr_index, is_field, class_type_index, class_access_flags);
811 if (!*have_class) {
812 // Should have really found one.
813 ErrorStringPrintf("could not find declaring class for %s index %" PRIu32,
814 type_descr,
815 curr_index);
816 return false;
817 }
818 }
819 return true;
820}
821
822template <bool kStatic>
823bool DexFileVerifier::CheckIntraClassDataItemFields(ClassDataItemIterator* it,
824 bool* have_class,
825 uint16_t* class_type_index,
826 uint32_t* class_access_flags) {
827 DCHECK(it != nullptr);
828 // These calls use the raw access flags to check whether the whole dex field is valid.
829 uint32_t prev_index = 0;
830 for (; kStatic ? it->HasNextStaticField() : it->HasNextInstanceField(); it->Next()) {
831 uint32_t curr_index = it->GetMemberIndex();
832 if (!CheckOrderAndGetClassFlags(true,
833 kStatic ? "static field" : "instance field",
834 curr_index,
835 prev_index,
836 have_class,
837 class_type_index,
838 class_access_flags)) {
839 return false;
840 }
841 prev_index = curr_index;
842
843 if (!CheckClassDataItemField(curr_index,
844 it->GetRawMemberAccessFlags(),
845 *class_access_flags,
846 *class_type_index,
847 kStatic)) {
848 return false;
849 }
850 }
851
852 return true;
853}
854
855template <bool kDirect>
856bool DexFileVerifier::CheckIntraClassDataItemMethods(
857 ClassDataItemIterator* it,
858 std::unordered_set<uint32_t>* direct_method_indexes,
859 bool* have_class,
860 uint16_t* class_type_index,
861 uint32_t* class_access_flags) {
862 uint32_t prev_index = 0;
863 for (; kDirect ? it->HasNextDirectMethod() : it->HasNextVirtualMethod(); it->Next()) {
864 uint32_t curr_index = it->GetMemberIndex();
865 if (!CheckOrderAndGetClassFlags(false,
866 kDirect ? "direct method" : "virtual method",
867 curr_index,
868 prev_index,
869 have_class,
870 class_type_index,
871 class_access_flags)) {
872 return false;
873 }
874 prev_index = curr_index;
875
876 if (!CheckClassDataItemMethod(curr_index,
877 it->GetRawMemberAccessFlags(),
878 *class_access_flags,
879 *class_type_index,
880 it->GetMethodCodeItemOffset(),
881 direct_method_indexes,
882 kDirect)) {
883 return false;
884 }
885 }
886
887 return true;
888}
889
jeffhao10037c82012-01-23 15:06:23 -0800890bool DexFileVerifier::CheckIntraClassDataItem() {
891 ClassDataItemIterator it(*dex_file_, ptr_);
Jeff Haoa574b0e2015-06-04 18:12:26 -0700892 std::unordered_set<uint32_t> direct_method_indexes;
jeffhao10037c82012-01-23 15:06:23 -0800893
Andreas Gampee6215c02015-08-31 18:54:38 -0700894 // This code is complicated by the fact that we don't directly know which class this belongs to.
895 // So we need to explicitly search with the first item we find (either field or method), and then,
896 // as the lookup is expensive, cache the result.
897 bool have_class = false;
898 uint16_t class_type_index;
899 uint32_t class_access_flags;
900
901 // Check fields.
902 if (!CheckIntraClassDataItemFields<true>(&it,
903 &have_class,
904 &class_type_index,
905 &class_access_flags)) {
906 return false;
jeffhao10037c82012-01-23 15:06:23 -0800907 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700908 if (!CheckIntraClassDataItemFields<false>(&it,
909 &have_class,
910 &class_type_index,
911 &class_access_flags)) {
912 return false;
jeffhao10037c82012-01-23 15:06:23 -0800913 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700914
915 // Check methods.
916 if (!CheckIntraClassDataItemMethods<true>(&it,
917 &direct_method_indexes,
918 &have_class,
919 &class_type_index,
920 &class_access_flags)) {
921 return false;
jeffhao10037c82012-01-23 15:06:23 -0800922 }
Andreas Gampee6215c02015-08-31 18:54:38 -0700923 if (!CheckIntraClassDataItemMethods<false>(&it,
924 &direct_method_indexes,
925 &have_class,
926 &class_type_index,
927 &class_access_flags)) {
928 return false;
jeffhao10037c82012-01-23 15:06:23 -0800929 }
930
931 ptr_ = it.EndDataPointer();
932 return true;
933}
934
935bool DexFileVerifier::CheckIntraCodeItem() {
936 const DexFile::CodeItem* code_item = reinterpret_cast<const DexFile::CodeItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -0700937 if (!CheckListSize(code_item, 1, sizeof(DexFile::CodeItem), "code")) {
jeffhao10037c82012-01-23 15:06:23 -0800938 return false;
939 }
940
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700941 if (UNLIKELY(code_item->ins_size_ > code_item->registers_size_)) {
942 ErrorStringPrintf("ins_size (%ud) > registers_size (%ud)",
943 code_item->ins_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800944 return false;
945 }
946
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700947 if (UNLIKELY((code_item->outs_size_ > 5) &&
948 (code_item->outs_size_ > code_item->registers_size_))) {
jeffhao10037c82012-01-23 15:06:23 -0800949 /*
950 * outs_size can be up to 5, even if registers_size is smaller, since the
951 * short forms of method invocation allow repetitions of a register multiple
952 * times within a single parameter list. However, longer parameter lists
953 * need to be represented in-order in the register file.
954 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700955 ErrorStringPrintf("outs_size (%ud) > registers_size (%ud)",
956 code_item->outs_size_, code_item->registers_size_);
jeffhao10037c82012-01-23 15:06:23 -0800957 return false;
958 }
959
960 const uint16_t* insns = code_item->insns_;
961 uint32_t insns_size = code_item->insns_size_in_code_units_;
962 if (!CheckListSize(insns, insns_size, sizeof(uint16_t), "insns size")) {
963 return false;
964 }
965
966 // Grab the end of the insns if there are no try_items.
967 uint32_t try_items_size = code_item->tries_size_;
968 if (try_items_size == 0) {
Ian Rogers13735952014-10-08 12:43:28 -0700969 ptr_ = reinterpret_cast<const uint8_t*>(&insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -0800970 return true;
971 }
972
973 // try_items are 4-byte aligned. Verify the spacer is 0.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -0800974 if (((reinterpret_cast<uintptr_t>(&insns[insns_size]) & 3) != 0) && (insns[insns_size] != 0)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700975 ErrorStringPrintf("Non-zero padding: %x", insns[insns_size]);
jeffhao10037c82012-01-23 15:06:23 -0800976 return false;
977 }
978
979 const DexFile::TryItem* try_items = DexFile::GetTryItems(*code_item, 0);
jeffhao10037c82012-01-23 15:06:23 -0800980 if (!CheckListSize(try_items, try_items_size, sizeof(DexFile::TryItem), "try_items size")) {
981 return false;
982 }
983
Anestis Bechtsoudis6a8df532015-07-12 12:51:35 -0500984 ptr_ = DexFile::GetCatchHandlerData(*code_item, 0);
985 uint32_t handlers_size = DecodeUnsignedLeb128(&ptr_);
986
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700987 if (UNLIKELY((handlers_size == 0) || (handlers_size >= 65536))) {
988 ErrorStringPrintf("Invalid handlers_size: %ud", handlers_size);
jeffhao10037c82012-01-23 15:06:23 -0800989 return false;
990 }
991
Ian Rogers700a4022014-05-19 16:49:03 -0700992 std::unique_ptr<uint32_t[]> handler_offsets(new uint32_t[handlers_size]);
Elliott Hughesee0fa762012-03-26 17:12:41 -0700993 if (!CheckAndGetHandlerOffsets(code_item, &handler_offsets[0], handlers_size)) {
jeffhao10037c82012-01-23 15:06:23 -0800994 return false;
995 }
996
997 uint32_t last_addr = 0;
998 while (try_items_size--) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700999 if (UNLIKELY(try_items->start_addr_ < last_addr)) {
1000 ErrorStringPrintf("Out-of_order try_item with start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001001 return false;
1002 }
1003
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001004 if (UNLIKELY(try_items->start_addr_ >= insns_size)) {
1005 ErrorStringPrintf("Invalid try_item start_addr: %x", try_items->start_addr_);
jeffhao10037c82012-01-23 15:06:23 -08001006 return false;
1007 }
1008
1009 uint32_t i;
1010 for (i = 0; i < handlers_size; i++) {
1011 if (try_items->handler_off_ == handler_offsets[i]) {
1012 break;
1013 }
1014 }
1015
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001016 if (UNLIKELY(i == handlers_size)) {
1017 ErrorStringPrintf("Bogus handler offset: %x", try_items->handler_off_);
jeffhao10037c82012-01-23 15:06:23 -08001018 return false;
1019 }
1020
1021 last_addr = try_items->start_addr_ + try_items->insn_count_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001022 if (UNLIKELY(last_addr > insns_size)) {
1023 ErrorStringPrintf("Invalid try_item insn_count: %x", try_items->insn_count_);
jeffhao10037c82012-01-23 15:06:23 -08001024 return false;
1025 }
1026
1027 try_items++;
1028 }
1029
1030 return true;
1031}
1032
1033bool DexFileVerifier::CheckIntraStringDataItem() {
1034 uint32_t size = DecodeUnsignedLeb128(&ptr_);
Ian Rogers13735952014-10-08 12:43:28 -07001035 const uint8_t* file_end = begin_ + size_;
jeffhao10037c82012-01-23 15:06:23 -08001036
1037 for (uint32_t i = 0; i < size; i++) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001038 CHECK_LT(i, size); // b/15014252 Prevents hitting the impossible case below
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001039 if (UNLIKELY(ptr_ >= file_end)) {
1040 ErrorStringPrintf("String data would go beyond end-of-file");
jeffhao10037c82012-01-23 15:06:23 -08001041 return false;
1042 }
1043
1044 uint8_t byte = *(ptr_++);
1045
1046 // Switch on the high 4 bits.
1047 switch (byte >> 4) {
1048 case 0x00:
1049 // Special case of bit pattern 0xxx.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001050 if (UNLIKELY(byte == 0)) {
Brian Carlstromc6475642014-05-27 11:14:12 -07001051 CHECK_LT(i, size); // b/15014252 Actually hit this impossible case with clang
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001052 ErrorStringPrintf("String data shorter than indicated utf16_size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001053 return false;
1054 }
1055 break;
1056 case 0x01:
1057 case 0x02:
1058 case 0x03:
1059 case 0x04:
1060 case 0x05:
1061 case 0x06:
1062 case 0x07:
1063 // No extra checks necessary for bit pattern 0xxx.
1064 break;
1065 case 0x08:
1066 case 0x09:
1067 case 0x0a:
1068 case 0x0b:
1069 case 0x0f:
1070 // Illegal bit patterns 10xx or 1111.
1071 // Note: 1111 is valid for normal UTF-8, but not here.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001072 ErrorStringPrintf("Illegal start byte %x in string data", byte);
jeffhao10037c82012-01-23 15:06:23 -08001073 return false;
1074 case 0x0c:
1075 case 0x0d: {
1076 // Bit pattern 110x has an additional byte.
1077 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001078 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1079 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001080 return false;
1081 }
1082 uint16_t value = ((byte & 0x1f) << 6) | (byte2 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001083 if (UNLIKELY((value != 0) && (value < 0x80))) {
1084 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001085 return false;
1086 }
1087 break;
1088 }
1089 case 0x0e: {
1090 // Bit pattern 1110 has 2 additional bytes.
1091 uint8_t byte2 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001092 if (UNLIKELY((byte2 & 0xc0) != 0x80)) {
1093 ErrorStringPrintf("Illegal continuation byte %x in string data", byte2);
jeffhao10037c82012-01-23 15:06:23 -08001094 return false;
1095 }
1096 uint8_t byte3 = *(ptr_++);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001097 if (UNLIKELY((byte3 & 0xc0) != 0x80)) {
1098 ErrorStringPrintf("Illegal continuation byte %x in string data", byte3);
jeffhao10037c82012-01-23 15:06:23 -08001099 return false;
1100 }
1101 uint16_t value = ((byte & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001102 if (UNLIKELY(value < 0x800)) {
1103 ErrorStringPrintf("Illegal representation for value %x in string data", value);
jeffhao10037c82012-01-23 15:06:23 -08001104 return false;
1105 }
1106 break;
1107 }
1108 }
1109 }
1110
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001111 if (UNLIKELY(*(ptr_++) != '\0')) {
1112 ErrorStringPrintf("String longer than indicated size %x", size);
jeffhao10037c82012-01-23 15:06:23 -08001113 return false;
1114 }
1115
1116 return true;
1117}
1118
1119bool DexFileVerifier::CheckIntraDebugInfoItem() {
1120 DecodeUnsignedLeb128(&ptr_);
1121 uint32_t parameters_size = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001122 if (UNLIKELY(parameters_size > 65536)) {
1123 ErrorStringPrintf("Invalid parameters_size: %x", parameters_size);
jeffhao10037c82012-01-23 15:06:23 -08001124 return false;
1125 }
1126
1127 for (uint32_t j = 0; j < parameters_size; j++) {
1128 uint32_t parameter_name = DecodeUnsignedLeb128(&ptr_);
1129 if (parameter_name != 0) {
1130 parameter_name--;
1131 if (!CheckIndex(parameter_name, header_->string_ids_size_, "debug_info_item parameter_name")) {
1132 return false;
1133 }
1134 }
1135 }
1136
1137 while (true) {
1138 uint8_t opcode = *(ptr_++);
1139 switch (opcode) {
1140 case DexFile::DBG_END_SEQUENCE: {
1141 return true;
1142 }
1143 case DexFile::DBG_ADVANCE_PC: {
1144 DecodeUnsignedLeb128(&ptr_);
1145 break;
1146 }
1147 case DexFile::DBG_ADVANCE_LINE: {
1148 DecodeSignedLeb128(&ptr_);
1149 break;
1150 }
1151 case DexFile::DBG_START_LOCAL: {
1152 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001153 if (UNLIKELY(reg_num >= 65536)) {
1154 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001155 return false;
1156 }
1157 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1158 if (name_idx != 0) {
1159 name_idx--;
1160 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL name_idx")) {
1161 return false;
1162 }
1163 }
1164 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
1165 if (type_idx != 0) {
1166 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001167 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001168 return false;
1169 }
1170 }
1171 break;
1172 }
1173 case DexFile::DBG_END_LOCAL:
1174 case DexFile::DBG_RESTART_LOCAL: {
1175 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001176 if (UNLIKELY(reg_num >= 65536)) {
1177 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001178 return false;
1179 }
1180 break;
1181 }
1182 case DexFile::DBG_START_LOCAL_EXTENDED: {
1183 uint32_t reg_num = DecodeUnsignedLeb128(&ptr_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001184 if (UNLIKELY(reg_num >= 65536)) {
1185 ErrorStringPrintf("Bad reg_num for opcode %x", opcode);
jeffhao10037c82012-01-23 15:06:23 -08001186 return false;
1187 }
1188 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1189 if (name_idx != 0) {
1190 name_idx--;
1191 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED name_idx")) {
1192 return false;
1193 }
1194 }
1195 uint32_t type_idx = DecodeUnsignedLeb128(&ptr_);
1196 if (type_idx != 0) {
1197 type_idx--;
Logan Chiendd3208d2015-04-19 23:27:52 +08001198 if (!CheckIndex(type_idx, header_->type_ids_size_, "DBG_START_LOCAL_EXTENDED type_idx")) {
jeffhao10037c82012-01-23 15:06:23 -08001199 return false;
1200 }
1201 }
1202 uint32_t sig_idx = DecodeUnsignedLeb128(&ptr_);
1203 if (sig_idx != 0) {
1204 sig_idx--;
1205 if (!CheckIndex(sig_idx, header_->string_ids_size_, "DBG_START_LOCAL_EXTENDED sig_idx")) {
1206 return false;
1207 }
1208 }
1209 break;
1210 }
1211 case DexFile::DBG_SET_FILE: {
1212 uint32_t name_idx = DecodeUnsignedLeb128(&ptr_);
1213 if (name_idx != 0) {
1214 name_idx--;
1215 if (!CheckIndex(name_idx, header_->string_ids_size_, "DBG_SET_FILE name_idx")) {
1216 return false;
1217 }
1218 }
1219 break;
1220 }
1221 }
1222 }
1223}
1224
1225bool DexFileVerifier::CheckIntraAnnotationItem() {
Ian Rogers13735952014-10-08 12:43:28 -07001226 if (!CheckListSize(ptr_, 1, sizeof(uint8_t), "annotation visibility")) {
jeffhao10037c82012-01-23 15:06:23 -08001227 return false;
1228 }
1229
1230 // Check visibility
1231 switch (*(ptr_++)) {
1232 case DexFile::kDexVisibilityBuild:
1233 case DexFile::kDexVisibilityRuntime:
1234 case DexFile::kDexVisibilitySystem:
1235 break;
1236 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001237 ErrorStringPrintf("Bad annotation visibility: %x", *ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001238 return false;
1239 }
1240
1241 if (!CheckEncodedAnnotation()) {
1242 return false;
1243 }
1244
1245 return true;
1246}
1247
1248bool DexFileVerifier::CheckIntraAnnotationsDirectoryItem() {
1249 const DexFile::AnnotationsDirectoryItem* item =
1250 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001251 if (!CheckListSize(item, 1, sizeof(DexFile::AnnotationsDirectoryItem), "annotations_directory")) {
jeffhao10037c82012-01-23 15:06:23 -08001252 return false;
1253 }
1254
1255 // Field annotations follow immediately after the annotations directory.
1256 const DexFile::FieldAnnotationsItem* field_item =
1257 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
1258 uint32_t field_count = item->fields_size_;
1259 if (!CheckListSize(field_item, field_count, sizeof(DexFile::FieldAnnotationsItem), "field_annotations list")) {
1260 return false;
1261 }
1262
1263 uint32_t last_idx = 0;
1264 for (uint32_t i = 0; i < field_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001265 if (UNLIKELY(last_idx >= field_item->field_idx_ && i != 0)) {
1266 ErrorStringPrintf("Out-of-order field_idx for annotation: %x then %x", last_idx, field_item->field_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001267 return false;
1268 }
1269 last_idx = field_item->field_idx_;
1270 field_item++;
1271 }
1272
1273 // Method annotations follow immediately after field annotations.
1274 const DexFile::MethodAnnotationsItem* method_item =
1275 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
1276 uint32_t method_count = item->methods_size_;
1277 if (!CheckListSize(method_item, method_count, sizeof(DexFile::MethodAnnotationsItem), "method_annotations list")) {
1278 return false;
1279 }
1280
1281 last_idx = 0;
1282 for (uint32_t i = 0; i < method_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001283 if (UNLIKELY(last_idx >= method_item->method_idx_ && i != 0)) {
1284 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1285 last_idx, method_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001286 return false;
1287 }
1288 last_idx = method_item->method_idx_;
1289 method_item++;
1290 }
1291
1292 // Parameter annotations follow immediately after method annotations.
1293 const DexFile::ParameterAnnotationsItem* parameter_item =
1294 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
1295 uint32_t parameter_count = item->parameters_size_;
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07001296 if (!CheckListSize(parameter_item, parameter_count, sizeof(DexFile::ParameterAnnotationsItem),
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001297 "parameter_annotations list")) {
jeffhao10037c82012-01-23 15:06:23 -08001298 return false;
1299 }
1300
1301 last_idx = 0;
1302 for (uint32_t i = 0; i < parameter_count; i++) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001303 if (UNLIKELY(last_idx >= parameter_item->method_idx_ && i != 0)) {
1304 ErrorStringPrintf("Out-of-order method_idx for annotation: %x then %x",
1305 last_idx, parameter_item->method_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001306 return false;
1307 }
1308 last_idx = parameter_item->method_idx_;
1309 parameter_item++;
1310 }
1311
1312 // Return a pointer to the end of the annotations.
Ian Rogers13735952014-10-08 12:43:28 -07001313 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08001314 return true;
1315}
1316
Andreas Gampeb061cc12014-09-02 10:22:20 -07001317bool DexFileVerifier::CheckIntraSectionIterate(size_t offset, uint32_t section_count,
1318 uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001319 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001320 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001321 switch (type) {
1322 case DexFile::kDexTypeClassDataItem:
1323 case DexFile::kDexTypeStringDataItem:
1324 case DexFile::kDexTypeDebugInfoItem:
1325 case DexFile::kDexTypeAnnotationItem:
1326 case DexFile::kDexTypeEncodedArrayItem:
1327 alignment_mask = sizeof(uint8_t) - 1;
1328 break;
1329 default:
1330 alignment_mask = sizeof(uint32_t) - 1;
1331 break;
1332 }
1333
1334 // Iterate through the items in the section.
Andreas Gampeb061cc12014-09-02 10:22:20 -07001335 for (uint32_t i = 0; i < section_count; i++) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001336 size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08001337
1338 // Check the padding between items.
1339 if (!CheckPadding(offset, aligned_offset)) {
1340 return false;
1341 }
1342
1343 // Check depending on the section type.
1344 switch (type) {
1345 case DexFile::kDexTypeStringIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001346 if (!CheckListSize(ptr_, 1, sizeof(DexFile::StringId), "string_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001347 return false;
1348 }
1349 ptr_ += sizeof(DexFile::StringId);
1350 break;
1351 }
1352 case DexFile::kDexTypeTypeIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001353 if (!CheckListSize(ptr_, 1, sizeof(DexFile::TypeId), "type_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001354 return false;
1355 }
1356 ptr_ += sizeof(DexFile::TypeId);
1357 break;
1358 }
1359 case DexFile::kDexTypeProtoIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001360 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001361 return false;
1362 }
1363 ptr_ += sizeof(DexFile::ProtoId);
1364 break;
1365 }
1366 case DexFile::kDexTypeFieldIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001367 if (!CheckListSize(ptr_, 1, sizeof(DexFile::FieldId), "field_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001368 return false;
1369 }
1370 ptr_ += sizeof(DexFile::FieldId);
1371 break;
1372 }
1373 case DexFile::kDexTypeMethodIdItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001374 if (!CheckListSize(ptr_, 1, sizeof(DexFile::MethodId), "method_ids")) {
jeffhao10037c82012-01-23 15:06:23 -08001375 return false;
1376 }
1377 ptr_ += sizeof(DexFile::MethodId);
1378 break;
1379 }
1380 case DexFile::kDexTypeClassDefItem: {
Andreas Gampe50d1bc12014-07-17 21:49:24 -07001381 if (!CheckListSize(ptr_, 1, sizeof(DexFile::ClassDef), "class_defs")) {
jeffhao10037c82012-01-23 15:06:23 -08001382 return false;
1383 }
1384 ptr_ += sizeof(DexFile::ClassDef);
1385 break;
1386 }
1387 case DexFile::kDexTypeTypeList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001388 if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001389 return false;
1390 }
jeffhao10037c82012-01-23 15:06:23 -08001391 break;
1392 }
1393 case DexFile::kDexTypeAnnotationSetRefList: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001394 if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001395 return false;
1396 }
jeffhao10037c82012-01-23 15:06:23 -08001397 break;
1398 }
1399 case DexFile::kDexTypeAnnotationSetItem: {
Andreas Gamped4ae41f2014-09-02 11:17:34 -07001400 if (!CheckList(sizeof(uint32_t), "annotation_set_item", &ptr_)) {
jeffhao10037c82012-01-23 15:06:23 -08001401 return false;
1402 }
jeffhao10037c82012-01-23 15:06:23 -08001403 break;
1404 }
1405 case DexFile::kDexTypeClassDataItem: {
1406 if (!CheckIntraClassDataItem()) {
1407 return false;
1408 }
1409 break;
1410 }
1411 case DexFile::kDexTypeCodeItem: {
1412 if (!CheckIntraCodeItem()) {
1413 return false;
1414 }
1415 break;
1416 }
1417 case DexFile::kDexTypeStringDataItem: {
1418 if (!CheckIntraStringDataItem()) {
1419 return false;
1420 }
1421 break;
1422 }
1423 case DexFile::kDexTypeDebugInfoItem: {
1424 if (!CheckIntraDebugInfoItem()) {
1425 return false;
1426 }
1427 break;
1428 }
1429 case DexFile::kDexTypeAnnotationItem: {
1430 if (!CheckIntraAnnotationItem()) {
1431 return false;
1432 }
1433 break;
1434 }
1435 case DexFile::kDexTypeEncodedArrayItem: {
1436 if (!CheckEncodedArray()) {
1437 return false;
1438 }
1439 break;
1440 }
1441 case DexFile::kDexTypeAnnotationsDirectoryItem: {
1442 if (!CheckIntraAnnotationsDirectoryItem()) {
1443 return false;
1444 }
1445 break;
1446 }
1447 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001448 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001449 return false;
1450 }
1451
1452 if (IsDataSectionType(type)) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001453 if (aligned_offset == 0u) {
1454 ErrorStringPrintf("Item %d offset is 0", i);
1455 return false;
1456 }
1457 DCHECK(offset_to_type_map_.Find(aligned_offset) == offset_to_type_map_.end());
1458 offset_to_type_map_.Insert(std::pair<uint32_t, uint16_t>(aligned_offset, type));
jeffhao10037c82012-01-23 15:06:23 -08001459 }
1460
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001461 aligned_offset = ptr_ - begin_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001462 if (UNLIKELY(aligned_offset > size_)) {
1463 ErrorStringPrintf("Item %d at ends out of bounds", i);
jeffhao10037c82012-01-23 15:06:23 -08001464 return false;
1465 }
1466
1467 offset = aligned_offset;
1468 }
1469
1470 return true;
1471}
1472
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001473bool DexFileVerifier::CheckIntraIdSection(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08001474 uint32_t expected_offset;
1475 uint32_t expected_size;
1476
1477 // Get the expected offset and size from the header.
1478 switch (type) {
1479 case DexFile::kDexTypeStringIdItem:
1480 expected_offset = header_->string_ids_off_;
1481 expected_size = header_->string_ids_size_;
1482 break;
1483 case DexFile::kDexTypeTypeIdItem:
1484 expected_offset = header_->type_ids_off_;
1485 expected_size = header_->type_ids_size_;
1486 break;
1487 case DexFile::kDexTypeProtoIdItem:
1488 expected_offset = header_->proto_ids_off_;
1489 expected_size = header_->proto_ids_size_;
1490 break;
1491 case DexFile::kDexTypeFieldIdItem:
1492 expected_offset = header_->field_ids_off_;
1493 expected_size = header_->field_ids_size_;
1494 break;
1495 case DexFile::kDexTypeMethodIdItem:
1496 expected_offset = header_->method_ids_off_;
1497 expected_size = header_->method_ids_size_;
1498 break;
1499 case DexFile::kDexTypeClassDefItem:
1500 expected_offset = header_->class_defs_off_;
1501 expected_size = header_->class_defs_size_;
1502 break;
1503 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001504 ErrorStringPrintf("Bad type for id section: %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001505 return false;
1506 }
1507
1508 // Check that the offset and size are what were expected from the header.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001509 if (UNLIKELY(offset != expected_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001510 ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
jeffhao10037c82012-01-23 15:06:23 -08001511 return false;
1512 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001513 if (UNLIKELY(count != expected_size)) {
1514 ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
jeffhao10037c82012-01-23 15:06:23 -08001515 return false;
1516 }
1517
1518 return CheckIntraSectionIterate(offset, count, type);
1519}
1520
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001521bool DexFileVerifier::CheckIntraDataSection(size_t offset, uint32_t count, uint16_t type) {
1522 size_t data_start = header_->data_off_;
1523 size_t data_end = data_start + header_->data_size_;
jeffhao10037c82012-01-23 15:06:23 -08001524
1525 // Sanity check the offset of the section.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001526 if (UNLIKELY((offset < data_start) || (offset > data_end))) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001527 ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
jeffhao10037c82012-01-23 15:06:23 -08001528 return false;
1529 }
1530
1531 if (!CheckIntraSectionIterate(offset, count, type)) {
1532 return false;
1533 }
1534
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001535 size_t next_offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001536 if (next_offset > data_end) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001537 ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
jeffhao10037c82012-01-23 15:06:23 -08001538 return false;
1539 }
1540
1541 return true;
1542}
1543
1544bool DexFileVerifier::CheckIntraSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08001545 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001546 const DexFile::MapItem* item = map->list_;
1547
1548 uint32_t count = map->size_;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001549 size_t offset = 0;
Ian Rogers30fab402012-01-23 15:43:46 -08001550 ptr_ = begin_;
jeffhao10037c82012-01-23 15:06:23 -08001551
1552 // Check the items listed in the map.
1553 while (count--) {
1554 uint32_t section_offset = item->offset_;
1555 uint32_t section_count = item->size_;
1556 uint16_t type = item->type_;
1557
1558 // Check for padding and overlap between items.
1559 if (!CheckPadding(offset, section_offset)) {
1560 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001561 } else if (UNLIKELY(offset > section_offset)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001562 ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001563 return false;
1564 }
1565
1566 // Check each item based on its type.
1567 switch (type) {
1568 case DexFile::kDexTypeHeaderItem:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001569 if (UNLIKELY(section_count != 1)) {
1570 ErrorStringPrintf("Multiple header items");
jeffhao10037c82012-01-23 15:06:23 -08001571 return false;
1572 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001573 if (UNLIKELY(section_offset != 0)) {
1574 ErrorStringPrintf("Header at %x, not at start of file", section_offset);
jeffhao10037c82012-01-23 15:06:23 -08001575 return false;
1576 }
Ian Rogers30fab402012-01-23 15:43:46 -08001577 ptr_ = begin_ + header_->header_size_;
jeffhao10037c82012-01-23 15:06:23 -08001578 offset = header_->header_size_;
1579 break;
1580 case DexFile::kDexTypeStringIdItem:
1581 case DexFile::kDexTypeTypeIdItem:
1582 case DexFile::kDexTypeProtoIdItem:
1583 case DexFile::kDexTypeFieldIdItem:
1584 case DexFile::kDexTypeMethodIdItem:
1585 case DexFile::kDexTypeClassDefItem:
1586 if (!CheckIntraIdSection(section_offset, section_count, type)) {
1587 return false;
1588 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001589 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001590 break;
1591 case DexFile::kDexTypeMapList:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001592 if (UNLIKELY(section_count != 1)) {
1593 ErrorStringPrintf("Multiple map list items");
jeffhao10037c82012-01-23 15:06:23 -08001594 return false;
1595 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001596 if (UNLIKELY(section_offset != header_->map_off_)) {
1597 ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
1598 section_offset, header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08001599 return false;
1600 }
1601 ptr_ += sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1602 offset = section_offset + sizeof(uint32_t) + (map->size_ * sizeof(DexFile::MapItem));
1603 break;
1604 case DexFile::kDexTypeTypeList:
1605 case DexFile::kDexTypeAnnotationSetRefList:
1606 case DexFile::kDexTypeAnnotationSetItem:
1607 case DexFile::kDexTypeClassDataItem:
1608 case DexFile::kDexTypeCodeItem:
1609 case DexFile::kDexTypeStringDataItem:
1610 case DexFile::kDexTypeDebugInfoItem:
1611 case DexFile::kDexTypeAnnotationItem:
1612 case DexFile::kDexTypeEncodedArrayItem:
1613 case DexFile::kDexTypeAnnotationsDirectoryItem:
1614 if (!CheckIntraDataSection(section_offset, section_count, type)) {
1615 return false;
1616 }
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001617 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08001618 break;
1619 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001620 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08001621 return false;
1622 }
1623
1624 item++;
1625 }
1626
1627 return true;
1628}
1629
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001630bool DexFileVerifier::CheckOffsetToTypeMap(size_t offset, uint16_t type) {
Mathieu Chartier0f8e0722015-10-26 14:52:42 -07001631 DCHECK_NE(offset, 0u);
1632 auto it = offset_to_type_map_.Find(offset);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001633 if (UNLIKELY(it == offset_to_type_map_.end())) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001634 ErrorStringPrintf("No data map entry found @ %zx; expected %x", offset, type);
jeffhao10037c82012-01-23 15:06:23 -08001635 return false;
1636 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001637 if (UNLIKELY(it->second != type)) {
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08001638 ErrorStringPrintf("Unexpected data map entry @ %zx; expected %x, found %x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001639 offset, type, it->second);
jeffhao10037c82012-01-23 15:06:23 -08001640 return false;
1641 }
1642 return true;
1643}
1644
Ian Rogers13735952014-10-08 12:43:28 -07001645uint16_t DexFileVerifier::FindFirstClassDataDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001646 ClassDataItemIterator it(*dex_file_, ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001647 *success = true;
jeffhao10037c82012-01-23 15:06:23 -08001648
1649 if (it.HasNextStaticField() || it.HasNextInstanceField()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001650 LOAD_FIELD(field, it.GetMemberIndex(), "first_class_data_definer field_id",
1651 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001652 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001653 }
1654
1655 if (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001656 LOAD_METHOD(method, it.GetMemberIndex(), "first_class_data_definer method_id",
1657 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001658 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001659 }
1660
1661 return DexFile::kDexNoIndex16;
1662}
1663
Ian Rogers13735952014-10-08 12:43:28 -07001664uint16_t DexFileVerifier::FindFirstAnnotationsDirectoryDefiner(const uint8_t* ptr, bool* success) {
jeffhao10037c82012-01-23 15:06:23 -08001665 const DexFile::AnnotationsDirectoryItem* item =
1666 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001667 *success = true;
1668
jeffhao10037c82012-01-23 15:06:23 -08001669 if (item->fields_size_ != 0) {
1670 DexFile::FieldAnnotationsItem* field_items = (DexFile::FieldAnnotationsItem*) (item + 1);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001671 LOAD_FIELD(field, field_items[0].field_idx_, "first_annotations_dir_definer field_id",
1672 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001673 return field->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001674 }
1675
1676 if (item->methods_size_ != 0) {
1677 DexFile::MethodAnnotationsItem* method_items = (DexFile::MethodAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001678 LOAD_METHOD(method, method_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001679 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001680 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001681 }
1682
1683 if (item->parameters_size_ != 0) {
1684 DexFile::ParameterAnnotationsItem* parameter_items = (DexFile::ParameterAnnotationsItem*) (item + 1);
Andreas Gampee09269c2014-06-06 18:45:35 -07001685 LOAD_METHOD(method, parameter_items[0].method_idx_, "first_annotations_dir_definer method id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001686 *success = false; return DexFile::kDexNoIndex16)
Andreas Gampee09269c2014-06-06 18:45:35 -07001687 return method->class_idx_;
jeffhao10037c82012-01-23 15:06:23 -08001688 }
1689
1690 return DexFile::kDexNoIndex16;
1691}
1692
1693bool DexFileVerifier::CheckInterStringIdItem() {
1694 const DexFile::StringId* item = reinterpret_cast<const DexFile::StringId*>(ptr_);
1695
1696 // Check the map to make sure it has the right offset->type.
1697 if (!CheckOffsetToTypeMap(item->string_data_off_, DexFile::kDexTypeStringDataItem)) {
1698 return false;
1699 }
1700
1701 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001702 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001703 const DexFile::StringId* prev_item = reinterpret_cast<const DexFile::StringId*>(previous_item_);
1704 const char* prev_str = dex_file_->GetStringData(*prev_item);
1705 const char* str = dex_file_->GetStringData(*item);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001706 if (UNLIKELY(CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues(prev_str, str) >= 0)) {
1707 ErrorStringPrintf("Out-of-order string_ids: '%s' then '%s'", prev_str, str);
jeffhao10037c82012-01-23 15:06:23 -08001708 return false;
1709 }
1710 }
1711
1712 ptr_ += sizeof(DexFile::StringId);
1713 return true;
1714}
1715
1716bool DexFileVerifier::CheckInterTypeIdItem() {
1717 const DexFile::TypeId* item = reinterpret_cast<const DexFile::TypeId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001718
1719 LOAD_STRING(descriptor, item->descriptor_idx_, "inter_type_id_item descriptor_idx")
jeffhao10037c82012-01-23 15:06:23 -08001720
1721 // Check that the descriptor is a valid type.
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001722 if (UNLIKELY(!IsValidDescriptor(descriptor))) {
1723 ErrorStringPrintf("Invalid type descriptor: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001724 return false;
1725 }
1726
1727 // Check ordering between items.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001728 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001729 const DexFile::TypeId* prev_item = reinterpret_cast<const DexFile::TypeId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001730 if (UNLIKELY(prev_item->descriptor_idx_ >= item->descriptor_idx_)) {
1731 ErrorStringPrintf("Out-of-order type_ids: %x then %x",
1732 prev_item->descriptor_idx_, item->descriptor_idx_);
jeffhao10037c82012-01-23 15:06:23 -08001733 return false;
1734 }
1735 }
1736
1737 ptr_ += sizeof(DexFile::TypeId);
1738 return true;
1739}
1740
1741bool DexFileVerifier::CheckInterProtoIdItem() {
1742 const DexFile::ProtoId* item = reinterpret_cast<const DexFile::ProtoId*>(ptr_);
Andreas Gampee09269c2014-06-06 18:45:35 -07001743
1744 LOAD_STRING(shorty, item->shorty_idx_, "inter_proto_id_item shorty_idx")
1745
jeffhao10037c82012-01-23 15:06:23 -08001746 if (item->parameters_off_ != 0 &&
1747 !CheckOffsetToTypeMap(item->parameters_off_, DexFile::kDexTypeTypeList)) {
1748 return false;
1749 }
1750
1751 // Check the return type and advance the shorty.
Andreas Gampee09269c2014-06-06 18:45:35 -07001752 LOAD_STRING_BY_TYPE(return_type, item->return_type_idx_, "inter_proto_id_item return_type_idx")
1753 if (!CheckShortyDescriptorMatch(*shorty, return_type, true)) {
jeffhao10037c82012-01-23 15:06:23 -08001754 return false;
1755 }
1756 shorty++;
1757
1758 DexFileParameterIterator it(*dex_file_, *item);
1759 while (it.HasNext() && *shorty != '\0') {
Andreas Gampebb836e12014-06-13 15:31:40 -07001760 if (!CheckIndex(it.GetTypeIdx(), dex_file_->NumTypeIds(),
1761 "inter_proto_id_item shorty type_idx")) {
1762 return false;
1763 }
jeffhao10037c82012-01-23 15:06:23 -08001764 const char* descriptor = it.GetDescriptor();
1765 if (!CheckShortyDescriptorMatch(*shorty, descriptor, false)) {
1766 return false;
1767 }
1768 it.Next();
1769 shorty++;
1770 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001771 if (UNLIKELY(it.HasNext() || *shorty != '\0')) {
1772 ErrorStringPrintf("Mismatched length for parameters and shorty");
jeffhao10037c82012-01-23 15:06:23 -08001773 return false;
1774 }
1775
1776 // Check ordering between items. This relies on type_ids being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001777 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001778 const DexFile::ProtoId* prev = reinterpret_cast<const DexFile::ProtoId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001779 if (UNLIKELY(prev->return_type_idx_ > item->return_type_idx_)) {
1780 ErrorStringPrintf("Out-of-order proto_id return types");
jeffhao10037c82012-01-23 15:06:23 -08001781 return false;
1782 } else if (prev->return_type_idx_ == item->return_type_idx_) {
1783 DexFileParameterIterator curr_it(*dex_file_, *item);
1784 DexFileParameterIterator prev_it(*dex_file_, *prev);
1785
1786 while (curr_it.HasNext() && prev_it.HasNext()) {
1787 uint16_t prev_idx = prev_it.GetTypeIdx();
1788 uint16_t curr_idx = curr_it.GetTypeIdx();
1789 if (prev_idx == DexFile::kDexNoIndex16) {
1790 break;
1791 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001792 if (UNLIKELY(curr_idx == DexFile::kDexNoIndex16)) {
1793 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001794 return false;
1795 }
1796
1797 if (prev_idx < curr_idx) {
1798 break;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001799 } else if (UNLIKELY(prev_idx > curr_idx)) {
1800 ErrorStringPrintf("Out-of-order proto_id arguments");
jeffhao10037c82012-01-23 15:06:23 -08001801 return false;
1802 }
1803
1804 prev_it.Next();
1805 curr_it.Next();
1806 }
1807 }
1808 }
1809
1810 ptr_ += sizeof(DexFile::ProtoId);
1811 return true;
1812}
1813
1814bool DexFileVerifier::CheckInterFieldIdItem() {
1815 const DexFile::FieldId* item = reinterpret_cast<const DexFile::FieldId*>(ptr_);
1816
1817 // Check that the class descriptor is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001818 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_field_id_item class_idx")
1819 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1820 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001821 return false;
1822 }
1823
1824 // Check that the type descriptor is a valid field name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001825 LOAD_STRING_BY_TYPE(type_descriptor, item->type_idx_, "inter_field_id_item type_idx")
1826 if (UNLIKELY(!IsValidDescriptor(type_descriptor) || type_descriptor[0] == 'V')) {
1827 ErrorStringPrintf("Invalid descriptor for type_idx: '%s'", type_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001828 return false;
1829 }
1830
1831 // Check that the name is valid.
Andreas Gampee09269c2014-06-06 18:45:35 -07001832 LOAD_STRING(descriptor, item->name_idx_, "inter_field_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001833 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1834 ErrorStringPrintf("Invalid field name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001835 return false;
1836 }
1837
1838 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001839 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001840 const DexFile::FieldId* prev_item = reinterpret_cast<const DexFile::FieldId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001841 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1842 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001843 return false;
1844 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001845 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1846 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001847 return false;
1848 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001849 if (UNLIKELY(prev_item->type_idx_ >= item->type_idx_)) {
1850 ErrorStringPrintf("Out-of-order field_ids");
jeffhao10037c82012-01-23 15:06:23 -08001851 return false;
1852 }
1853 }
1854 }
1855 }
1856
1857 ptr_ += sizeof(DexFile::FieldId);
1858 return true;
1859}
1860
1861bool DexFileVerifier::CheckInterMethodIdItem() {
1862 const DexFile::MethodId* item = reinterpret_cast<const DexFile::MethodId*>(ptr_);
1863
1864 // Check that the class descriptor is a valid reference name.
Andreas Gampee09269c2014-06-06 18:45:35 -07001865 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_method_id_item class_idx")
1866 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || (class_descriptor[0] != 'L' &&
1867 class_descriptor[0] != '['))) {
1868 ErrorStringPrintf("Invalid descriptor for class_idx: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001869 return false;
1870 }
1871
1872 // Check that the name is valid.
Andreas Gampedf10b322014-06-11 21:46:05 -07001873 LOAD_STRING(descriptor, item->name_idx_, "inter_method_id_item name_idx")
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001874 if (UNLIKELY(!IsValidMemberName(descriptor))) {
1875 ErrorStringPrintf("Invalid method name: '%s'", descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001876 return false;
1877 }
1878
Andreas Gampedf10b322014-06-11 21:46:05 -07001879 // Check that the proto id is valid.
1880 if (UNLIKELY(!CheckIndex(item->proto_idx_, dex_file_->NumProtoIds(),
1881 "inter_method_id_item proto_idx"))) {
1882 return false;
1883 }
1884
jeffhao10037c82012-01-23 15:06:23 -08001885 // Check ordering between items. This relies on the other sections being in order.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001886 if (previous_item_ != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001887 const DexFile::MethodId* prev_item = reinterpret_cast<const DexFile::MethodId*>(previous_item_);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001888 if (UNLIKELY(prev_item->class_idx_ > item->class_idx_)) {
1889 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001890 return false;
1891 } else if (prev_item->class_idx_ == item->class_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001892 if (UNLIKELY(prev_item->name_idx_ > item->name_idx_)) {
1893 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001894 return false;
1895 } else if (prev_item->name_idx_ == item->name_idx_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001896 if (UNLIKELY(prev_item->proto_idx_ >= item->proto_idx_)) {
1897 ErrorStringPrintf("Out-of-order method_ids");
jeffhao10037c82012-01-23 15:06:23 -08001898 return false;
1899 }
1900 }
1901 }
1902 }
1903
1904 ptr_ += sizeof(DexFile::MethodId);
1905 return true;
1906}
1907
1908bool DexFileVerifier::CheckInterClassDefItem() {
1909 const DexFile::ClassDef* item = reinterpret_cast<const DexFile::ClassDef*>(ptr_);
jeffhao10037c82012-01-23 15:06:23 -08001910
Andreas Gampe0ba238d2014-07-29 01:22:07 -07001911 // Check for duplicate class def.
1912 if (defined_classes_.find(item->class_idx_) != defined_classes_.end()) {
1913 ErrorStringPrintf("Redefinition of class with type idx: '%d'", item->class_idx_);
1914 return false;
1915 }
1916 defined_classes_.insert(item->class_idx_);
1917
Andreas Gampee09269c2014-06-06 18:45:35 -07001918 LOAD_STRING_BY_TYPE(class_descriptor, item->class_idx_, "inter_class_def_item class_idx")
1919 if (UNLIKELY(!IsValidDescriptor(class_descriptor) || class_descriptor[0] != 'L')) {
1920 ErrorStringPrintf("Invalid class descriptor: '%s'", class_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001921 return false;
1922 }
1923
Andreas Gampeacc2bb62014-07-17 19:26:50 -07001924 // Only allow non-runtime modifiers.
1925 if ((item->access_flags_ & ~kAccJavaFlagsMask) != 0) {
1926 ErrorStringPrintf("Invalid class flags: '%d'", item->access_flags_);
1927 return false;
1928 }
1929
jeffhao10037c82012-01-23 15:06:23 -08001930 if (item->interfaces_off_ != 0 &&
1931 !CheckOffsetToTypeMap(item->interfaces_off_, DexFile::kDexTypeTypeList)) {
1932 return false;
1933 }
1934 if (item->annotations_off_ != 0 &&
1935 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationsDirectoryItem)) {
1936 return false;
1937 }
1938 if (item->class_data_off_ != 0 &&
1939 !CheckOffsetToTypeMap(item->class_data_off_, DexFile::kDexTypeClassDataItem)) {
1940 return false;
1941 }
1942 if (item->static_values_off_ != 0 &&
1943 !CheckOffsetToTypeMap(item->static_values_off_, DexFile::kDexTypeEncodedArrayItem)) {
1944 return false;
1945 }
1946
1947 if (item->superclass_idx_ != DexFile::kDexNoIndex16) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001948 LOAD_STRING_BY_TYPE(superclass_descriptor, item->superclass_idx_,
1949 "inter_class_def_item superclass_idx")
1950 if (UNLIKELY(!IsValidDescriptor(superclass_descriptor) || superclass_descriptor[0] != 'L')) {
1951 ErrorStringPrintf("Invalid superclass: '%s'", superclass_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001952 return false;
1953 }
1954 }
1955
1956 const DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(*item);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001957 if (interfaces != nullptr) {
jeffhao10037c82012-01-23 15:06:23 -08001958 uint32_t size = interfaces->Size();
1959
1960 // Ensure that all interfaces refer to classes (not arrays or primitives).
1961 for (uint32_t i = 0; i < size; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001962 LOAD_STRING_BY_TYPE(inf_descriptor, interfaces->GetTypeItem(i).type_idx_,
1963 "inter_class_def_item interface type_idx")
1964 if (UNLIKELY(!IsValidDescriptor(inf_descriptor) || inf_descriptor[0] != 'L')) {
1965 ErrorStringPrintf("Invalid interface: '%s'", inf_descriptor);
jeffhao10037c82012-01-23 15:06:23 -08001966 return false;
1967 }
1968 }
1969
1970 /*
1971 * Ensure that there are no duplicates. This is an O(N^2) test, but in
1972 * practice the number of interfaces implemented by any given class is low.
1973 */
1974 for (uint32_t i = 1; i < size; i++) {
1975 uint32_t idx1 = interfaces->GetTypeItem(i).type_idx_;
1976 for (uint32_t j =0; j < i; j++) {
1977 uint32_t idx2 = interfaces->GetTypeItem(j).type_idx_;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001978 if (UNLIKELY(idx1 == idx2)) {
1979 ErrorStringPrintf("Duplicate interface: '%s'", dex_file_->StringByTypeIdx(idx1));
jeffhao10037c82012-01-23 15:06:23 -08001980 return false;
1981 }
1982 }
1983 }
1984 }
1985
1986 // Check that references in class_data_item are to the right class.
1987 if (item->class_data_off_ != 0) {
Ian Rogers13735952014-10-08 12:43:28 -07001988 const uint8_t* data = begin_ + item->class_data_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07001989 bool success;
1990 uint16_t data_definer = FindFirstClassDataDefiner(data, &success);
1991 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07001992 return false;
1993 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001994 if (UNLIKELY((data_definer != item->class_idx_) && (data_definer != DexFile::kDexNoIndex16))) {
1995 ErrorStringPrintf("Invalid class_data_item");
jeffhao10037c82012-01-23 15:06:23 -08001996 return false;
1997 }
1998 }
1999
2000 // Check that references in annotations_directory_item are to right class.
2001 if (item->annotations_off_ != 0) {
Andreas Gampeb512c0e2016-02-19 19:45:34 -08002002 // annotations_off_ is supposed to be aligned by 4.
2003 if (!IsAlignedParam(item->annotations_off_, 4)) {
2004 ErrorStringPrintf("Invalid annotations_off_, not aligned by 4");
2005 return false;
2006 }
Ian Rogers13735952014-10-08 12:43:28 -07002007 const uint8_t* data = begin_ + item->annotations_off_;
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002008 bool success;
2009 uint16_t annotations_definer = FindFirstAnnotationsDirectoryDefiner(data, &success);
2010 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002011 return false;
2012 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002013 if (UNLIKELY((annotations_definer != item->class_idx_) &&
2014 (annotations_definer != DexFile::kDexNoIndex16))) {
2015 ErrorStringPrintf("Invalid annotations_directory_item");
jeffhao10037c82012-01-23 15:06:23 -08002016 return false;
2017 }
2018 }
2019
2020 ptr_ += sizeof(DexFile::ClassDef);
2021 return true;
2022}
2023
2024bool DexFileVerifier::CheckInterAnnotationSetRefList() {
2025 const DexFile::AnnotationSetRefList* list =
2026 reinterpret_cast<const DexFile::AnnotationSetRefList*>(ptr_);
2027 const DexFile::AnnotationSetRefItem* item = list->list_;
2028 uint32_t count = list->size_;
2029
2030 while (count--) {
2031 if (item->annotations_off_ != 0 &&
2032 !CheckOffsetToTypeMap(item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2033 return false;
2034 }
2035 item++;
2036 }
2037
Ian Rogers13735952014-10-08 12:43:28 -07002038 ptr_ = reinterpret_cast<const uint8_t*>(item);
jeffhao10037c82012-01-23 15:06:23 -08002039 return true;
2040}
2041
2042bool DexFileVerifier::CheckInterAnnotationSetItem() {
2043 const DexFile::AnnotationSetItem* set = reinterpret_cast<const DexFile::AnnotationSetItem*>(ptr_);
2044 const uint32_t* offsets = set->entries_;
2045 uint32_t count = set->size_;
2046 uint32_t last_idx = 0;
2047
2048 for (uint32_t i = 0; i < count; i++) {
2049 if (*offsets != 0 && !CheckOffsetToTypeMap(*offsets, DexFile::kDexTypeAnnotationItem)) {
2050 return false;
2051 }
2052
2053 // Get the annotation from the offset and the type index for the annotation.
2054 const DexFile::AnnotationItem* annotation =
Ian Rogers30fab402012-01-23 15:43:46 -08002055 reinterpret_cast<const DexFile::AnnotationItem*>(begin_ + *offsets);
jeffhao10037c82012-01-23 15:06:23 -08002056 const uint8_t* data = annotation->annotation_;
2057 uint32_t idx = DecodeUnsignedLeb128(&data);
2058
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002059 if (UNLIKELY(last_idx >= idx && i != 0)) {
2060 ErrorStringPrintf("Out-of-order entry types: %x then %x", last_idx, idx);
jeffhao10037c82012-01-23 15:06:23 -08002061 return false;
2062 }
2063
2064 last_idx = idx;
2065 offsets++;
2066 }
2067
Ian Rogers13735952014-10-08 12:43:28 -07002068 ptr_ = reinterpret_cast<const uint8_t*>(offsets);
jeffhao10037c82012-01-23 15:06:23 -08002069 return true;
2070}
2071
2072bool DexFileVerifier::CheckInterClassDataItem() {
2073 ClassDataItemIterator it(*dex_file_, ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002074 bool success;
2075 uint16_t defining_class = FindFirstClassDataDefiner(ptr_, &success);
2076 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002077 return false;
2078 }
jeffhao10037c82012-01-23 15:06:23 -08002079
2080 for (; it.HasNextStaticField() || it.HasNextInstanceField(); it.Next()) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002081 LOAD_FIELD(field, it.GetMemberIndex(), "inter_class_data_item field_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002082 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002083 ErrorStringPrintf("Mismatched defining class for class_data_item field");
jeffhao10037c82012-01-23 15:06:23 -08002084 return false;
2085 }
2086 }
2087 for (; it.HasNextDirectMethod() || it.HasNextVirtualMethod(); it.Next()) {
2088 uint32_t code_off = it.GetMethodCodeItemOffset();
2089 if (code_off != 0 && !CheckOffsetToTypeMap(code_off, DexFile::kDexTypeCodeItem)) {
2090 return false;
2091 }
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002092 LOAD_METHOD(method, it.GetMemberIndex(), "inter_class_data_item method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002093 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002094 ErrorStringPrintf("Mismatched defining class for class_data_item method");
jeffhao10037c82012-01-23 15:06:23 -08002095 return false;
2096 }
2097 }
2098
2099 ptr_ = it.EndDataPointer();
2100 return true;
2101}
2102
2103bool DexFileVerifier::CheckInterAnnotationsDirectoryItem() {
2104 const DexFile::AnnotationsDirectoryItem* item =
2105 reinterpret_cast<const DexFile::AnnotationsDirectoryItem*>(ptr_);
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002106 bool success;
2107 uint16_t defining_class = FindFirstAnnotationsDirectoryDefiner(ptr_, &success);
2108 if (!success) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002109 return false;
2110 }
jeffhao10037c82012-01-23 15:06:23 -08002111
2112 if (item->class_annotations_off_ != 0 &&
2113 !CheckOffsetToTypeMap(item->class_annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2114 return false;
2115 }
2116
2117 // Field annotations follow immediately after the annotations directory.
2118 const DexFile::FieldAnnotationsItem* field_item =
2119 reinterpret_cast<const DexFile::FieldAnnotationsItem*>(item + 1);
2120 uint32_t field_count = item->fields_size_;
2121 for (uint32_t i = 0; i < field_count; i++) {
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002122 LOAD_FIELD(field, field_item->field_idx_, "inter_annotations_directory_item field_id",
2123 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002124 if (UNLIKELY(field->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002125 ErrorStringPrintf("Mismatched defining class for field_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002126 return false;
2127 }
2128 if (!CheckOffsetToTypeMap(field_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2129 return false;
2130 }
2131 field_item++;
2132 }
2133
2134 // Method annotations follow immediately after field annotations.
2135 const DexFile::MethodAnnotationsItem* method_item =
2136 reinterpret_cast<const DexFile::MethodAnnotationsItem*>(field_item);
2137 uint32_t method_count = item->methods_size_;
2138 for (uint32_t i = 0; i < method_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002139 LOAD_METHOD(method, method_item->method_idx_, "inter_annotations_directory_item method_id",
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002140 return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002141 if (UNLIKELY(method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002142 ErrorStringPrintf("Mismatched defining class for method_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002143 return false;
2144 }
2145 if (!CheckOffsetToTypeMap(method_item->annotations_off_, DexFile::kDexTypeAnnotationSetItem)) {
2146 return false;
2147 }
2148 method_item++;
2149 }
2150
2151 // Parameter annotations follow immediately after method annotations.
2152 const DexFile::ParameterAnnotationsItem* parameter_item =
2153 reinterpret_cast<const DexFile::ParameterAnnotationsItem*>(method_item);
2154 uint32_t parameter_count = item->parameters_size_;
2155 for (uint32_t i = 0; i < parameter_count; i++) {
Andreas Gampee09269c2014-06-06 18:45:35 -07002156 LOAD_METHOD(parameter_method, parameter_item->method_idx_,
Andreas Gampe5e31dda2014-06-13 11:35:12 -07002157 "inter_annotations_directory_item parameter method_id", return false)
Andreas Gampee09269c2014-06-06 18:45:35 -07002158 if (UNLIKELY(parameter_method->class_idx_ != defining_class)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002159 ErrorStringPrintf("Mismatched defining class for parameter_annotation");
jeffhao10037c82012-01-23 15:06:23 -08002160 return false;
2161 }
Dragos Sbirlea2b87ddf2013-05-28 14:14:12 -07002162 if (!CheckOffsetToTypeMap(parameter_item->annotations_off_,
2163 DexFile::kDexTypeAnnotationSetRefList)) {
jeffhao10037c82012-01-23 15:06:23 -08002164 return false;
2165 }
2166 parameter_item++;
2167 }
2168
Ian Rogers13735952014-10-08 12:43:28 -07002169 ptr_ = reinterpret_cast<const uint8_t*>(parameter_item);
jeffhao10037c82012-01-23 15:06:23 -08002170 return true;
2171}
2172
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002173bool DexFileVerifier::CheckInterSectionIterate(size_t offset, uint32_t count, uint16_t type) {
jeffhao10037c82012-01-23 15:06:23 -08002174 // Get the right alignment mask for the type of section.
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002175 size_t alignment_mask;
jeffhao10037c82012-01-23 15:06:23 -08002176 switch (type) {
2177 case DexFile::kDexTypeClassDataItem:
2178 alignment_mask = sizeof(uint8_t) - 1;
2179 break;
2180 default:
2181 alignment_mask = sizeof(uint32_t) - 1;
2182 break;
2183 }
2184
2185 // Iterate through the items in the section.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002186 previous_item_ = nullptr;
jeffhao10037c82012-01-23 15:06:23 -08002187 for (uint32_t i = 0; i < count; i++) {
2188 uint32_t new_offset = (offset + alignment_mask) & ~alignment_mask;
Ian Rogers30fab402012-01-23 15:43:46 -08002189 ptr_ = begin_ + new_offset;
Ian Rogers13735952014-10-08 12:43:28 -07002190 const uint8_t* prev_ptr = ptr_;
jeffhao10037c82012-01-23 15:06:23 -08002191
2192 // Check depending on the section type.
2193 switch (type) {
2194 case DexFile::kDexTypeStringIdItem: {
2195 if (!CheckInterStringIdItem()) {
2196 return false;
2197 }
2198 break;
2199 }
2200 case DexFile::kDexTypeTypeIdItem: {
2201 if (!CheckInterTypeIdItem()) {
2202 return false;
2203 }
2204 break;
2205 }
2206 case DexFile::kDexTypeProtoIdItem: {
2207 if (!CheckInterProtoIdItem()) {
2208 return false;
2209 }
2210 break;
2211 }
2212 case DexFile::kDexTypeFieldIdItem: {
2213 if (!CheckInterFieldIdItem()) {
2214 return false;
2215 }
2216 break;
2217 }
2218 case DexFile::kDexTypeMethodIdItem: {
2219 if (!CheckInterMethodIdItem()) {
2220 return false;
2221 }
2222 break;
2223 }
2224 case DexFile::kDexTypeClassDefItem: {
2225 if (!CheckInterClassDefItem()) {
2226 return false;
2227 }
2228 break;
2229 }
2230 case DexFile::kDexTypeAnnotationSetRefList: {
2231 if (!CheckInterAnnotationSetRefList()) {
2232 return false;
2233 }
2234 break;
2235 }
2236 case DexFile::kDexTypeAnnotationSetItem: {
2237 if (!CheckInterAnnotationSetItem()) {
2238 return false;
2239 }
2240 break;
2241 }
2242 case DexFile::kDexTypeClassDataItem: {
2243 if (!CheckInterClassDataItem()) {
2244 return false;
2245 }
2246 break;
2247 }
2248 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2249 if (!CheckInterAnnotationsDirectoryItem()) {
2250 return false;
2251 }
2252 break;
2253 }
2254 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002255 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002256 return false;
2257 }
2258
2259 previous_item_ = prev_ptr;
Ian Rogers8a6bbfc2014-01-23 13:29:07 -08002260 offset = ptr_ - begin_;
jeffhao10037c82012-01-23 15:06:23 -08002261 }
2262
2263 return true;
2264}
2265
2266bool DexFileVerifier::CheckInterSection() {
Ian Rogers30fab402012-01-23 15:43:46 -08002267 const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(begin_ + header_->map_off_);
jeffhao10037c82012-01-23 15:06:23 -08002268 const DexFile::MapItem* item = map->list_;
2269 uint32_t count = map->size_;
2270
2271 // Cross check the items listed in the map.
2272 while (count--) {
2273 uint32_t section_offset = item->offset_;
2274 uint32_t section_count = item->size_;
2275 uint16_t type = item->type_;
2276
2277 switch (type) {
2278 case DexFile::kDexTypeHeaderItem:
2279 case DexFile::kDexTypeMapList:
2280 case DexFile::kDexTypeTypeList:
2281 case DexFile::kDexTypeCodeItem:
2282 case DexFile::kDexTypeStringDataItem:
2283 case DexFile::kDexTypeDebugInfoItem:
2284 case DexFile::kDexTypeAnnotationItem:
2285 case DexFile::kDexTypeEncodedArrayItem:
2286 break;
2287 case DexFile::kDexTypeStringIdItem:
2288 case DexFile::kDexTypeTypeIdItem:
2289 case DexFile::kDexTypeProtoIdItem:
2290 case DexFile::kDexTypeFieldIdItem:
2291 case DexFile::kDexTypeMethodIdItem:
2292 case DexFile::kDexTypeClassDefItem:
2293 case DexFile::kDexTypeAnnotationSetRefList:
2294 case DexFile::kDexTypeAnnotationSetItem:
2295 case DexFile::kDexTypeClassDataItem:
2296 case DexFile::kDexTypeAnnotationsDirectoryItem: {
2297 if (!CheckInterSectionIterate(section_offset, section_count, type)) {
2298 return false;
2299 }
2300 break;
2301 }
2302 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002303 ErrorStringPrintf("Unknown map item type %x", type);
jeffhao10037c82012-01-23 15:06:23 -08002304 return false;
2305 }
2306
2307 item++;
2308 }
2309
2310 return true;
2311}
2312
2313bool DexFileVerifier::Verify() {
2314 // Check the header.
2315 if (!CheckHeader()) {
2316 return false;
2317 }
2318
2319 // Check the map section.
2320 if (!CheckMap()) {
2321 return false;
2322 }
2323
2324 // Check structure within remaining sections.
2325 if (!CheckIntraSection()) {
2326 return false;
2327 }
2328
2329 // Check references from one section to another.
2330 if (!CheckInterSection()) {
2331 return false;
2332 }
2333
2334 return true;
2335}
2336
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002337void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...) {
2338 va_list ap;
2339 va_start(ap, fmt);
2340 DCHECK(failure_reason_.empty()) << failure_reason_;
2341 failure_reason_ = StringPrintf("Failure to verify dex file '%s': ", location_);
2342 StringAppendV(&failure_reason_, fmt, ap);
2343 va_end(ap);
2344}
2345
Andreas Gampee6215c02015-08-31 18:54:38 -07002346// Fields and methods may have only one of public/protected/private.
2347static bool CheckAtMostOneOfPublicProtectedPrivate(uint32_t flags) {
2348 size_t count = (((flags & kAccPublic) == 0) ? 0 : 1) +
2349 (((flags & kAccProtected) == 0) ? 0 : 1) +
2350 (((flags & kAccPrivate) == 0) ? 0 : 1);
2351 return count <= 1;
2352}
2353
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002354// Helper functions to retrieve names from the dex file. We do not want to rely on DexFile
2355// functionality, as we're still verifying the dex file. begin and header correspond to the
2356// underscored variants in the DexFileVerifier.
2357
2358static std::string GetStringOrError(const uint8_t* const begin,
2359 const DexFile::Header* const header,
2360 uint32_t string_idx) {
2361 if (header->string_ids_size_ < string_idx) {
2362 return "(error)";
2363 }
2364
2365 const DexFile::StringId* string_id =
2366 reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx;
2367
2368 // Assume that the data is OK at this point. String data has been checked at this point.
2369
2370 const uint8_t* ptr = begin + string_id->string_data_off_;
2371 DecodeUnsignedLeb128(&ptr);
2372 return reinterpret_cast<const char*>(ptr);
2373}
2374
2375static std::string GetClassOrError(const uint8_t* const begin,
2376 const DexFile::Header* const header,
2377 uint32_t class_idx) {
2378 if (header->type_ids_size_ < class_idx) {
2379 return "(error)";
2380 }
2381
2382 const DexFile::TypeId* type_id =
2383 reinterpret_cast<const DexFile::TypeId*>(begin + header->type_ids_off_) + class_idx;
2384
2385 // Assume that the data is OK at this point. Type id offsets have been checked at this point.
2386
2387 return GetStringOrError(begin, header, type_id->descriptor_idx_);
2388}
2389
2390static std::string GetFieldDescriptionOrError(const uint8_t* const begin,
2391 const DexFile::Header* const header,
2392 uint32_t idx) {
2393 if (header->field_ids_size_ < idx) {
2394 return "(error)";
2395 }
2396
2397 const DexFile::FieldId* field_id =
2398 reinterpret_cast<const DexFile::FieldId*>(begin + header->field_ids_off_) + idx;
2399
2400 // Assume that the data is OK at this point. Field id offsets have been checked at this point.
2401
2402 std::string class_name = GetClassOrError(begin, header, field_id->class_idx_);
2403 std::string field_name = GetStringOrError(begin, header, field_id->name_idx_);
2404
2405 return class_name + "." + field_name;
2406}
2407
2408static std::string GetMethodDescriptionOrError(const uint8_t* const begin,
2409 const DexFile::Header* const header,
2410 uint32_t idx) {
2411 if (header->method_ids_size_ < idx) {
2412 return "(error)";
2413 }
2414
2415 const DexFile::MethodId* method_id =
2416 reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) + idx;
2417
2418 // Assume that the data is OK at this point. Method id offsets have been checked at this point.
2419
2420 std::string class_name = GetClassOrError(begin, header, method_id->class_idx_);
2421 std::string method_name = GetStringOrError(begin, header, method_id->name_idx_);
2422
2423 return class_name + "." + method_name;
2424}
2425
2426bool DexFileVerifier::CheckFieldAccessFlags(uint32_t idx,
2427 uint32_t field_access_flags,
Andreas Gampee6215c02015-08-31 18:54:38 -07002428 uint32_t class_access_flags,
2429 std::string* error_msg) {
2430 // Generally sort out >16-bit flags.
2431 if ((field_access_flags & ~kAccJavaFlagsMask) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002432 *error_msg = StringPrintf("Bad field access_flags for %s: %x(%s)",
2433 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2434 field_access_flags,
2435 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002436 return false;
2437 }
2438
2439 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2440 constexpr uint32_t kFieldAccessFlags = kAccPublic |
2441 kAccPrivate |
2442 kAccProtected |
2443 kAccStatic |
2444 kAccFinal |
2445 kAccVolatile |
2446 kAccTransient |
2447 kAccSynthetic |
2448 kAccEnum;
2449
2450 // Fields may have only one of public/protected/final.
2451 if (!CheckAtMostOneOfPublicProtectedPrivate(field_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002452 *error_msg = StringPrintf("Field may have only one of public/protected/private, %s: %x(%s)",
2453 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2454 field_access_flags,
2455 PrettyJavaAccessFlags(field_access_flags).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002456 return false;
2457 }
2458
2459 // Interfaces have a pretty restricted list.
2460 if ((class_access_flags & kAccInterface) != 0) {
2461 // Interface fields must be public final static.
2462 constexpr uint32_t kPublicFinalStatic = kAccPublic | kAccFinal | kAccStatic;
2463 if ((field_access_flags & kPublicFinalStatic) != kPublicFinalStatic) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002464 *error_msg = StringPrintf("Interface field is not public final static, %s: %x(%s)",
2465 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2466 field_access_flags,
2467 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002468 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002469 return false;
2470 } else {
2471 // Allow in older versions, but warn.
2472 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2473 << *error_msg;
2474 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002475 }
2476 // Interface fields may be synthetic, but may not have other flags.
2477 constexpr uint32_t kDisallowed = ~(kPublicFinalStatic | kAccSynthetic);
2478 if ((field_access_flags & kFieldAccessFlags & kDisallowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002479 *error_msg = StringPrintf("Interface field has disallowed flag, %s: %x(%s)",
2480 GetFieldDescriptionOrError(begin_, header_, idx).c_str(),
2481 field_access_flags,
2482 PrettyJavaAccessFlags(field_access_flags).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002483 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002484 return false;
2485 } else {
2486 // Allow in older versions, but warn.
2487 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2488 << *error_msg;
2489 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002490 }
2491 return true;
2492 }
2493
2494 // Volatile fields may not be final.
2495 constexpr uint32_t kVolatileFinal = kAccVolatile | kAccFinal;
2496 if ((field_access_flags & kVolatileFinal) == kVolatileFinal) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002497 *error_msg = StringPrintf("Fields may not be volatile and final: %s",
2498 GetFieldDescriptionOrError(begin_, header_, idx).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002499 return false;
2500 }
2501
2502 return true;
2503}
2504
2505// Try to find the name of the method with the given index. We do not want to rely on DexFile
2506// infrastructure at this point, so do it all by hand. begin and header correspond to begin_ and
2507// header_ of the DexFileVerifier. str will contain the pointer to the method name on success
2508// (flagged by the return value), otherwise error_msg will contain an error string.
2509static bool FindMethodName(uint32_t method_index,
2510 const uint8_t* begin,
2511 const DexFile::Header* header,
2512 const char** str,
2513 std::string* error_msg) {
2514 if (method_index >= header->method_ids_size_) {
2515 *error_msg = "Method index not available for method flags verification";
2516 return false;
2517 }
2518 uint32_t string_idx =
2519 (reinterpret_cast<const DexFile::MethodId*>(begin + header->method_ids_off_) +
2520 method_index)->name_idx_;
2521 if (string_idx >= header->string_ids_size_) {
2522 *error_msg = "String index not available for method flags verification";
2523 return false;
2524 }
2525 uint32_t string_off =
2526 (reinterpret_cast<const DexFile::StringId*>(begin + header->string_ids_off_) + string_idx)->
2527 string_data_off_;
2528 if (string_off >= header->file_size_) {
2529 *error_msg = "String offset out of bounds for method flags verification";
2530 return false;
2531 }
2532 const uint8_t* str_data_ptr = begin + string_off;
2533 DecodeUnsignedLeb128(&str_data_ptr);
2534 *str = reinterpret_cast<const char*>(str_data_ptr);
2535 return true;
2536}
2537
2538bool DexFileVerifier::CheckMethodAccessFlags(uint32_t method_index,
2539 uint32_t method_access_flags,
2540 uint32_t class_access_flags,
2541 bool has_code,
2542 bool expect_direct,
2543 std::string* error_msg) {
2544 // Generally sort out >16-bit flags, except dex knows Constructor and DeclaredSynchronized.
2545 constexpr uint32_t kAllMethodFlags =
2546 kAccJavaFlagsMask | kAccConstructor | kAccDeclaredSynchronized;
2547 if ((method_access_flags & ~kAllMethodFlags) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002548 *error_msg = StringPrintf("Bad method access_flags for %s: %x",
2549 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2550 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002551 return false;
2552 }
2553
2554 // Flags allowed on fields, in general. Other lower-16-bit flags are to be ignored.
2555 constexpr uint32_t kMethodAccessFlags = kAccPublic |
2556 kAccPrivate |
2557 kAccProtected |
2558 kAccStatic |
2559 kAccFinal |
2560 kAccSynthetic |
2561 kAccSynchronized |
2562 kAccBridge |
2563 kAccVarargs |
2564 kAccNative |
2565 kAccAbstract |
2566 kAccStrict;
2567
2568 // Methods may have only one of public/protected/final.
2569 if (!CheckAtMostOneOfPublicProtectedPrivate(method_access_flags)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002570 *error_msg = StringPrintf("Method may have only one of public/protected/private, %s: %x",
2571 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002572 method_access_flags);
2573 return false;
2574 }
2575
2576 // Try to find the name, to check for constructor properties.
2577 const char* str;
2578 if (!FindMethodName(method_index, begin_, header_, &str, error_msg)) {
2579 return false;
2580 }
2581 bool is_init_by_name = false;
2582 constexpr const char* kInitName = "<init>";
2583 size_t str_offset = (reinterpret_cast<const uint8_t*>(str) - begin_);
2584 if (header_->file_size_ - str_offset >= sizeof(kInitName)) {
2585 is_init_by_name = strcmp(kInitName, str) == 0;
2586 }
2587 bool is_clinit_by_name = false;
2588 constexpr const char* kClinitName = "<clinit>";
2589 if (header_->file_size_ - str_offset >= sizeof(kClinitName)) {
2590 is_clinit_by_name = strcmp(kClinitName, str) == 0;
2591 }
2592 bool is_constructor = is_init_by_name || is_clinit_by_name;
2593
2594 // Only methods named "<clinit>" or "<init>" may be marked constructor. Note: we cannot enforce
2595 // the reverse for backwards compatibility reasons.
2596 if (((method_access_flags & kAccConstructor) != 0) && !is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002597 *error_msg =
2598 StringPrintf("Method %" PRIu32 "(%s) is marked constructor, but doesn't match name",
2599 method_index,
2600 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002601 return false;
2602 }
2603 // Check that the static constructor (= static initializer) is named "<clinit>" and that the
2604 // instance constructor is called "<init>".
2605 if (is_constructor) {
2606 bool is_static = (method_access_flags & kAccStatic) != 0;
2607 if (is_static ^ is_clinit_by_name) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002608 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) is not flagged correctly wrt/ static.",
2609 method_index,
2610 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002611 return false;
2612 }
2613 }
2614 // Check that static and private methods, as well as constructors, are in the direct methods list,
2615 // and other methods in the virtual methods list.
2616 bool is_direct = (method_access_flags & (kAccStatic | kAccPrivate)) != 0 || is_constructor;
2617 if (is_direct != expect_direct) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002618 *error_msg = StringPrintf("Direct/virtual method %" PRIu32 "(%s) not in expected list %d",
Andreas Gampee6215c02015-08-31 18:54:38 -07002619 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002620 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002621 expect_direct);
2622 return false;
2623 }
2624
2625
2626 // From here on out it is easier to mask out the bits we're supposed to ignore.
2627 method_access_flags &= kMethodAccessFlags;
2628
Alex Lightd7c10c22016-03-31 10:03:07 -07002629 // Interfaces are special.
2630 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightb55f1ac2016-04-12 15:50:55 -07002631 // Non-static interface methods must be public or private.
2632 uint32_t desired_flags = (kAccPublic | kAccStatic);
2633 if (dex_file_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
2634 desired_flags |= kAccPrivate;
2635 }
2636 if ((method_access_flags & desired_flags) == 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002637 *error_msg = StringPrintf("Interface virtual method %" PRIu32 "(%s) is not public",
2638 method_index,
2639 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002640 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002641 return false;
2642 } else {
2643 // Allow in older versions, but warn.
2644 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2645 << *error_msg;
2646 }
2647 }
2648 }
2649
Andreas Gampee6215c02015-08-31 18:54:38 -07002650 // If there aren't any instructions, make sure that's expected.
2651 if (!has_code) {
2652 // Only native or abstract methods may not have code.
2653 if ((method_access_flags & (kAccNative | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002654 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has no code, but is not marked native or "
Andreas Gampee6215c02015-08-31 18:54:38 -07002655 "abstract",
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002656 method_index,
2657 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002658 return false;
2659 }
2660 // Constructors must always have code.
2661 if (is_constructor) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002662 *error_msg = StringPrintf("Constructor %u(%s) must not be abstract or native",
2663 method_index,
2664 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002665 return false;
2666 }
2667 if ((method_access_flags & kAccAbstract) != 0) {
2668 // Abstract methods are not allowed to have the following flags.
2669 constexpr uint32_t kForbidden =
2670 kAccPrivate | kAccStatic | kAccFinal | kAccNative | kAccStrict | kAccSynchronized;
2671 if ((method_access_flags & kForbidden) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002672 *error_msg = StringPrintf("Abstract method %" PRIu32 "(%s) has disallowed access flags %x",
2673 method_index,
2674 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
2675 method_access_flags);
Andreas Gampee6215c02015-08-31 18:54:38 -07002676 return false;
2677 }
Andreas Gampe97b11352015-12-10 16:23:41 -08002678 // Abstract methods should be in an abstract class or interface.
Andreas Gampee6215c02015-08-31 18:54:38 -07002679 if ((class_access_flags & (kAccInterface | kAccAbstract)) == 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002680 LOG(WARNING) << "Method " << GetMethodDescriptionOrError(begin_, header_, method_index)
Andreas Gampe97b11352015-12-10 16:23:41 -08002681 << " is abstract, but the declaring class is neither abstract nor an "
2682 << "interface in dex file "
2683 << dex_file_->GetLocation();
Andreas Gampee6215c02015-08-31 18:54:38 -07002684 }
2685 }
2686 // Interfaces are special.
2687 if ((class_access_flags & kAccInterface) != 0) {
Alex Lightd7c10c22016-03-31 10:03:07 -07002688 // Interface methods without code must be abstract.
Andreas Gampee6215c02015-08-31 18:54:38 -07002689 if ((method_access_flags & (kAccPublic | kAccAbstract)) != (kAccPublic | kAccAbstract)) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002690 *error_msg = StringPrintf("Interface method %" PRIu32 "(%s) is not public and abstract",
2691 method_index,
2692 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Alex Lightb55f1ac2016-04-12 15:50:55 -07002693 if (header_->GetVersion() >= DexFile::kDefaultMethodsVersion) {
Andreas Gampe76ed99d2016-03-28 18:31:29 -07002694 return false;
2695 } else {
2696 // Allow in older versions, but warn.
2697 LOG(WARNING) << "This dex file is invalid and will be rejected in the future. Error is: "
2698 << *error_msg;
2699 }
Andreas Gampee6215c02015-08-31 18:54:38 -07002700 }
2701 // At this point, we know the method is public and abstract. This means that all the checks
2702 // for invalid combinations above applies. In addition, interface methods must not be
2703 // protected. This is caught by the check for only-one-of-public-protected-private.
2704 }
2705 return true;
2706 }
2707
2708 // When there's code, the method must not be native or abstract.
2709 if ((method_access_flags & (kAccNative | kAccAbstract)) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002710 *error_msg = StringPrintf("Method %" PRIu32 "(%s) has code, but is marked native or abstract",
2711 method_index,
2712 GetMethodDescriptionOrError(begin_, header_, method_index).c_str());
Andreas Gampee6215c02015-08-31 18:54:38 -07002713 return false;
2714 }
2715
Andreas Gampee6215c02015-08-31 18:54:38 -07002716 // Instance constructors must not be synchronized and a few other flags.
2717 if (is_init_by_name) {
2718 static constexpr uint32_t kInitAllowed =
2719 kAccPrivate | kAccProtected | kAccPublic | kAccStrict | kAccVarargs | kAccSynthetic;
2720 if ((method_access_flags & ~kInitAllowed) != 0) {
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002721 *error_msg = StringPrintf("Constructor %" PRIu32 "(%s) flagged inappropriately %x",
Andreas Gampee6215c02015-08-31 18:54:38 -07002722 method_index,
Andreas Gampec9f0ba12016-02-09 09:21:04 -08002723 GetMethodDescriptionOrError(begin_, header_, method_index).c_str(),
Andreas Gampee6215c02015-08-31 18:54:38 -07002724 method_access_flags);
2725 return false;
2726 }
2727 }
2728
2729 return true;
2730}
2731
jeffhao10037c82012-01-23 15:06:23 -08002732} // namespace art