2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Byte-swapping and verification of dex files.
23 #include "DexDataMap.h"
35 # error "byte ordering not defined"
38 #if __BYTE_ORDER == __LITTLE_ENDIAN
39 # define SWAP2(_value) (_value)
40 # define SWAP4(_value) (_value)
41 # define SWAP8(_value) (_value)
43 # define SWAP2(_value) endianSwapU2((_value))
44 # define SWAP4(_value) endianSwapU4((_value))
45 # define SWAP8(_value) endianSwapU8((_value))
46 static u2 endianSwapU2(u2 value) {
47 return (value >> 8) | (value << 8);
49 static u4 endianSwapU4(u4 value) {
50 /* ABCD --> CDAB --> DCBA */
51 value = (value >> 16) | (value << 16);
52 return ((value & 0xff00ff00) >> 8) | ((value << 8) & 0xff00ff00);
54 static u8 endianSwapU8(u8 value) {
55 /* ABCDEFGH --> EFGHABCD --> GHEFCDAB --> HGFEDCBA */
56 value = (value >> 32) | (value << 32);
57 value = ((value & 0xffff0000ffff0000ULL) >> 16) |
58 ((value << 16) & 0xffff0000ffff0000ULL);
59 return ((value & 0xff00ff00ff00ff00ULL) >> 8) |
60 ((value << 8) & 0xff00ff00ff00ff00ULL);
64 #define SWAP_FIELD2(_field) (_field) = SWAP2(_field)
65 #define SWAP_FIELD4(_field) (_field) = SWAP4(_field)
66 #define SWAP_FIELD8(_field) (_field) = SWAP8(_field)
69 * Some information we pass around to help verify values.
72 const DexHeader* pHeader;
74 const u1* fileEnd; // points to fileStart + fileLen
76 DexDataMap* pDataMap; // set after map verification
77 const DexFile* pDexFile; // set after intraitem verification
80 * bitmap of type_id indices that have been used to define classes;
81 * initialized immediately before class_def cross-verification, and
82 * freed immediately after it
84 u4* pDefinedClassBits;
86 const void* previousItem; // set during section iteration
90 * Return the file offset of the given pointer.
92 static inline u4 fileOffset(const CheckState* state, const void* ptr) {
93 return ((const u1*) ptr) - state->fileStart;
97 * Return a pointer for the given file offset.
99 static inline void* filePointer(const CheckState* state, u4 offset) {
100 return (void*) (state->fileStart + offset);
104 * Verify that a pointer range, start inclusive to end exclusive, only
105 * covers bytes in the file and doesn't point beyond the end of the
106 * file. That is, the start must indicate a valid byte or may point at
107 * the byte just past the end of the file (but no further), and the
108 * end must be no less than the start and must also not point beyond
109 * the byte just past the end of the file.
111 static inline bool checkPtrRange(const CheckState* state,
112 const void* start, const void* end, const char* label) {
113 const void* fileStart = state->fileStart;
114 const void* fileEnd = state->fileEnd;
115 if ((start < fileStart) || (start > fileEnd)
116 || (end < start) || (end > fileEnd)) {
117 ALOGW("Bad offset range for %s: %#x..%#x", label,
118 fileOffset(state, start), fileOffset(state, end));
125 * Verify that a range of offsets, start inclusive to end exclusive,
126 * are all valid. That is, the start must indicate a valid byte or may
127 * point at the byte just past the end of the file (but no further),
128 * and the end must be no less than the start and must also not point
129 * beyond the byte just past the end of the file.
131 * Assumes "const CheckState* state".
133 #define CHECK_OFFSET_RANGE(_start, _end) { \
134 const u1* _startPtr = (const u1*) filePointer(state, (_start)); \
135 const u1* _endPtr = (const u1*) filePointer(state, (_end)); \
136 if (!checkPtrRange(state, _startPtr, _endPtr, \
137 #_start ".." #_end)) { \
143 * Verify that a pointer range, start inclusive to end exclusive, only
144 * covers bytes in the file and doesn't point beyond the end of the
145 * file. That is, the start must indicate a valid byte or may point at
146 * the byte just past the end of the file (but no further), and the
147 * end must be no less than the start and must also not point beyond
148 * the byte just past the end of the file.
150 * Assumes "const CheckState* state".
152 #define CHECK_PTR_RANGE(_start, _end) { \
153 if (!checkPtrRange(state, (_start), (_end), #_start ".." #_end)) { \
159 * Make sure a list of items fits entirely within the file.
161 * Assumes "const CheckState* state" and "typeof(_count) == typeof(_elemSize)"
162 * If the type sizes or signs are mismatched, this will return 0.
164 #define CHECK_LIST_SIZE(_ptr, _count, _elemSize) { \
165 const u1* _start = (const u1*) (_ptr); \
166 const u1* _end = _start + ((_count) * (_elemSize)); \
167 if (!safe_mul(NULL, (_count), (_elemSize)) || \
168 !checkPtrRange(state, _start, _end, #_ptr)) { \
174 * Swap a field that is known to hold an absolute DEX file offset. Note:
175 * This does not check to see that the swapped offset points within the
176 * mapped file, since that should be handled (with even more rigor) by
177 * the cross-verification phase.
179 * Assumes "const CheckState* state".
181 #define SWAP_OFFSET4(_field) { \
182 SWAP_FIELD4((_field)); \
186 * Verify that an index falls in a valid range.
188 #define CHECK_INDEX(_field, _limit) { \
189 if ((_field) >= (_limit)) { \
190 ALOGW("Bad index: %s(%u) > %s(%u)", \
191 #_field, (u4)(_field), #_limit, (u4)(_limit)); \
197 * Swap an index, and verify that it falls in a valid range.
199 #define SWAP_INDEX2(_field, _limit) { \
200 SWAP_FIELD2((_field)); \
201 CHECK_INDEX((_field), (_limit)); \
205 * Verify that an index falls in a valid range or is kDexNoIndex.
207 #define CHECK_INDEX_OR_NOINDEX(_field, _limit) { \
208 if ((_field) != kDexNoIndex && (_field) >= (_limit)) { \
209 ALOGW("Bad index: %s(%u) > %s(%u)", \
210 #_field, (u4)(_field), #_limit, (u4)(_limit)); \
216 * Swap an index, and verify that it falls in a valid range.
218 #define SWAP_INDEX4(_field, _limit) { \
219 SWAP_FIELD4((_field)); \
220 CHECK_INDEX((_field), (_limit)); \
224 * Swap an index, and verify that it falls in a valid range or is
227 #define SWAP_INDEX4_OR_NOINDEX(_field, _limit) { \
228 SWAP_FIELD4((_field)); \
229 CHECK_INDEX_OR_NOINDEX((_field), (_limit)); \
232 /* Verify the definer of a given field_idx. */
233 static bool verifyFieldDefiner(const CheckState* state, u4 definingClass,
235 const DexFieldId* field = dexGetFieldId(state->pDexFile, fieldIdx);
236 return field->classIdx == definingClass;
239 /* Verify the definer of a given method_idx. */
240 static bool verifyMethodDefiner(const CheckState* state, u4 definingClass,
242 const DexMethodId* meth = dexGetMethodId(state->pDexFile, methodIdx);
243 return meth->classIdx == definingClass;
247 * Calculate the required size (in elements) of the array pointed at by
250 static size_t calcDefinedClassBitsSize(const CheckState* state)
252 // Divide typeIdsSize by 32 (0x20), rounding up.
253 return (state->pHeader->typeIdsSize + 0x1f) >> 5;
257 * Set the given bit in pDefinedClassBits, returning its former value.
259 static bool setDefinedClassBit(const CheckState* state, u4 typeIdx) {
260 u4 arrayIdx = typeIdx >> 5;
261 u4 bit = 1 << (typeIdx & 0x1f);
262 u4* element = &state->pDefinedClassBits[arrayIdx];
263 bool result = (*element & bit) != 0;
271 * Swap the header_item.
273 static bool swapDexHeader(const CheckState* state, DexHeader* pHeader)
275 CHECK_PTR_RANGE(pHeader, pHeader + 1);
278 SWAP_FIELD4(pHeader->checksum);
280 SWAP_FIELD4(pHeader->fileSize);
281 SWAP_FIELD4(pHeader->headerSize);
282 SWAP_FIELD4(pHeader->endianTag);
283 SWAP_FIELD4(pHeader->linkSize);
284 SWAP_OFFSET4(pHeader->linkOff);
285 SWAP_OFFSET4(pHeader->mapOff);
286 SWAP_FIELD4(pHeader->stringIdsSize);
287 SWAP_OFFSET4(pHeader->stringIdsOff);
288 SWAP_FIELD4(pHeader->typeIdsSize);
289 SWAP_OFFSET4(pHeader->typeIdsOff);
290 SWAP_FIELD4(pHeader->fieldIdsSize);
291 SWAP_OFFSET4(pHeader->fieldIdsOff);
292 SWAP_FIELD4(pHeader->methodIdsSize);
293 SWAP_OFFSET4(pHeader->methodIdsOff);
294 SWAP_FIELD4(pHeader->protoIdsSize);
295 SWAP_OFFSET4(pHeader->protoIdsOff);
296 SWAP_FIELD4(pHeader->classDefsSize);
297 SWAP_OFFSET4(pHeader->classDefsOff);
298 SWAP_FIELD4(pHeader->dataSize);
299 SWAP_OFFSET4(pHeader->dataOff);
301 if (pHeader->endianTag != kDexEndianConstant) {
302 ALOGE("Unexpected endian_tag: %#x", pHeader->endianTag);
306 // Assign variables so the diagnostic is prettier. (Hooray for macros.)
307 u4 linkOff = pHeader->linkOff;
308 u4 linkEnd = linkOff + pHeader->linkSize;
309 u4 dataOff = pHeader->dataOff;
310 u4 dataEnd = dataOff + pHeader->dataSize;
311 CHECK_OFFSET_RANGE(linkOff, linkEnd);
312 CHECK_OFFSET_RANGE(dataOff, dataEnd);
315 * Note: The offsets and ranges of the other header items end up getting
316 * checked during the first iteration over the map.
322 /* Check the header section for sanity. */
323 static bool checkHeaderSection(const CheckState* state, u4 sectionOffset,
324 u4 sectionCount, u4* endOffset) {
325 if (sectionCount != 1) {
326 ALOGE("Multiple header items");
330 if (sectionOffset != 0) {
331 ALOGE("Header at %#x; not at start of file", sectionOffset);
335 const DexHeader* pHeader = (const DexHeader*) filePointer(state, 0);
336 *endOffset = pHeader->headerSize;
341 * Helper for swapMap(), which turns a map type constant into a small
342 * one-bit-on integer, suitable for use in an int-sized bit set.
344 static u4 mapTypeToBitMask(int mapType) {
346 case kDexTypeHeaderItem: return 1 << 0;
347 case kDexTypeStringIdItem: return 1 << 1;
348 case kDexTypeTypeIdItem: return 1 << 2;
349 case kDexTypeProtoIdItem: return 1 << 3;
350 case kDexTypeFieldIdItem: return 1 << 4;
351 case kDexTypeMethodIdItem: return 1 << 5;
352 case kDexTypeClassDefItem: return 1 << 6;
353 case kDexTypeMapList: return 1 << 7;
354 case kDexTypeTypeList: return 1 << 8;
355 case kDexTypeAnnotationSetRefList: return 1 << 9;
356 case kDexTypeAnnotationSetItem: return 1 << 10;
357 case kDexTypeClassDataItem: return 1 << 11;
358 case kDexTypeCodeItem: return 1 << 12;
359 case kDexTypeStringDataItem: return 1 << 13;
360 case kDexTypeDebugInfoItem: return 1 << 14;
361 case kDexTypeAnnotationItem: return 1 << 15;
362 case kDexTypeEncodedArrayItem: return 1 << 16;
363 case kDexTypeAnnotationsDirectoryItem: return 1 << 17;
365 ALOGE("Unknown map item type %04x", mapType);
372 * Helper for swapMap(), which indicates if an item type should appear
373 * in the data section.
375 static bool isDataSectionType(int mapType) {
377 case kDexTypeHeaderItem:
378 case kDexTypeStringIdItem:
379 case kDexTypeTypeIdItem:
380 case kDexTypeProtoIdItem:
381 case kDexTypeFieldIdItem:
382 case kDexTypeMethodIdItem:
383 case kDexTypeClassDefItem: {
392 * Swap the map_list and verify what we can about it. Also, if verification
393 * passes, allocate the state's DexDataMap.
395 static bool swapMap(CheckState* state, DexMapList* pMap)
397 DexMapItem* item = pMap->list;
399 u4 dataItemCount = 0; // Total count of items in the data section.
400 u4 dataItemsLeft = state->pHeader->dataSize; // See use below.
401 u4 usedBits = 0; // Bit set: one bit per section
405 SWAP_FIELD4(pMap->size);
408 CHECK_LIST_SIZE(item, count, sizeof(DexMapItem));
411 SWAP_FIELD2(item->type);
412 SWAP_FIELD2(item->unused);
413 SWAP_FIELD4(item->size);
414 SWAP_OFFSET4(item->offset);
418 } else if (lastOffset >= item->offset) {
419 ALOGE("Out-of-order map item: %#x then %#x",
420 lastOffset, item->offset);
424 if (item->offset >= state->pHeader->fileSize) {
425 ALOGE("Map item after end of file: %x, size %#x",
426 item->offset, state->pHeader->fileSize);
430 if (isDataSectionType(item->type)) {
431 u4 icount = item->size;
434 * This sanity check on the data section items ensures that
435 * there are no more items than the number of bytes in
438 if (icount > dataItemsLeft) {
439 ALOGE("Unrealistically many items in the data section: "
440 "at least %d", dataItemCount + icount);
444 dataItemsLeft -= icount;
445 dataItemCount += icount;
448 u4 bit = mapTypeToBitMask(item->type);
454 if ((usedBits & bit) != 0) {
455 ALOGE("Duplicate map section of type %#x", item->type);
460 lastOffset = item->offset;
464 if ((usedBits & mapTypeToBitMask(kDexTypeHeaderItem)) == 0) {
465 ALOGE("Map is missing header entry");
469 if ((usedBits & mapTypeToBitMask(kDexTypeMapList)) == 0) {
470 ALOGE("Map is missing map_list entry");
474 if (((usedBits & mapTypeToBitMask(kDexTypeStringIdItem)) == 0)
475 && ((state->pHeader->stringIdsOff != 0)
476 || (state->pHeader->stringIdsSize != 0))) {
477 ALOGE("Map is missing string_ids entry");
481 if (((usedBits & mapTypeToBitMask(kDexTypeTypeIdItem)) == 0)
482 && ((state->pHeader->typeIdsOff != 0)
483 || (state->pHeader->typeIdsSize != 0))) {
484 ALOGE("Map is missing type_ids entry");
488 if (((usedBits & mapTypeToBitMask(kDexTypeProtoIdItem)) == 0)
489 && ((state->pHeader->protoIdsOff != 0)
490 || (state->pHeader->protoIdsSize != 0))) {
491 ALOGE("Map is missing proto_ids entry");
495 if (((usedBits & mapTypeToBitMask(kDexTypeFieldIdItem)) == 0)
496 && ((state->pHeader->fieldIdsOff != 0)
497 || (state->pHeader->fieldIdsSize != 0))) {
498 ALOGE("Map is missing field_ids entry");
502 if (((usedBits & mapTypeToBitMask(kDexTypeMethodIdItem)) == 0)
503 && ((state->pHeader->methodIdsOff != 0)
504 || (state->pHeader->methodIdsSize != 0))) {
505 ALOGE("Map is missing method_ids entry");
509 if (((usedBits & mapTypeToBitMask(kDexTypeClassDefItem)) == 0)
510 && ((state->pHeader->classDefsOff != 0)
511 || (state->pHeader->classDefsSize != 0))) {
512 ALOGE("Map is missing class_defs entry");
516 state->pDataMap = dexDataMapAlloc(dataItemCount);
517 if (state->pDataMap == NULL) {
518 ALOGE("Unable to allocate data map (size %#x)", dataItemCount);
525 /* Check the map section for sanity. */
526 static bool checkMapSection(const CheckState* state, u4 sectionOffset,
527 u4 sectionCount, u4* endOffset) {
528 if (sectionCount != 1) {
529 ALOGE("Multiple map list items");
533 if (sectionOffset != state->pHeader->mapOff) {
534 ALOGE("Map not at header-defined offset: %#x, expected %#x",
535 sectionOffset, state->pHeader->mapOff);
539 const DexMapList* pMap = (const DexMapList*) filePointer(state, sectionOffset);
542 sectionOffset + sizeof(u4) + (pMap->size * sizeof(DexMapItem));
546 /* Perform byte-swapping and intra-item verification on string_id_item. */
547 static void* swapStringIdItem(const CheckState* state, void* ptr) {
548 DexStringId* item = (DexStringId*) ptr;
550 CHECK_PTR_RANGE(item, item + 1);
551 SWAP_OFFSET4(item->stringDataOff);
556 /* Perform cross-item verification of string_id_item. */
557 static void* crossVerifyStringIdItem(const CheckState* state, void* ptr) {
558 const DexStringId* item = (const DexStringId*) ptr;
560 if (!dexDataMapVerify(state->pDataMap,
561 item->stringDataOff, kDexTypeStringDataItem)) {
565 const DexStringId* item0 = (const DexStringId*) state->previousItem;
568 const char* s0 = dexGetStringData(state->pDexFile, item0);
569 const char* s1 = dexGetStringData(state->pDexFile, item);
570 if (dexUtf8Cmp(s0, s1) >= 0) {
571 ALOGE("Out-of-order string_ids: '%s' then '%s'", s0, s1);
576 return (void*) (item + 1);
579 /* Perform byte-swapping and intra-item verification on type_id_item. */
580 static void* swapTypeIdItem(const CheckState* state, void* ptr) {
581 DexTypeId* item = (DexTypeId*) ptr;
583 CHECK_PTR_RANGE(item, item + 1);
584 SWAP_INDEX4(item->descriptorIdx, state->pHeader->stringIdsSize);
589 /* Perform cross-item verification of type_id_item. */
590 static void* crossVerifyTypeIdItem(const CheckState* state, void* ptr) {
591 const DexTypeId* item = (const DexTypeId*) ptr;
592 const char* descriptor =
593 dexStringById(state->pDexFile, item->descriptorIdx);
595 if (!dexIsValidTypeDescriptor(descriptor)) {
596 ALOGE("Invalid type descriptor: '%s'", descriptor);
600 const DexTypeId* item0 = (const DexTypeId*) state->previousItem;
602 // Check ordering. This relies on string_ids being in order.
603 if (item0->descriptorIdx >= item->descriptorIdx) {
604 ALOGE("Out-of-order type_ids: %#x then %#x",
605 item0->descriptorIdx, item->descriptorIdx);
610 return (void*) (item + 1);
613 /* Perform byte-swapping and intra-item verification on proto_id_item. */
614 static void* swapProtoIdItem(const CheckState* state, void* ptr) {
615 DexProtoId* item = (DexProtoId*) ptr;
617 CHECK_PTR_RANGE(item, item + 1);
618 SWAP_INDEX4(item->shortyIdx, state->pHeader->stringIdsSize);
619 SWAP_INDEX4(item->returnTypeIdx, state->pHeader->typeIdsSize);
620 SWAP_OFFSET4(item->parametersOff);
625 /* Helper for crossVerifyProtoIdItem(), which checks a shorty character
626 * to see if it is compatible with a type descriptor. Returns true if
627 * so, false if not. */
628 static bool shortyDescMatch(char shorty, const char* descriptor, bool
633 ALOGE("Invalid use of void");
646 if ((descriptor[0] != shorty) || (descriptor[1] != '\0')) {
647 ALOGE("Shorty vs. primitive type mismatch: '%c', '%s'",
654 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
655 ALOGE("Shorty vs. type mismatch: '%c', '%s'",
662 ALOGE("Bogus shorty: '%c'", shorty);
670 /* Perform cross-item verification of proto_id_item. */
671 static void* crossVerifyProtoIdItem(const CheckState* state, void* ptr) {
672 const DexProtoId* item = (const DexProtoId*) ptr;
674 dexStringById(state->pDexFile, item->shortyIdx);
676 if (!dexDataMapVerify0Ok(state->pDataMap,
677 item->parametersOff, kDexTypeTypeList)) {
681 if (!shortyDescMatch(*shorty,
682 dexStringByTypeIdx(state->pDexFile, item->returnTypeIdx),
687 u4 protoIdx = item - state->pDexFile->pProtoIds;
688 DexProto proto = { state->pDexFile, protoIdx };
689 DexParameterIterator iterator;
691 dexParameterIteratorInit(&iterator, &proto);
692 shorty++; // Skip the return type.
695 const char *desc = dexParameterIteratorNextDescriptor(&iterator);
701 if (*shorty == '\0') {
702 ALOGE("Shorty is too short");
706 if (!shortyDescMatch(*shorty, desc, false)) {
713 if (*shorty != '\0') {
714 ALOGE("Shorty is too long");
718 const DexProtoId* item0 = (const DexProtoId*) state->previousItem;
720 // Check ordering. This relies on type_ids being in order.
721 if (item0->returnTypeIdx > item->returnTypeIdx) {
722 ALOGE("Out-of-order proto_id return types");
724 } else if (item0->returnTypeIdx == item->returnTypeIdx) {
725 bool badOrder = false;
726 DexProto proto0 = { state->pDexFile, protoIdx - 1 };
727 DexParameterIterator iterator0;
729 dexParameterIteratorInit(&iterator, &proto);
730 dexParameterIteratorInit(&iterator0, &proto0);
733 u4 idx0 = dexParameterIteratorNextIndex(&iterator0);
734 u4 idx1 = dexParameterIteratorNextIndex(&iterator);
736 if (idx1 == kDexNoIndex) {
741 if (idx0 == kDexNoIndex) {
747 } else if (idx0 > idx1) {
754 ALOGE("Out-of-order proto_id arguments");
760 return (void*) (item + 1);
763 /* Perform byte-swapping and intra-item verification on field_id_item. */
764 static void* swapFieldIdItem(const CheckState* state, void* ptr) {
765 DexFieldId* item = (DexFieldId*) ptr;
767 CHECK_PTR_RANGE(item, item + 1);
768 SWAP_INDEX2(item->classIdx, state->pHeader->typeIdsSize);
769 SWAP_INDEX2(item->typeIdx, state->pHeader->typeIdsSize);
770 SWAP_INDEX4(item->nameIdx, state->pHeader->stringIdsSize);
775 /* Perform cross-item verification of field_id_item. */
776 static void* crossVerifyFieldIdItem(const CheckState* state, void* ptr) {
777 const DexFieldId* item = (const DexFieldId*) ptr;
780 s = dexStringByTypeIdx(state->pDexFile, item->classIdx);
781 if (!dexIsClassDescriptor(s)) {
782 ALOGE("Invalid descriptor for class_idx: '%s'", s);
786 s = dexStringByTypeIdx(state->pDexFile, item->typeIdx);
787 if (!dexIsFieldDescriptor(s)) {
788 ALOGE("Invalid descriptor for type_idx: '%s'", s);
792 s = dexStringById(state->pDexFile, item->nameIdx);
793 if (!dexIsValidMemberName(s)) {
794 ALOGE("Invalid name: '%s'", s);
798 const DexFieldId* item0 = (const DexFieldId*) state->previousItem;
800 // Check ordering. This relies on the other sections being in order.
804 if (item0->classIdx > item->classIdx) {
807 } else if (item0->classIdx < item->classIdx) {
812 if (item0->nameIdx > item->nameIdx) {
815 } else if (item0->nameIdx < item->nameIdx) {
821 if (item0->typeIdx >= item->typeIdx) {
827 ALOGE("Out-of-order field_ids");
832 return (void*) (item + 1);
835 /* Perform byte-swapping and intra-item verification on method_id_item. */
836 static void* swapMethodIdItem(const CheckState* state, void* ptr) {
837 DexMethodId* item = (DexMethodId*) ptr;
839 CHECK_PTR_RANGE(item, item + 1);
840 SWAP_INDEX2(item->classIdx, state->pHeader->typeIdsSize);
841 SWAP_INDEX2(item->protoIdx, state->pHeader->protoIdsSize);
842 SWAP_INDEX4(item->nameIdx, state->pHeader->stringIdsSize);
847 /* Perform cross-item verification of method_id_item. */
848 static void* crossVerifyMethodIdItem(const CheckState* state, void* ptr) {
849 const DexMethodId* item = (const DexMethodId*) ptr;
852 s = dexStringByTypeIdx(state->pDexFile, item->classIdx);
853 if (!dexIsReferenceDescriptor(s)) {
854 ALOGE("Invalid descriptor for class_idx: '%s'", s);
858 s = dexStringById(state->pDexFile, item->nameIdx);
859 if (!dexIsValidMemberName(s)) {
860 ALOGE("Invalid name: '%s'", s);
864 const DexMethodId* item0 = (const DexMethodId*) state->previousItem;
866 // Check ordering. This relies on the other sections being in order.
870 if (item0->classIdx > item->classIdx) {
873 } else if (item0->classIdx < item->classIdx) {
878 if (item0->nameIdx > item->nameIdx) {
881 } else if (item0->nameIdx < item->nameIdx) {
887 if (item0->protoIdx >= item->protoIdx) {
893 ALOGE("Out-of-order method_ids");
898 return (void*) (item + 1);
901 /* Perform byte-swapping and intra-item verification on class_def_item. */
902 static void* swapClassDefItem(const CheckState* state, void* ptr) {
903 DexClassDef* item = (DexClassDef*) ptr;
905 CHECK_PTR_RANGE(item, item + 1);
906 SWAP_INDEX4(item->classIdx, state->pHeader->typeIdsSize);
907 SWAP_FIELD4(item->accessFlags);
908 SWAP_INDEX4_OR_NOINDEX(item->superclassIdx, state->pHeader->typeIdsSize);
909 SWAP_OFFSET4(item->interfacesOff);
910 SWAP_INDEX4_OR_NOINDEX(item->sourceFileIdx, state->pHeader->stringIdsSize);
911 SWAP_OFFSET4(item->annotationsOff);
912 SWAP_OFFSET4(item->classDataOff);
918 static u4 findFirstClassDataDefiner(const CheckState* state,
919 DexClassData* classData);
920 static u4 findFirstAnnotationsDirectoryDefiner(const CheckState* state,
921 const DexAnnotationsDirectoryItem* dir);
923 /* Helper for crossVerifyClassDefItem(), which checks a class_data_item to
924 * make sure all its references are to a given class. */
925 static bool verifyClassDataIsForDef(const CheckState* state, u4 offset,
931 const u1* data = (const u1*) filePointer(state, offset);
932 DexClassData* classData = dexReadAndVerifyClassData(&data, NULL);
934 if (classData == NULL) {
935 // Shouldn't happen, but bail here just in case.
940 * The class_data_item verification ensures that
941 * it consistently refers to the same definer, so all we need to
942 * do is check the first one.
944 u4 dataDefiner = findFirstClassDataDefiner(state, classData);
945 bool result = (dataDefiner == definerIdx) || (dataDefiner == kDexNoIndex);
951 /* Helper for crossVerifyClassDefItem(), which checks an
952 * annotations_directory_item to make sure all its references are to a
954 static bool verifyAnnotationsDirectoryIsForDef(const CheckState* state,
955 u4 offset, u4 definerIdx) {
960 const DexAnnotationsDirectoryItem* dir =
961 (const DexAnnotationsDirectoryItem*) filePointer(state, offset);
962 u4 annoDefiner = findFirstAnnotationsDirectoryDefiner(state, dir);
964 return (annoDefiner == definerIdx) || (annoDefiner == kDexNoIndex);
967 /* Perform cross-item verification of class_def_item. */
968 static void* crossVerifyClassDefItem(const CheckState* state, void* ptr) {
969 const DexClassDef* item = (const DexClassDef*) ptr;
970 u4 classIdx = item->classIdx;
971 const char* descriptor = dexStringByTypeIdx(state->pDexFile, classIdx);
973 if (!dexIsClassDescriptor(descriptor)) {
974 ALOGE("Invalid class: '%s'", descriptor);
978 if (setDefinedClassBit(state, classIdx)) {
979 ALOGE("Duplicate class definition: '%s'", descriptor);
984 dexDataMapVerify0Ok(state->pDataMap,
985 item->interfacesOff, kDexTypeTypeList)
986 && dexDataMapVerify0Ok(state->pDataMap,
987 item->annotationsOff, kDexTypeAnnotationsDirectoryItem)
988 && dexDataMapVerify0Ok(state->pDataMap,
989 item->classDataOff, kDexTypeClassDataItem)
990 && dexDataMapVerify0Ok(state->pDataMap,
991 item->staticValuesOff, kDexTypeEncodedArrayItem);
997 if (item->superclassIdx != kDexNoIndex) {
998 descriptor = dexStringByTypeIdx(state->pDexFile, item->superclassIdx);
999 if (!dexIsClassDescriptor(descriptor)) {
1000 ALOGE("Invalid superclass: '%s'", descriptor);
1005 const DexTypeList* interfaces =
1006 dexGetInterfacesList(state->pDexFile, item);
1007 if (interfaces != NULL) {
1008 u4 size = interfaces->size;
1012 * Ensure that all interfaces refer to classes (not arrays or
1015 for (i = 0; i < size; i++) {
1016 descriptor = dexStringByTypeIdx(state->pDexFile,
1017 dexTypeListGetIdx(interfaces, i));
1018 if (!dexIsClassDescriptor(descriptor)) {
1019 ALOGE("Invalid interface: '%s'", descriptor);
1025 * Ensure that there are no duplicates. This is an O(N^2) test,
1026 * but in practice the number of interfaces implemented by any
1027 * given class is low. I will buy a milkshake for the
1028 * first person to show me a realistic case for which this test
1029 * would be unacceptably slow.
1031 for (i = 1; i < size; i++) {
1032 u4 idx1 = dexTypeListGetIdx(interfaces, i);
1034 for (j = 0; j < i; j++) {
1035 u4 idx2 = dexTypeListGetIdx(interfaces, j);
1037 ALOGE("Duplicate interface: '%s'",
1038 dexStringByTypeIdx(state->pDexFile, idx1));
1045 if (!verifyClassDataIsForDef(state, item->classDataOff, item->classIdx)) {
1046 ALOGE("Invalid class_data_item");
1050 if (!verifyAnnotationsDirectoryIsForDef(state, item->annotationsOff,
1052 ALOGE("Invalid annotations_directory_item");
1056 return (void*) (item + 1);
1059 /* Helper for swapAnnotationsDirectoryItem(), which performs
1060 * byte-swapping and intra-item verification on an
1061 * annotation_directory_item's field elements. */
1062 static u1* swapFieldAnnotations(const CheckState* state, u4 count, u1* addr) {
1063 DexFieldAnnotationsItem* item = (DexFieldAnnotationsItem*) addr;
1067 CHECK_LIST_SIZE(item, count, sizeof(DexFieldAnnotationsItem));
1070 SWAP_INDEX4(item->fieldIdx, state->pHeader->fieldIdsSize);
1071 SWAP_OFFSET4(item->annotationsOff);
1075 } else if (lastIdx >= item->fieldIdx) {
1076 ALOGE("Out-of-order field_idx: %#x then %#x", lastIdx,
1081 lastIdx = item->fieldIdx;
1088 /* Helper for swapAnnotationsDirectoryItem(), which performs
1089 * byte-swapping and intra-item verification on an
1090 * annotation_directory_item's method elements. */
1091 static u1* swapMethodAnnotations(const CheckState* state, u4 count, u1* addr) {
1092 DexMethodAnnotationsItem* item = (DexMethodAnnotationsItem*) addr;
1096 CHECK_LIST_SIZE(item, count, sizeof(DexMethodAnnotationsItem));
1099 SWAP_INDEX4(item->methodIdx, state->pHeader->methodIdsSize);
1100 SWAP_OFFSET4(item->annotationsOff);
1104 } else if (lastIdx >= item->methodIdx) {
1105 ALOGE("Out-of-order method_idx: %#x then %#x", lastIdx,
1110 lastIdx = item->methodIdx;
1117 /* Helper for swapAnnotationsDirectoryItem(), which performs
1118 * byte-swapping and intra-item verification on an
1119 * annotation_directory_item's parameter elements. */
1120 static u1* swapParameterAnnotations(const CheckState* state, u4 count,
1122 DexParameterAnnotationsItem* item = (DexParameterAnnotationsItem*) addr;
1126 CHECK_LIST_SIZE(item, count, sizeof(DexParameterAnnotationsItem));
1129 SWAP_INDEX4(item->methodIdx, state->pHeader->methodIdsSize);
1130 SWAP_OFFSET4(item->annotationsOff);
1134 } else if (lastIdx >= item->methodIdx) {
1135 ALOGE("Out-of-order method_idx: %#x then %#x", lastIdx,
1140 lastIdx = item->methodIdx;
1147 /* Perform byte-swapping and intra-item verification on
1148 * annotations_directory_item. */
1149 static void* swapAnnotationsDirectoryItem(const CheckState* state, void* ptr) {
1150 DexAnnotationsDirectoryItem* item = (DexAnnotationsDirectoryItem*) ptr;
1152 CHECK_PTR_RANGE(item, item + 1);
1153 SWAP_OFFSET4(item->classAnnotationsOff);
1154 SWAP_FIELD4(item->fieldsSize);
1155 SWAP_FIELD4(item->methodsSize);
1156 SWAP_FIELD4(item->parametersSize);
1158 u1* addr = (u1*) (item + 1);
1160 if (item->fieldsSize != 0) {
1161 addr = swapFieldAnnotations(state, item->fieldsSize, addr);
1167 if (item->methodsSize != 0) {
1168 addr = swapMethodAnnotations(state, item->methodsSize, addr);
1174 if (item->parametersSize != 0) {
1175 addr = swapParameterAnnotations(state, item->parametersSize, addr);
1184 /* Helper for crossVerifyAnnotationsDirectoryItem(), which checks the
1185 * field elements. */
1186 static const u1* crossVerifyFieldAnnotations(const CheckState* state, u4 count,
1187 const u1* addr, u4 definingClass) {
1188 const DexFieldAnnotationsItem* item = (DexFieldAnnotationsItem*) addr;
1191 if (!verifyFieldDefiner(state, definingClass, item->fieldIdx)) {
1194 if (!dexDataMapVerify(state->pDataMap, item->annotationsOff,
1195 kDexTypeAnnotationSetItem)) {
1201 return (const u1*) item;
1204 /* Helper for crossVerifyAnnotationsDirectoryItem(), which checks the
1205 * method elements. */
1206 static const u1* crossVerifyMethodAnnotations(const CheckState* state,
1207 u4 count, const u1* addr, u4 definingClass) {
1208 const DexMethodAnnotationsItem* item = (DexMethodAnnotationsItem*) addr;
1211 if (!verifyMethodDefiner(state, definingClass, item->methodIdx)) {
1214 if (!dexDataMapVerify(state->pDataMap, item->annotationsOff,
1215 kDexTypeAnnotationSetItem)) {
1221 return (const u1*) item;
1224 /* Helper for crossVerifyAnnotationsDirectoryItem(), which checks the
1225 * parameter elements. */
1226 static const u1* crossVerifyParameterAnnotations(const CheckState* state,
1227 u4 count, const u1* addr, u4 definingClass) {
1228 const DexParameterAnnotationsItem* item =
1229 (DexParameterAnnotationsItem*) addr;
1232 if (!verifyMethodDefiner(state, definingClass, item->methodIdx)) {
1235 if (!dexDataMapVerify(state->pDataMap, item->annotationsOff,
1236 kDexTypeAnnotationSetRefList)) {
1242 return (const u1*) item;
1245 /* Helper for crossVerifyClassDefItem() and
1246 * crossVerifyAnnotationsDirectoryItem(), which finds the type_idx of
1247 * the definer of the first item in the data. */
1248 static u4 findFirstAnnotationsDirectoryDefiner(const CheckState* state,
1249 const DexAnnotationsDirectoryItem* dir) {
1250 if (dir->fieldsSize != 0) {
1251 const DexFieldAnnotationsItem* fields =
1252 dexGetFieldAnnotations(state->pDexFile, dir);
1253 const DexFieldId* field =
1254 dexGetFieldId(state->pDexFile, fields[0].fieldIdx);
1255 return field->classIdx;
1258 if (dir->methodsSize != 0) {
1259 const DexMethodAnnotationsItem* methods =
1260 dexGetMethodAnnotations(state->pDexFile, dir);
1261 const DexMethodId* method =
1262 dexGetMethodId(state->pDexFile, methods[0].methodIdx);
1263 return method->classIdx;
1266 if (dir->parametersSize != 0) {
1267 const DexParameterAnnotationsItem* parameters =
1268 dexGetParameterAnnotations(state->pDexFile, dir);
1269 const DexMethodId* method =
1270 dexGetMethodId(state->pDexFile, parameters[0].methodIdx);
1271 return method->classIdx;
1277 /* Perform cross-item verification of annotations_directory_item. */
1278 static void* crossVerifyAnnotationsDirectoryItem(const CheckState* state,
1280 const DexAnnotationsDirectoryItem* item = (const DexAnnotationsDirectoryItem*) ptr;
1281 u4 definingClass = findFirstAnnotationsDirectoryDefiner(state, item);
1283 if (!dexDataMapVerify0Ok(state->pDataMap,
1284 item->classAnnotationsOff, kDexTypeAnnotationSetItem)) {
1288 const u1* addr = (const u1*) (item + 1);
1290 if (item->fieldsSize != 0) {
1291 addr = crossVerifyFieldAnnotations(state, item->fieldsSize, addr,
1298 if (item->methodsSize != 0) {
1299 addr = crossVerifyMethodAnnotations(state, item->methodsSize, addr,
1306 if (item->parametersSize != 0) {
1307 addr = crossVerifyParameterAnnotations(state, item->parametersSize,
1308 addr, definingClass);
1314 return (void*) addr;
1317 /* Perform byte-swapping and intra-item verification on type_list. */
1318 static void* swapTypeList(const CheckState* state, void* ptr)
1320 DexTypeList* pTypeList = (DexTypeList*) ptr;
1324 CHECK_PTR_RANGE(pTypeList, pTypeList + 1);
1325 SWAP_FIELD4(pTypeList->size);
1326 count = pTypeList->size;
1327 pType = pTypeList->list;
1328 CHECK_LIST_SIZE(pType, count, sizeof(DexTypeItem));
1331 SWAP_INDEX2(pType->typeIdx, state->pHeader->typeIdsSize);
1338 /* Perform byte-swapping and intra-item verification on
1339 * annotation_set_ref_list. */
1340 static void* swapAnnotationSetRefList(const CheckState* state, void* ptr) {
1341 DexAnnotationSetRefList* list = (DexAnnotationSetRefList*) ptr;
1342 DexAnnotationSetRefItem* item;
1345 CHECK_PTR_RANGE(list, list + 1);
1346 SWAP_FIELD4(list->size);
1349 CHECK_LIST_SIZE(item, count, sizeof(DexAnnotationSetRefItem));
1352 SWAP_OFFSET4(item->annotationsOff);
1359 /* Perform cross-item verification of annotation_set_ref_list. */
1360 static void* crossVerifyAnnotationSetRefList(const CheckState* state,
1362 const DexAnnotationSetRefList* list = (const DexAnnotationSetRefList*) ptr;
1363 const DexAnnotationSetRefItem* item = list->list;
1364 int count = list->size;
1367 if (!dexDataMapVerify0Ok(state->pDataMap,
1368 item->annotationsOff, kDexTypeAnnotationSetItem)) {
1374 return (void*) item;
1377 /* Perform byte-swapping and intra-item verification on
1378 * annotation_set_item. */
1379 static void* swapAnnotationSetItem(const CheckState* state, void* ptr) {
1380 DexAnnotationSetItem* set = (DexAnnotationSetItem*) ptr;
1384 CHECK_PTR_RANGE(set, set + 1);
1385 SWAP_FIELD4(set->size);
1387 item = set->entries;
1388 CHECK_LIST_SIZE(item, count, sizeof(u4));
1391 SWAP_OFFSET4(*item);
1398 /* Helper for crossVerifyAnnotationSetItem(), which extracts the type_idx
1399 * out of an annotation_item. */
1400 static u4 annotationItemTypeIdx(const DexAnnotationItem* item) {
1401 const u1* data = item->annotation;
1402 return readUnsignedLeb128(&data);
1405 /* Perform cross-item verification of annotation_set_item. */
1406 static void* crossVerifyAnnotationSetItem(const CheckState* state, void* ptr) {
1407 const DexAnnotationSetItem* set = (const DexAnnotationSetItem*) ptr;
1408 int count = set->size;
1413 for (i = 0; i < count; i++) {
1414 if (!dexDataMapVerify0Ok(state->pDataMap,
1415 dexGetAnnotationOff(set, i), kDexTypeAnnotationItem)) {
1419 const DexAnnotationItem* annotation =
1420 dexGetAnnotationItem(state->pDexFile, set, i);
1421 u4 idx = annotationItemTypeIdx(annotation);
1425 } else if (lastIdx >= idx) {
1426 ALOGE("Out-of-order entry types: %#x then %#x",
1434 return (void*) (set->entries + count);
1437 /* Helper for verifyClassDataItem(), which checks a list of fields. */
1438 static bool verifyFields(const CheckState* state, u4 size,
1439 DexField* fields, bool expectStatic) {
1442 for (i = 0; i < size; i++) {
1443 DexField* field = &fields[i];
1444 u4 accessFlags = field->accessFlags;
1445 bool isStatic = (accessFlags & ACC_STATIC) != 0;
1447 CHECK_INDEX(field->fieldIdx, state->pHeader->fieldIdsSize);
1449 if (isStatic != expectStatic) {
1450 ALOGE("Field in wrong list @ %d", i);
1454 if ((accessFlags & ~ACC_FIELD_MASK) != 0) {
1455 ALOGE("Bogus field access flags %x @ %d", accessFlags, i);
1463 /* Helper for verifyClassDataItem(), which checks a list of methods. */
1464 static bool verifyMethods(const CheckState* state, u4 size,
1465 DexMethod* methods, bool expectDirect) {
1468 for (i = 0; i < size; i++) {
1469 DexMethod* method = &methods[i];
1471 CHECK_INDEX(method->methodIdx, state->pHeader->methodIdsSize);
1473 u4 accessFlags = method->accessFlags;
1475 (accessFlags & (ACC_STATIC | ACC_PRIVATE | ACC_CONSTRUCTOR)) != 0;
1476 bool expectCode = (accessFlags & (ACC_NATIVE | ACC_ABSTRACT)) == 0;
1477 bool isSynchronized = (accessFlags & ACC_SYNCHRONIZED) != 0;
1478 bool allowSynchronized = (accessFlags & ACC_NATIVE) != 0;
1480 if (isDirect != expectDirect) {
1481 ALOGE("Method in wrong list @ %d", i);
1485 if (((accessFlags & ~ACC_METHOD_MASK) != 0)
1486 || (isSynchronized && !allowSynchronized)) {
1487 ALOGE("Bogus method access flags %x @ %d", accessFlags, i);
1492 if (method->codeOff == 0) {
1493 ALOGE("Unexpected zero code_off for access_flags %x",
1497 } else if (method->codeOff != 0) {
1498 ALOGE("Unexpected non-zero code_off %#x for access_flags %x",
1499 method->codeOff, accessFlags);
1507 /* Helper for verifyClassDataItem(), which does most of the work. */
1508 static bool verifyClassDataItem0(const CheckState* state,
1509 DexClassData* classData) {
1512 okay = verifyFields(state, classData->header.staticFieldsSize,
1513 classData->staticFields, true);
1516 ALOGE("Trouble with static fields");
1520 verifyFields(state, classData->header.instanceFieldsSize,
1521 classData->instanceFields, false);
1524 ALOGE("Trouble with instance fields");
1528 okay = verifyMethods(state, classData->header.directMethodsSize,
1529 classData->directMethods, true);
1532 ALOGE("Trouble with direct methods");
1536 okay = verifyMethods(state, classData->header.virtualMethodsSize,
1537 classData->virtualMethods, false);
1540 ALOGE("Trouble with virtual methods");
1547 /* Perform intra-item verification on class_data_item. */
1548 static void* intraVerifyClassDataItem(const CheckState* state, void* ptr) {
1549 const u1* data = (const u1*) ptr;
1550 DexClassData* classData = dexReadAndVerifyClassData(&data, state->fileEnd);
1552 if (classData == NULL) {
1553 ALOGE("Unable to parse class_data_item");
1557 bool okay = verifyClassDataItem0(state, classData);
1565 return (void*) data;
1568 /* Helper for crossVerifyClassDefItem() and
1569 * crossVerifyClassDataItem(), which finds the type_idx of the definer
1570 * of the first item in the data. */
1571 static u4 findFirstClassDataDefiner(const CheckState* state,
1572 DexClassData* classData) {
1573 if (classData->header.staticFieldsSize != 0) {
1574 u4 fieldIdx = classData->staticFields[0].fieldIdx;
1575 const DexFieldId* field = dexGetFieldId(state->pDexFile, fieldIdx);
1576 return field->classIdx;
1579 if (classData->header.instanceFieldsSize != 0) {
1580 u4 fieldIdx = classData->instanceFields[0].fieldIdx;
1581 const DexFieldId* field = dexGetFieldId(state->pDexFile, fieldIdx);
1582 return field->classIdx;
1585 if (classData->header.directMethodsSize != 0) {
1586 u4 methodIdx = classData->directMethods[0].methodIdx;
1587 const DexMethodId* meth = dexGetMethodId(state->pDexFile, methodIdx);
1588 return meth->classIdx;
1591 if (classData->header.virtualMethodsSize != 0) {
1592 u4 methodIdx = classData->virtualMethods[0].methodIdx;
1593 const DexMethodId* meth = dexGetMethodId(state->pDexFile, methodIdx);
1594 return meth->classIdx;
1600 /* Perform cross-item verification of class_data_item. */
1601 static void* crossVerifyClassDataItem(const CheckState* state, void* ptr) {
1602 const u1* data = (const u1*) ptr;
1603 DexClassData* classData = dexReadAndVerifyClassData(&data, state->fileEnd);
1604 u4 definingClass = findFirstClassDataDefiner(state, classData);
1608 for (i = classData->header.staticFieldsSize; okay && (i > 0); /*i*/) {
1610 const DexField* field = &classData->staticFields[i];
1611 okay = verifyFieldDefiner(state, definingClass, field->fieldIdx);
1614 for (i = classData->header.instanceFieldsSize; okay && (i > 0); /*i*/) {
1616 const DexField* field = &classData->instanceFields[i];
1617 okay = verifyFieldDefiner(state, definingClass, field->fieldIdx);
1620 for (i = classData->header.directMethodsSize; okay && (i > 0); /*i*/) {
1622 const DexMethod* meth = &classData->directMethods[i];
1623 okay = dexDataMapVerify0Ok(state->pDataMap, meth->codeOff,
1625 && verifyMethodDefiner(state, definingClass, meth->methodIdx);
1628 for (i = classData->header.virtualMethodsSize; okay && (i > 0); /*i*/) {
1630 const DexMethod* meth = &classData->virtualMethods[i];
1631 okay = dexDataMapVerify0Ok(state->pDataMap, meth->codeOff,
1633 && verifyMethodDefiner(state, definingClass, meth->methodIdx);
1642 return (void*) data;
1645 /* Helper for swapCodeItem(), which fills an array with all the valid
1646 * handlerOff values for catch handlers and also verifies the handler
1648 static u4 setHandlerOffsAndVerify(const CheckState* state,
1649 DexCode* code, u4 firstOffset, u4 handlersSize, u4* handlerOffs) {
1650 const u1* fileEnd = state->fileEnd;
1651 const u1* handlersBase = dexGetCatchHandlerData(code);
1652 u4 offset = firstOffset;
1656 for (i = 0; i < handlersSize; i++) {
1657 const u1* ptr = handlersBase + offset;
1658 int size = readAndVerifySignedLeb128(&ptr, fileEnd, &okay);
1662 ALOGE("Bogus size");
1666 if ((size < -65536) || (size > 65536)) {
1667 ALOGE("Invalid size: %d", size);
1678 handlerOffs[i] = offset;
1680 while (size-- > 0) {
1682 readAndVerifyUnsignedLeb128(&ptr, fileEnd, &okay);
1685 ALOGE("Bogus type_idx");
1689 CHECK_INDEX(typeIdx, state->pHeader->typeIdsSize);
1691 u4 addr = readAndVerifyUnsignedLeb128(&ptr, fileEnd, &okay);
1694 ALOGE("Bogus addr");
1698 if (addr >= code->insnsSize) {
1699 ALOGE("Invalid addr: %#x", addr);
1705 u4 addr = readAndVerifyUnsignedLeb128(&ptr, fileEnd, &okay);
1708 ALOGE("Bogus catch_all_addr");
1712 if (addr >= code->insnsSize) {
1713 ALOGE("Invalid catch_all_addr: %#x", addr);
1718 offset = ptr - handlersBase;
1724 /* Helper for swapCodeItem(), which does all the try-catch related
1725 * swapping and verification. */
1726 static void* swapTriesAndCatches(const CheckState* state, DexCode* code) {
1727 const u1* encodedHandlers = dexGetCatchHandlerData(code);
1728 const u1* encodedPtr = encodedHandlers;
1731 readAndVerifyUnsignedLeb128(&encodedPtr, state->fileEnd, &okay);
1734 ALOGE("Bogus handlers_size");
1738 if ((handlersSize == 0) || (handlersSize >= 65536)) {
1739 ALOGE("Invalid handlers_size: %d", handlersSize);
1743 u4 handlerOffs[handlersSize]; // list of valid handlerOff values
1744 u4 endOffset = setHandlerOffsAndVerify(state, code,
1745 encodedPtr - encodedHandlers,
1746 handlersSize, handlerOffs);
1748 if (endOffset == 0) {
1752 DexTry* tries = (DexTry*) dexGetTries(code);
1753 u4 count = code->triesSize;
1756 CHECK_LIST_SIZE(tries, count, sizeof(DexTry));
1761 SWAP_FIELD4(tries->startAddr);
1762 SWAP_FIELD2(tries->insnCount);
1763 SWAP_FIELD2(tries->handlerOff);
1765 if (tries->startAddr < lastEnd) {
1766 ALOGE("Out-of-order try");
1770 if (tries->startAddr >= code->insnsSize) {
1771 ALOGE("Invalid start_addr: %#x", tries->startAddr);
1775 for (i = 0; i < handlersSize; i++) {
1776 if (tries->handlerOff == handlerOffs[i]) {
1781 if (i == handlersSize) {
1782 ALOGE("Bogus handler offset: %#x", tries->handlerOff);
1786 lastEnd = tries->startAddr + tries->insnCount;
1788 if (lastEnd > code->insnsSize) {
1789 ALOGE("Invalid insn_count: %#x (end addr %#x)",
1790 tries->insnCount, lastEnd);
1797 return (u1*) encodedHandlers + endOffset;
1800 /* Perform byte-swapping and intra-item verification on code_item. */
1801 static void* swapCodeItem(const CheckState* state, void* ptr) {
1802 DexCode* item = (DexCode*) ptr;
1806 CHECK_PTR_RANGE(item, item + 1);
1807 SWAP_FIELD2(item->registersSize);
1808 SWAP_FIELD2(item->insSize);
1809 SWAP_FIELD2(item->outsSize);
1810 SWAP_FIELD2(item->triesSize);
1811 SWAP_OFFSET4(item->debugInfoOff);
1812 SWAP_FIELD4(item->insnsSize);
1814 if (item->insSize > item->registersSize) {
1815 ALOGE("insSize (%u) > registersSize (%u)", item->insSize,
1816 item->registersSize);
1820 if ((item->outsSize > 5) && (item->outsSize > item->registersSize)) {
1822 * It's okay for outsSize to be up to five, even if registersSize
1823 * is smaller, since the short forms of method invocation allow
1824 * repetition of a register multiple times within a single parameter
1825 * list. Longer parameter lists, though, need to be represented
1826 * in-order in the register file.
1828 ALOGE("outsSize (%u) > registersSize (%u)", item->outsSize,
1829 item->registersSize);
1833 count = item->insnsSize;
1834 insns = item->insns;
1835 CHECK_LIST_SIZE(insns, count, sizeof(u2));
1838 *insns = SWAP2(*insns);
1842 if (item->triesSize == 0) {
1845 if ((((u4) insns) & 3) != 0) {
1846 // Four-byte alignment for the tries. Verify the spacer is a 0.
1848 ALOGE("Non-zero padding: %#x", (u4) *insns);
1853 ptr = swapTriesAndCatches(state, item);
1859 /* Perform intra-item verification on string_data_item. */
1860 static void* intraVerifyStringDataItem(const CheckState* state, void* ptr) {
1861 const u1* fileEnd = state->fileEnd;
1862 const u1* data = (const u1*) ptr;
1864 u4 utf16Size = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
1868 ALOGE("Bogus utf16_size");
1872 for (i = 0; i < utf16Size; i++) {
1873 if (data >= fileEnd) {
1874 ALOGE("String data would go beyond end-of-file");
1878 u1 byte1 = *(data++);
1880 // Switch on the high four bits.
1881 switch (byte1 >> 4) {
1883 // Special case of bit pattern 0xxx.
1885 ALOGE("String shorter than indicated utf16_size %#x",
1898 // Bit pattern 0xxx. No need for any extra bytes or checks.
1907 * Bit pattern 10xx or 1111, which are illegal start bytes.
1908 * Note: 1111 is valid for normal UTF-8, but not the
1909 * modified UTF-8 used here.
1911 ALOGE("Illegal start byte %#x", byte1);
1915 // Bit pattern 1110, so there are two additional bytes.
1916 u1 byte2 = *(data++);
1917 if ((byte2 & 0xc0) != 0x80) {
1918 ALOGE("Illegal continuation byte %#x", byte2);
1921 u1 byte3 = *(data++);
1922 if ((byte3 & 0xc0) != 0x80) {
1923 ALOGE("Illegal continuation byte %#x", byte3);
1926 u2 value = ((byte1 & 0x0f) << 12) | ((byte2 & 0x3f) << 6)
1928 if (value < 0x800) {
1929 ALOGE("Illegal representation for value %x", value);
1936 // Bit pattern 110x, so there is one additional byte.
1937 u1 byte2 = *(data++);
1938 if ((byte2 & 0xc0) != 0x80) {
1939 ALOGE("Illegal continuation byte %#x", byte2);
1942 u2 value = ((byte1 & 0x1f) << 6) | (byte2 & 0x3f);
1943 if ((value != 0) && (value < 0x80)) {
1944 ALOGE("Illegal representation for value %x", value);
1952 if (*(data++) != '\0') {
1953 ALOGE("String longer than indicated utf16_size %#x", utf16Size);
1957 return (void*) data;
1960 /* Perform intra-item verification on debug_info_item. */
1961 static void* intraVerifyDebugInfoItem(const CheckState* state, void* ptr) {
1962 const u1* fileEnd = state->fileEnd;
1963 const u1* data = (const u1*) ptr;
1967 readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
1970 ALOGE("Bogus line_start");
1975 readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
1978 ALOGE("Bogus parameters_size");
1982 if (parametersSize > 65536) {
1983 ALOGE("Invalid parameters_size: %#x", parametersSize);
1987 for (i = 0; i < parametersSize; i++) {
1989 readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
1992 ALOGE("Bogus parameter_name");
1996 if (parameterName != 0) {
1998 CHECK_INDEX(parameterName, state->pHeader->stringIdsSize);
2004 u1 opcode = *(data++);
2007 case DBG_END_SEQUENCE: {
2011 case DBG_ADVANCE_PC: {
2012 readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2015 case DBG_ADVANCE_LINE: {
2016 readAndVerifySignedLeb128(&data, fileEnd, &okay);
2019 case DBG_START_LOCAL: {
2021 u4 regNum = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2023 if (regNum >= 65536) {
2027 idx = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2031 CHECK_INDEX(idx, state->pHeader->stringIdsSize);
2033 idx = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2037 CHECK_INDEX(idx, state->pHeader->stringIdsSize);
2042 case DBG_RESTART_LOCAL: {
2043 u4 regNum = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2045 if (regNum >= 65536) {
2051 case DBG_START_LOCAL_EXTENDED: {
2053 u4 regNum = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2055 if (regNum >= 65536) {
2059 idx = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2063 CHECK_INDEX(idx, state->pHeader->stringIdsSize);
2065 idx = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2069 CHECK_INDEX(idx, state->pHeader->stringIdsSize);
2071 idx = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2075 CHECK_INDEX(idx, state->pHeader->stringIdsSize);
2079 case DBG_SET_FILE: {
2080 u4 idx = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2084 CHECK_INDEX(idx, state->pHeader->stringIdsSize);
2089 // No arguments to parse for anything else.
2094 ALOGE("Bogus syntax for opcode %02x", opcode);
2099 return (void*) data;
2103 static const u1* verifyEncodedValue(const CheckState* state, const u1* data,
2105 static const u1* verifyEncodedAnnotation(const CheckState* state,
2106 const u1* data, bool crossVerify);
2108 /* Helper for verifyEncodedValue(), which reads a 1- to 4- byte unsigned
2109 * little endian value. */
2110 static u4 readUnsignedLittleEndian(const CheckState* state, const u1** pData,
2112 const u1* data = *pData;
2116 CHECK_PTR_RANGE(data, data + size);
2118 for (i = 0; i < size; i++) {
2119 result |= ((u4) *(data++)) << (i * 8);
2126 /* Helper for *VerifyAnnotationItem() and *VerifyEncodedArrayItem(), which
2127 * verifies an encoded_array. */
2128 static const u1* verifyEncodedArray(const CheckState* state,
2129 const u1* data, bool crossVerify) {
2131 u4 size = readAndVerifyUnsignedLeb128(&data, state->fileEnd, &okay);
2134 ALOGE("Bogus encoded_array size");
2139 data = verifyEncodedValue(state, data, crossVerify);
2141 ALOGE("Bogus encoded_array value");
2149 /* Helper for *VerifyAnnotationItem() and *VerifyEncodedArrayItem(), which
2150 * verifies an encoded_value. */
2151 static const u1* verifyEncodedValue(const CheckState* state,
2152 const u1* data, bool crossVerify) {
2153 CHECK_PTR_RANGE(data, data + 1);
2155 u1 headerByte = *(data++);
2156 u4 valueType = headerByte & kDexAnnotationValueTypeMask;
2157 u4 valueArg = headerByte >> kDexAnnotationValueArgShift;
2159 switch (valueType) {
2160 case kDexAnnotationByte: {
2161 if (valueArg != 0) {
2162 ALOGE("Bogus byte size %#x", valueArg);
2168 case kDexAnnotationShort:
2169 case kDexAnnotationChar: {
2171 ALOGE("Bogus char/short size %#x", valueArg);
2174 data += valueArg + 1;
2177 case kDexAnnotationInt:
2178 case kDexAnnotationFloat: {
2180 ALOGE("Bogus int/float size %#x", valueArg);
2183 data += valueArg + 1;
2186 case kDexAnnotationLong:
2187 case kDexAnnotationDouble: {
2188 data += valueArg + 1;
2191 case kDexAnnotationString: {
2193 ALOGE("Bogus string size %#x", valueArg);
2196 u4 idx = readUnsignedLittleEndian(state, &data, valueArg + 1);
2197 CHECK_INDEX(idx, state->pHeader->stringIdsSize);
2200 case kDexAnnotationType: {
2202 ALOGE("Bogus type size %#x", valueArg);
2205 u4 idx = readUnsignedLittleEndian(state, &data, valueArg + 1);
2206 CHECK_INDEX(idx, state->pHeader->typeIdsSize);
2209 case kDexAnnotationField:
2210 case kDexAnnotationEnum: {
2212 ALOGE("Bogus field/enum size %#x", valueArg);
2215 u4 idx = readUnsignedLittleEndian(state, &data, valueArg + 1);
2216 CHECK_INDEX(idx, state->pHeader->fieldIdsSize);
2219 case kDexAnnotationMethod: {
2221 ALOGE("Bogus method size %#x", valueArg);
2224 u4 idx = readUnsignedLittleEndian(state, &data, valueArg + 1);
2225 CHECK_INDEX(idx, state->pHeader->methodIdsSize);
2228 case kDexAnnotationArray: {
2229 if (valueArg != 0) {
2230 ALOGE("Bogus array value_arg %#x", valueArg);
2233 data = verifyEncodedArray(state, data, crossVerify);
2236 case kDexAnnotationAnnotation: {
2237 if (valueArg != 0) {
2238 ALOGE("Bogus annotation value_arg %#x", valueArg);
2241 data = verifyEncodedAnnotation(state, data, crossVerify);
2244 case kDexAnnotationNull: {
2245 if (valueArg != 0) {
2246 ALOGE("Bogus null value_arg %#x", valueArg);
2249 // Nothing else to do for this type.
2252 case kDexAnnotationBoolean: {
2254 ALOGE("Bogus boolean value_arg %#x", valueArg);
2257 // Nothing else to do for this type.
2261 ALOGE("Bogus value_type %#x", valueType);
2269 /* Helper for *VerifyAnnotationItem() and *VerifyEncodedArrayItem(), which
2270 * verifies an encoded_annotation. */
2271 static const u1* verifyEncodedAnnotation(const CheckState* state,
2272 const u1* data, bool crossVerify) {
2273 const u1* fileEnd = state->fileEnd;
2275 u4 idx = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2278 ALOGE("Bogus encoded_annotation type_idx");
2282 CHECK_INDEX(idx, state->pHeader->typeIdsSize);
2285 const char* descriptor = dexStringByTypeIdx(state->pDexFile, idx);
2286 if (!dexIsClassDescriptor(descriptor)) {
2287 ALOGE("Bogus annotation type: '%s'", descriptor);
2292 u4 size = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2297 ALOGE("Bogus encoded_annotation size");
2302 idx = readAndVerifyUnsignedLeb128(&data, fileEnd, &okay);
2305 ALOGE("Bogus encoded_annotation name_idx");
2309 CHECK_INDEX(idx, state->pHeader->stringIdsSize);
2312 const char* name = dexStringById(state->pDexFile, idx);
2313 if (!dexIsValidMemberName(name)) {
2314 ALOGE("Bogus annotation member name: '%s'", name);
2321 } else if (lastIdx >= idx) {
2322 ALOGE("Out-of-order encoded_annotation name_idx: %#x then %#x",
2327 data = verifyEncodedValue(state, data, crossVerify);
2338 /* Perform intra-item verification on encoded_array_item. */
2339 static void* intraVerifyEncodedArrayItem(const CheckState* state, void* ptr) {
2340 return (void*) verifyEncodedArray(state, (const u1*) ptr, false);
2343 /* Perform intra-item verification on annotation_item. */
2344 static void* intraVerifyAnnotationItem(const CheckState* state, void* ptr) {
2345 const u1* data = (const u1*) ptr;
2347 CHECK_PTR_RANGE(data, data + 1);
2349 switch (*(data++)) {
2350 case kDexVisibilityBuild:
2351 case kDexVisibilityRuntime:
2352 case kDexVisibilitySystem: {
2356 ALOGE("Bogus annotation visibility: %#x", *data);
2361 return (void*) verifyEncodedAnnotation(state, data, false);
2364 /* Perform cross-item verification on annotation_item. */
2365 static void* crossVerifyAnnotationItem(const CheckState* state, void* ptr) {
2366 const u1* data = (const u1*) ptr;
2368 // Skip the visibility byte.
2371 return (void*) verifyEncodedAnnotation(state, data, true);
2378 * Function to visit an individual top-level item type.
2380 typedef void* ItemVisitorFunction(const CheckState* state, void* ptr);
2383 * Iterate over all the items in a section, optionally updating the
2384 * data map (done if mapType is passed as non-negative). The section
2385 * must consist of concatenated items of the same type.
2387 static bool iterateSectionWithOptionalUpdate(CheckState* state,
2388 u4 offset, u4 count, ItemVisitorFunction* func, u4 alignment,
2389 u4* nextOffset, int mapType) {
2390 u4 alignmentMask = alignment - 1;
2393 state->previousItem = NULL;
2395 for (i = 0; i < count; i++) {
2396 u4 newOffset = (offset + alignmentMask) & ~alignmentMask;
2397 u1* ptr = (u1*) filePointer(state, newOffset);
2399 if (offset < newOffset) {
2400 ptr = (u1*) filePointer(state, offset);
2401 if (offset < newOffset) {
2402 CHECK_OFFSET_RANGE(offset, newOffset);
2403 while (offset < newOffset) {
2405 ALOGE("Non-zero padding 0x%02x @ %x", *ptr, offset);
2414 u1* newPtr = (u1*) func(state, ptr);
2415 newOffset = fileOffset(state, newPtr);
2417 if (newPtr == NULL) {
2418 ALOGE("Trouble with item %d @ offset %#x", i, offset);
2422 if (newOffset > state->fileLen) {
2423 ALOGE("Item %d @ offset %#x ends out of bounds", i, offset);
2428 dexDataMapAdd(state->pDataMap, offset, mapType);
2431 state->previousItem = ptr;
2435 if (nextOffset != NULL) {
2436 *nextOffset = offset;
2443 * Iterate over all the items in a section. The section must consist of
2444 * concatenated items of the same type. This variant will not update the data
2447 static bool iterateSection(CheckState* state, u4 offset, u4 count,
2448 ItemVisitorFunction* func, u4 alignment, u4* nextOffset) {
2449 return iterateSectionWithOptionalUpdate(state, offset, count, func,
2450 alignment, nextOffset, -1);
2454 * Like iterateSection(), but also check that the offset and count match
2455 * a given pair of expected values.
2457 static bool checkBoundsAndIterateSection(CheckState* state,
2458 u4 offset, u4 count, u4 expectedOffset, u4 expectedCount,
2459 ItemVisitorFunction* func, u4 alignment, u4* nextOffset) {
2460 if (offset != expectedOffset) {
2461 ALOGE("Bogus offset for section: got %#x; expected %#x",
2462 offset, expectedOffset);
2466 if (count != expectedCount) {
2467 ALOGE("Bogus size for section: got %#x; expected %#x",
2468 count, expectedCount);
2472 return iterateSection(state, offset, count, func, alignment, nextOffset);
2476 * Like iterateSection(), but also update the data section map and
2477 * check that all the items fall within the data section.
2479 static bool iterateDataSection(CheckState* state, u4 offset, u4 count,
2480 ItemVisitorFunction* func, u4 alignment, u4* nextOffset, int mapType) {
2481 u4 dataStart = state->pHeader->dataOff;
2482 u4 dataEnd = dataStart + state->pHeader->dataSize;
2484 assert(nextOffset != NULL);
2486 if ((offset < dataStart) || (offset >= dataEnd)) {
2487 ALOGE("Bogus offset for data subsection: %#x", offset);
2491 if (!iterateSectionWithOptionalUpdate(state, offset, count, func,
2492 alignment, nextOffset, mapType)) {
2496 if (*nextOffset > dataEnd) {
2497 ALOGE("Out-of-bounds end of data subsection: %#x", *nextOffset);
2505 * Byte-swap all items in the given map except the header and the map
2506 * itself, both of which should have already gotten swapped. This also
2507 * does all possible intra-item verification, that is, verification
2508 * that doesn't need to assume the sanctity of the contents of *other*
2509 * items. The intra-item limitation is because at the time an item is
2510 * asked to verify itself, it can't assume that the items it refers to
2511 * have been byte-swapped and verified.
2513 static bool swapEverythingButHeaderAndMap(CheckState* state,
2515 const DexMapItem* item = pMap->list;
2517 u4 count = pMap->size;
2520 while (okay && count--) {
2521 u4 sectionOffset = item->offset;
2522 u4 sectionCount = item->size;
2523 u2 type = item->type;
2525 if (lastOffset < sectionOffset) {
2526 CHECK_OFFSET_RANGE(lastOffset, sectionOffset);
2527 const u1* ptr = (const u1*) filePointer(state, lastOffset);
2528 while (lastOffset < sectionOffset) {
2530 ALOGE("Non-zero padding 0x%02x before section start @ %x",
2538 } else if (lastOffset > sectionOffset) {
2539 ALOGE("Section overlap or out-of-order map: %x, %x",
2540 lastOffset, sectionOffset);
2549 case kDexTypeHeaderItem: {
2551 * The header got swapped very early on, but do some
2552 * additional sanity checking here.
2554 okay = checkHeaderSection(state, sectionOffset, sectionCount,
2558 case kDexTypeStringIdItem: {
2559 okay = checkBoundsAndIterateSection(state, sectionOffset,
2560 sectionCount, state->pHeader->stringIdsOff,
2561 state->pHeader->stringIdsSize, swapStringIdItem,
2562 sizeof(u4), &lastOffset);
2565 case kDexTypeTypeIdItem: {
2566 okay = checkBoundsAndIterateSection(state, sectionOffset,
2567 sectionCount, state->pHeader->typeIdsOff,
2568 state->pHeader->typeIdsSize, swapTypeIdItem,
2569 sizeof(u4), &lastOffset);
2572 case kDexTypeProtoIdItem: {
2573 okay = checkBoundsAndIterateSection(state, sectionOffset,
2574 sectionCount, state->pHeader->protoIdsOff,
2575 state->pHeader->protoIdsSize, swapProtoIdItem,
2576 sizeof(u4), &lastOffset);
2579 case kDexTypeFieldIdItem: {
2580 okay = checkBoundsAndIterateSection(state, sectionOffset,
2581 sectionCount, state->pHeader->fieldIdsOff,
2582 state->pHeader->fieldIdsSize, swapFieldIdItem,
2583 sizeof(u4), &lastOffset);
2586 case kDexTypeMethodIdItem: {
2587 okay = checkBoundsAndIterateSection(state, sectionOffset,
2588 sectionCount, state->pHeader->methodIdsOff,
2589 state->pHeader->methodIdsSize, swapMethodIdItem,
2590 sizeof(u4), &lastOffset);
2593 case kDexTypeClassDefItem: {
2594 okay = checkBoundsAndIterateSection(state, sectionOffset,
2595 sectionCount, state->pHeader->classDefsOff,
2596 state->pHeader->classDefsSize, swapClassDefItem,
2597 sizeof(u4), &lastOffset);
2600 case kDexTypeMapList: {
2602 * The map section was swapped early on, but do some
2603 * additional sanity checking here.
2605 okay = checkMapSection(state, sectionOffset, sectionCount,
2609 case kDexTypeTypeList: {
2610 okay = iterateDataSection(state, sectionOffset, sectionCount,
2611 swapTypeList, sizeof(u4), &lastOffset, type);
2614 case kDexTypeAnnotationSetRefList: {
2615 okay = iterateDataSection(state, sectionOffset, sectionCount,
2616 swapAnnotationSetRefList, sizeof(u4), &lastOffset,
2620 case kDexTypeAnnotationSetItem: {
2621 okay = iterateDataSection(state, sectionOffset, sectionCount,
2622 swapAnnotationSetItem, sizeof(u4), &lastOffset, type);
2625 case kDexTypeClassDataItem: {
2626 okay = iterateDataSection(state, sectionOffset, sectionCount,
2627 intraVerifyClassDataItem, sizeof(u1), &lastOffset,
2631 case kDexTypeCodeItem: {
2632 okay = iterateDataSection(state, sectionOffset, sectionCount,
2633 swapCodeItem, sizeof(u4), &lastOffset, type);
2636 case kDexTypeStringDataItem: {
2637 okay = iterateDataSection(state, sectionOffset, sectionCount,
2638 intraVerifyStringDataItem, sizeof(u1), &lastOffset,
2642 case kDexTypeDebugInfoItem: {
2643 okay = iterateDataSection(state, sectionOffset, sectionCount,
2644 intraVerifyDebugInfoItem, sizeof(u1), &lastOffset,
2648 case kDexTypeAnnotationItem: {
2649 okay = iterateDataSection(state, sectionOffset, sectionCount,
2650 intraVerifyAnnotationItem, sizeof(u1), &lastOffset,
2654 case kDexTypeEncodedArrayItem: {
2655 okay = iterateDataSection(state, sectionOffset, sectionCount,
2656 intraVerifyEncodedArrayItem, sizeof(u1), &lastOffset,
2660 case kDexTypeAnnotationsDirectoryItem: {
2661 okay = iterateDataSection(state, sectionOffset, sectionCount,
2662 swapAnnotationsDirectoryItem, sizeof(u4), &lastOffset,
2667 ALOGE("Unknown map item type %04x", type);
2673 ALOGE("Swap of section type %04x failed", type);
2683 * Perform cross-item verification on everything that needs it. This
2684 * pass is only called after all items are byte-swapped and
2685 * intra-verified (checked for internal consistency).
2687 static bool crossVerifyEverything(CheckState* state, DexMapList* pMap)
2689 const DexMapItem* item = pMap->list;
2690 u4 count = pMap->size;
2693 while (okay && count--) {
2694 u4 sectionOffset = item->offset;
2695 u4 sectionCount = item->size;
2697 switch (item->type) {
2698 case kDexTypeHeaderItem:
2699 case kDexTypeMapList:
2700 case kDexTypeTypeList:
2701 case kDexTypeCodeItem:
2702 case kDexTypeStringDataItem:
2703 case kDexTypeDebugInfoItem:
2704 case kDexTypeAnnotationItem:
2705 case kDexTypeEncodedArrayItem: {
2706 // There is no need for cross-item verification for these.
2709 case kDexTypeStringIdItem: {
2710 okay = iterateSection(state, sectionOffset, sectionCount,
2711 crossVerifyStringIdItem, sizeof(u4), NULL);
2714 case kDexTypeTypeIdItem: {
2715 okay = iterateSection(state, sectionOffset, sectionCount,
2716 crossVerifyTypeIdItem, sizeof(u4), NULL);
2719 case kDexTypeProtoIdItem: {
2720 okay = iterateSection(state, sectionOffset, sectionCount,
2721 crossVerifyProtoIdItem, sizeof(u4), NULL);
2724 case kDexTypeFieldIdItem: {
2725 okay = iterateSection(state, sectionOffset, sectionCount,
2726 crossVerifyFieldIdItem, sizeof(u4), NULL);
2729 case kDexTypeMethodIdItem: {
2730 okay = iterateSection(state, sectionOffset, sectionCount,
2731 crossVerifyMethodIdItem, sizeof(u4), NULL);
2734 case kDexTypeClassDefItem: {
2735 // Allocate (on the stack) the "observed class_def" bits.
2736 size_t arraySize = calcDefinedClassBitsSize(state);
2737 u4 definedClassBits[arraySize];
2738 memset(definedClassBits, 0, arraySize * sizeof(u4));
2739 state->pDefinedClassBits = definedClassBits;
2741 okay = iterateSection(state, sectionOffset, sectionCount,
2742 crossVerifyClassDefItem, sizeof(u4), NULL);
2744 state->pDefinedClassBits = NULL;
2747 case kDexTypeAnnotationSetRefList: {
2748 okay = iterateSection(state, sectionOffset, sectionCount,
2749 crossVerifyAnnotationSetRefList, sizeof(u4), NULL);
2752 case kDexTypeAnnotationSetItem: {
2753 okay = iterateSection(state, sectionOffset, sectionCount,
2754 crossVerifyAnnotationSetItem, sizeof(u4), NULL);
2757 case kDexTypeClassDataItem: {
2758 okay = iterateSection(state, sectionOffset, sectionCount,
2759 crossVerifyClassDataItem, sizeof(u1), NULL);
2762 case kDexTypeAnnotationsDirectoryItem: {
2763 okay = iterateSection(state, sectionOffset, sectionCount,
2764 crossVerifyAnnotationsDirectoryItem, sizeof(u4), NULL);
2768 ALOGE("Unknown map item type %04x", item->type);
2774 ALOGE("Cross-item verify of section type %04x failed",
2784 /* (documented in header file) */
2785 bool dexHasValidMagic(const DexHeader* pHeader)
2787 const u1* magic = pHeader->magic;
2788 const u1* version = &magic[4];
2790 if (memcmp(magic, DEX_MAGIC, 4) != 0) {
2791 ALOGE("ERROR: unrecognized magic number (%02x %02x %02x %02x)",
2792 magic[0], magic[1], magic[2], magic[3]);
2796 if ((memcmp(version, DEX_MAGIC_VERS, 4) != 0) &&
2797 (memcmp(version, DEX_MAGIC_VERS_API_13, 4) != 0)) {
2799 * Magic was correct, but this is an unsupported older or
2800 * newer format variant.
2802 ALOGE("ERROR: unsupported dex version (%02x %02x %02x %02x)",
2803 version[0], version[1], version[2], version[3]);
2811 * Fix the byte ordering of all fields in the DEX file, and do
2812 * structural verification. This is only required for code that opens
2813 * "raw" DEX files, such as the DEX optimizer.
2815 * Returns 0 on success, nonzero on failure.
2817 int dexSwapAndVerify(u1* addr, int len)
2823 memset(&state, 0, sizeof(state));
2824 ALOGV("+++ swapping and verifying");
2827 * Note: The caller must have verified that "len" is at least as
2828 * large as a dex file header.
2830 pHeader = (DexHeader*) addr;
2832 if (!dexHasValidMagic(pHeader)) {
2837 int expectedLen = (int) SWAP4(pHeader->fileSize);
2838 if (len < expectedLen) {
2839 ALOGE("ERROR: Bad length: expected %d, got %d", expectedLen, len);
2841 } else if (len != expectedLen) {
2842 ALOGW("WARNING: Odd length: expected %d, got %d", expectedLen,
2850 * Compute the adler32 checksum and compare it to what's stored in
2851 * the file. This isn't free, but chances are good that we just
2852 * unpacked this from a jar file and have all of the pages sitting
2853 * in memory, so it's pretty quick.
2855 * This might be a big-endian system, so we need to do this before
2856 * we byte-swap the header.
2858 uLong adler = adler32(0L, Z_NULL, 0);
2859 const int nonSum = sizeof(pHeader->magic) + sizeof(pHeader->checksum);
2860 u4 storedFileSize = SWAP4(pHeader->fileSize);
2861 u4 expectedChecksum = SWAP4(pHeader->checksum);
2863 adler = adler32(adler, ((const u1*) pHeader) + nonSum,
2864 storedFileSize - nonSum);
2866 if (adler != expectedChecksum) {
2867 ALOGE("ERROR: bad checksum (%08lx, expected %08x)",
2868 adler, expectedChecksum);
2874 state.fileStart = addr;
2875 state.fileEnd = addr + len;
2876 state.fileLen = len;
2877 state.pDexFile = NULL;
2878 state.pDataMap = NULL;
2879 state.pDefinedClassBits = NULL;
2880 state.previousItem = NULL;
2883 * Swap the header and check the contents.
2885 okay = swapDexHeader(&state, pHeader);
2889 state.pHeader = pHeader;
2891 if (pHeader->headerSize < sizeof(DexHeader)) {
2892 ALOGE("ERROR: Small header size %d, struct %d",
2893 pHeader->headerSize, (int) sizeof(DexHeader));
2895 } else if (pHeader->headerSize > sizeof(DexHeader)) {
2896 ALOGW("WARNING: Large header size %d, struct %d",
2897 pHeader->headerSize, (int) sizeof(DexHeader));
2904 * Look for the map. Swap it and then use it to find and swap
2907 if (pHeader->mapOff != 0) {
2909 DexMapList* pDexMap = (DexMapList*) (addr + pHeader->mapOff);
2911 okay = okay && swapMap(&state, pDexMap);
2912 okay = okay && swapEverythingButHeaderAndMap(&state, pDexMap);
2914 dexFileSetupBasicPointers(&dexFile, addr);
2915 state.pDexFile = &dexFile;
2917 okay = okay && crossVerifyEverything(&state, pDexMap);
2919 ALOGE("ERROR: No map found; impossible to byte-swap and verify");
2925 ALOGE("ERROR: Byte swap + verify failed");
2928 if (state.pDataMap != NULL) {
2929 dexDataMapFree(state.pDataMap);
2932 return !okay; // 0 == success
2936 * Detect the file type of the given memory buffer via magic number.
2937 * Call dexSwapAndVerify() on an unoptimized DEX file, do nothing
2938 * but return successfully on an optimized DEX file, and report an
2939 * error for all other cases.
2941 * Returns 0 on success, nonzero on failure.
2943 int dexSwapAndVerifyIfNecessary(u1* addr, int len)
2945 if (memcmp(addr, DEX_OPT_MAGIC, 4) == 0) {
2946 // It is an optimized dex file.
2950 if (memcmp(addr, DEX_MAGIC, 4) == 0) {
2951 // It is an unoptimized dex file.
2952 return dexSwapAndVerify(addr, len);
2955 ALOGE("ERROR: Bad magic number (0x%02x %02x %02x %02x)",
2956 addr[0], addr[1], addr[2], addr[3]);