1/* 2 * Copyright (C) 2008 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 */ 16 17/* 18 * The "dexdump" tool is intended to mimic "objdump". When possible, use 19 * similar command-line arguments. 20 * 21 * TODO: rework the "plain" output format to be more regexp-friendly 22 * 23 * Differences between XML output and the "current.xml" file: 24 * - classes in same package are not all grouped together; generally speaking 25 * nothing is sorted 26 * - no "deprecated" on fields and methods 27 * - no "value" on fields 28 * - no parameter names 29 * - no generic signatures on parameters, e.g. type="java.lang.Class<?>" 30 * - class shows declared fields and methods; does not show inherited fields 31 */ 32 33#include "libdex/DexFile.h" 34 35#include "libdex/CmdUtils.h" 36#include "libdex/DexCatch.h" 37#include "libdex/DexClass.h" 38#include "libdex/DexDebugInfo.h" 39#include "libdex/DexOpcodes.h" 40#include "libdex/DexProto.h" 41#include "libdex/InstrUtils.h" 42#include "libdex/SysUtil.h" 43 44#include <stdlib.h> 45#include <stdio.h> 46#include <fcntl.h> 47#include <string.h> 48#include <unistd.h> 49#include <getopt.h> 50#include <errno.h> 51#include <assert.h> 52 53static const char* gProgName = "dexdump"; 54 55enum OutputFormat { 56 OUTPUT_PLAIN = 0, /* default */ 57 OUTPUT_XML, /* fancy */ 58}; 59 60/* command-line options */ 61struct Options { 62 bool checksumOnly; 63 bool disassemble; 64 bool showFileHeaders; 65 bool showSectionHeaders; 66 bool ignoreBadChecksum; 67 bool dumpRegisterMaps; 68 OutputFormat outputFormat; 69 const char* tempFileName; 70 bool exportsOnly; 71 bool verbose; 72}; 73 74struct Options gOptions; 75 76/* basic info about a field or method */ 77struct FieldMethodInfo { 78 const char* classDescriptor; 79 const char* name; 80 const char* signature; 81}; 82 83/* 84 * Get 2 little-endian bytes. 85 */ 86static inline u2 get2LE(unsigned char const* pSrc) 87{ 88 return pSrc[0] | (pSrc[1] << 8); 89} 90 91/* 92 * Get 4 little-endian bytes. 93 */ 94static inline u4 get4LE(unsigned char const* pSrc) 95{ 96 return pSrc[0] | (pSrc[1] << 8) | (pSrc[2] << 16) | (pSrc[3] << 24); 97} 98 99/* 100 * Converts a single-character primitive type into its human-readable 101 * equivalent. 102 */ 103static const char* primitiveTypeLabel(char typeChar) 104{ 105 switch (typeChar) { 106 case 'B': return "byte"; 107 case 'C': return "char"; 108 case 'D': return "double"; 109 case 'F': return "float"; 110 case 'I': return "int"; 111 case 'J': return "long"; 112 case 'S': return "short"; 113 case 'V': return "void"; 114 case 'Z': return "boolean"; 115 default: 116 return "UNKNOWN"; 117 } 118} 119 120/* 121 * Converts a type descriptor to human-readable "dotted" form. For 122 * example, "Ljava/lang/String;" becomes "java.lang.String", and 123 * "[I" becomes "int[]". Also converts '$' to '.', which means this 124 * form can't be converted back to a descriptor. 125 */ 126static char* descriptorToDot(const char* str) 127{ 128 int targetLen = strlen(str); 129 int offset = 0; 130 int arrayDepth = 0; 131 char* newStr; 132 133 /* strip leading [s; will be added to end */ 134 while (targetLen > 1 && str[offset] == '[') { 135 offset++; 136 targetLen--; 137 } 138 arrayDepth = offset; 139 140 if (targetLen == 1) { 141 /* primitive type */ 142 str = primitiveTypeLabel(str[offset]); 143 offset = 0; 144 targetLen = strlen(str); 145 } else { 146 /* account for leading 'L' and trailing ';' */ 147 if (targetLen >= 2 && str[offset] == 'L' && 148 str[offset+targetLen-1] == ';') 149 { 150 targetLen -= 2; 151 offset++; 152 } 153 } 154 155 newStr = (char*)malloc(targetLen + arrayDepth * 2 +1); 156 157 /* copy class name over */ 158 int i; 159 for (i = 0; i < targetLen; i++) { 160 char ch = str[offset + i]; 161 newStr[i] = (ch == '/' || ch == '$') ? '.' : ch; 162 } 163 164 /* add the appropriate number of brackets for arrays */ 165 while (arrayDepth-- > 0) { 166 newStr[i++] = '['; 167 newStr[i++] = ']'; 168 } 169 newStr[i] = '\0'; 170 assert(i == targetLen + arrayDepth * 2); 171 172 return newStr; 173} 174 175/* 176 * Converts the class name portion of a type descriptor to human-readable 177 * "dotted" form. 178 * 179 * Returns a newly-allocated string. 180 */ 181static char* descriptorClassToDot(const char* str) 182{ 183 const char* lastSlash; 184 char* newStr; 185 char* cp; 186 187 /* reduce to just the class name, trimming trailing ';' */ 188 lastSlash = strrchr(str, '/'); 189 if (lastSlash == NULL) 190 lastSlash = str + 1; /* start past 'L' */ 191 else 192 lastSlash++; /* start past '/' */ 193 194 newStr = strdup(lastSlash); 195 newStr[strlen(lastSlash)-1] = '\0'; 196 for (cp = newStr; *cp != '\0'; cp++) { 197 if (*cp == '$') 198 *cp = '.'; 199 } 200 201 return newStr; 202} 203 204/* 205 * Returns a quoted string representing the boolean value. 206 */ 207static const char* quotedBool(bool val) 208{ 209 if (val) 210 return "\"true\""; 211 else 212 return "\"false\""; 213} 214 215static const char* quotedVisibility(u4 accessFlags) 216{ 217 if ((accessFlags & ACC_PUBLIC) != 0) 218 return "\"public\""; 219 else if ((accessFlags & ACC_PROTECTED) != 0) 220 return "\"protected\""; 221 else if ((accessFlags & ACC_PRIVATE) != 0) 222 return "\"private\""; 223 else 224 return "\"package\""; 225} 226 227/* 228 * Count the number of '1' bits in a word. 229 */ 230static int countOnes(u4 val) 231{ 232 int count = 0; 233 234 val = val - ((val >> 1) & 0x55555555); 235 val = (val & 0x33333333) + ((val >> 2) & 0x33333333); 236 count = (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; 237 238 return count; 239} 240 241/* 242 * Flag for use with createAccessFlagStr(). 243 */ 244enum AccessFor { 245 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, 246 kAccessForMAX 247}; 248 249/* 250 * Create a new string with human-readable access flags. 251 * 252 * In the base language the access_flags fields are type u2; in Dalvik 253 * they're u4. 254 */ 255static char* createAccessFlagStr(u4 flags, AccessFor forWhat) 256{ 257#define NUM_FLAGS 18 258 static const char* kAccessStrings[kAccessForMAX][NUM_FLAGS] = { 259 { 260 /* class, inner class */ 261 "PUBLIC", /* 0x0001 */ 262 "PRIVATE", /* 0x0002 */ 263 "PROTECTED", /* 0x0004 */ 264 "STATIC", /* 0x0008 */ 265 "FINAL", /* 0x0010 */ 266 "?", /* 0x0020 */ 267 "?", /* 0x0040 */ 268 "?", /* 0x0080 */ 269 "?", /* 0x0100 */ 270 "INTERFACE", /* 0x0200 */ 271 "ABSTRACT", /* 0x0400 */ 272 "?", /* 0x0800 */ 273 "SYNTHETIC", /* 0x1000 */ 274 "ANNOTATION", /* 0x2000 */ 275 "ENUM", /* 0x4000 */ 276 "?", /* 0x8000 */ 277 "VERIFIED", /* 0x10000 */ 278 "OPTIMIZED", /* 0x20000 */ 279 }, 280 { 281 /* method */ 282 "PUBLIC", /* 0x0001 */ 283 "PRIVATE", /* 0x0002 */ 284 "PROTECTED", /* 0x0004 */ 285 "STATIC", /* 0x0008 */ 286 "FINAL", /* 0x0010 */ 287 "SYNCHRONIZED", /* 0x0020 */ 288 "BRIDGE", /* 0x0040 */ 289 "VARARGS", /* 0x0080 */ 290 "NATIVE", /* 0x0100 */ 291 "?", /* 0x0200 */ 292 "ABSTRACT", /* 0x0400 */ 293 "STRICT", /* 0x0800 */ 294 "SYNTHETIC", /* 0x1000 */ 295 "?", /* 0x2000 */ 296 "?", /* 0x4000 */ 297 "MIRANDA", /* 0x8000 */ 298 "CONSTRUCTOR", /* 0x10000 */ 299 "DECLARED_SYNCHRONIZED", /* 0x20000 */ 300 }, 301 { 302 /* field */ 303 "PUBLIC", /* 0x0001 */ 304 "PRIVATE", /* 0x0002 */ 305 "PROTECTED", /* 0x0004 */ 306 "STATIC", /* 0x0008 */ 307 "FINAL", /* 0x0010 */ 308 "?", /* 0x0020 */ 309 "VOLATILE", /* 0x0040 */ 310 "TRANSIENT", /* 0x0080 */ 311 "?", /* 0x0100 */ 312 "?", /* 0x0200 */ 313 "?", /* 0x0400 */ 314 "?", /* 0x0800 */ 315 "SYNTHETIC", /* 0x1000 */ 316 "?", /* 0x2000 */ 317 "ENUM", /* 0x4000 */ 318 "?", /* 0x8000 */ 319 "?", /* 0x10000 */ 320 "?", /* 0x20000 */ 321 }, 322 }; 323 const int kLongest = 21; /* strlen of longest string above */ 324 int i, count; 325 char* str; 326 char* cp; 327 328 /* 329 * Allocate enough storage to hold the expected number of strings, 330 * plus a space between each. We over-allocate, using the longest 331 * string above as the base metric. 332 */ 333 count = countOnes(flags); 334 cp = str = (char*) malloc(count * (kLongest+1) +1); 335 336 for (i = 0; i < NUM_FLAGS; i++) { 337 if (flags & 0x01) { 338 const char* accessStr = kAccessStrings[forWhat][i]; 339 int len = strlen(accessStr); 340 if (cp != str) 341 *cp++ = ' '; 342 343 memcpy(cp, accessStr, len); 344 cp += len; 345 } 346 flags >>= 1; 347 } 348 *cp = '\0'; 349 350 return str; 351} 352 353 354/* 355 * Copy character data from "data" to "out", converting non-ASCII values 356 * to printf format chars or an ASCII filler ('.' or '?'). 357 * 358 * The output buffer must be able to hold (2*len)+1 bytes. The result is 359 * NUL-terminated. 360 */ 361static void asciify(char* out, const unsigned char* data, size_t len) 362{ 363 while (len--) { 364 if (*data < 0x20) { 365 /* could do more here, but we don't need them yet */ 366 switch (*data) { 367 case '\0': 368 *out++ = '\\'; 369 *out++ = '0'; 370 break; 371 case '\n': 372 *out++ = '\\'; 373 *out++ = 'n'; 374 break; 375 default: 376 *out++ = '.'; 377 break; 378 } 379 } else if (*data >= 0x80) { 380 *out++ = '?'; 381 } else { 382 *out++ = *data; 383 } 384 data++; 385 } 386 *out = '\0'; 387} 388 389/* 390 * Dump the file header. 391 */ 392void dumpFileHeader(const DexFile* pDexFile) 393{ 394 const DexOptHeader* pOptHeader = pDexFile->pOptHeader; 395 const DexHeader* pHeader = pDexFile->pHeader; 396 char sanitized[sizeof(pHeader->magic)*2 +1]; 397 398 assert(sizeof(pHeader->magic) == sizeof(pOptHeader->magic)); 399 400 if (pOptHeader != NULL) { 401 printf("Optimized DEX file header:\n"); 402 403 asciify(sanitized, pOptHeader->magic, sizeof(pOptHeader->magic)); 404 printf("magic : '%s'\n", sanitized); 405 printf("dex_offset : %d (0x%06x)\n", 406 pOptHeader->dexOffset, pOptHeader->dexOffset); 407 printf("dex_length : %d\n", pOptHeader->dexLength); 408 printf("deps_offset : %d (0x%06x)\n", 409 pOptHeader->depsOffset, pOptHeader->depsOffset); 410 printf("deps_length : %d\n", pOptHeader->depsLength); 411 printf("opt_offset : %d (0x%06x)\n", 412 pOptHeader->optOffset, pOptHeader->optOffset); 413 printf("opt_length : %d\n", pOptHeader->optLength); 414 printf("flags : %08x\n", pOptHeader->flags); 415 printf("checksum : %08x\n", pOptHeader->checksum); 416 printf("\n"); 417 } 418 419 printf("DEX file header:\n"); 420 asciify(sanitized, pHeader->magic, sizeof(pHeader->magic)); 421 printf("magic : '%s'\n", sanitized); 422 printf("checksum : %08x\n", pHeader->checksum); 423 printf("signature : %02x%02x...%02x%02x\n", 424 pHeader->signature[0], pHeader->signature[1], 425 pHeader->signature[kSHA1DigestLen-2], 426 pHeader->signature[kSHA1DigestLen-1]); 427 printf("file_size : %d\n", pHeader->fileSize); 428 printf("header_size : %d\n", pHeader->headerSize); 429 printf("link_size : %d\n", pHeader->linkSize); 430 printf("link_off : %d (0x%06x)\n", 431 pHeader->linkOff, pHeader->linkOff); 432 printf("string_ids_size : %d\n", pHeader->stringIdsSize); 433 printf("string_ids_off : %d (0x%06x)\n", 434 pHeader->stringIdsOff, pHeader->stringIdsOff); 435 printf("type_ids_size : %d\n", pHeader->typeIdsSize); 436 printf("type_ids_off : %d (0x%06x)\n", 437 pHeader->typeIdsOff, pHeader->typeIdsOff); 438 printf("field_ids_size : %d\n", pHeader->fieldIdsSize); 439 printf("field_ids_off : %d (0x%06x)\n", 440 pHeader->fieldIdsOff, pHeader->fieldIdsOff); 441 printf("method_ids_size : %d\n", pHeader->methodIdsSize); 442 printf("method_ids_off : %d (0x%06x)\n", 443 pHeader->methodIdsOff, pHeader->methodIdsOff); 444 printf("class_defs_size : %d\n", pHeader->classDefsSize); 445 printf("class_defs_off : %d (0x%06x)\n", 446 pHeader->classDefsOff, pHeader->classDefsOff); 447 printf("data_size : %d\n", pHeader->dataSize); 448 printf("data_off : %d (0x%06x)\n", 449 pHeader->dataOff, pHeader->dataOff); 450 printf("\n"); 451} 452 453/* 454 * Dump the "table of contents" for the opt area. 455 */ 456void dumpOptDirectory(const DexFile* pDexFile) 457{ 458 const DexOptHeader* pOptHeader = pDexFile->pOptHeader; 459 if (pOptHeader == NULL) 460 return; 461 462 printf("OPT section contents:\n"); 463 464 const u4* pOpt = (const u4*) ((u1*) pOptHeader + pOptHeader->optOffset); 465 466 if (*pOpt == 0) { 467 printf("(1.0 format, only class lookup table is present)\n\n"); 468 return; 469 } 470 471 /* 472 * The "opt" section is in "chunk" format: a 32-bit identifier, a 32-bit 473 * length, then the data. Chunks start on 64-bit boundaries. 474 */ 475 while (*pOpt != kDexChunkEnd) { 476 const char* verboseStr; 477 478 u4 size = *(pOpt+1); 479 480 switch (*pOpt) { 481 case kDexChunkClassLookup: 482 verboseStr = "class lookup hash table"; 483 break; 484 case kDexChunkRegisterMaps: 485 verboseStr = "register maps"; 486 break; 487 default: 488 verboseStr = "(unknown chunk type)"; 489 break; 490 } 491 492 printf("Chunk %08x (%c%c%c%c) - %s (%d bytes)\n", *pOpt, 493 *pOpt >> 24, (char)(*pOpt >> 16), (char)(*pOpt >> 8), (char)*pOpt, 494 verboseStr, size); 495 496 size = (size + 8 + 7) & ~7; 497 pOpt += size / sizeof(u4); 498 } 499 printf("\n"); 500} 501 502/* 503 * Dump a class_def_item. 504 */ 505void dumpClassDef(DexFile* pDexFile, int idx) 506{ 507 const DexClassDef* pClassDef; 508 const u1* pEncodedData; 509 DexClassData* pClassData; 510 511 pClassDef = dexGetClassDef(pDexFile, idx); 512 pEncodedData = dexGetClassData(pDexFile, pClassDef); 513 pClassData = dexReadAndVerifyClassData(&pEncodedData, NULL); 514 515 if (pClassData == NULL) { 516 fprintf(stderr, "Trouble reading class data\n"); 517 return; 518 } 519 520 printf("Class #%d header:\n", idx); 521 printf("class_idx : %d\n", pClassDef->classIdx); 522 printf("access_flags : %d (0x%04x)\n", 523 pClassDef->accessFlags, pClassDef->accessFlags); 524 printf("superclass_idx : %d\n", pClassDef->superclassIdx); 525 printf("interfaces_off : %d (0x%06x)\n", 526 pClassDef->interfacesOff, pClassDef->interfacesOff); 527 printf("source_file_idx : %d\n", pClassDef->sourceFileIdx); 528 printf("annotations_off : %d (0x%06x)\n", 529 pClassDef->annotationsOff, pClassDef->annotationsOff); 530 printf("class_data_off : %d (0x%06x)\n", 531 pClassDef->classDataOff, pClassDef->classDataOff); 532 printf("static_fields_size : %d\n", pClassData->header.staticFieldsSize); 533 printf("instance_fields_size: %d\n", 534 pClassData->header.instanceFieldsSize); 535 printf("direct_methods_size : %d\n", pClassData->header.directMethodsSize); 536 printf("virtual_methods_size: %d\n", 537 pClassData->header.virtualMethodsSize); 538 printf("\n"); 539 540 free(pClassData); 541} 542 543/* 544 * Dump an interface that a class declares to implement. 545 */ 546void dumpInterface(const DexFile* pDexFile, const DexTypeItem* pTypeItem, 547 int i) 548{ 549 const char* interfaceName = 550 dexStringByTypeIdx(pDexFile, pTypeItem->typeIdx); 551 552 if (gOptions.outputFormat == OUTPUT_PLAIN) { 553 printf(" #%d : '%s'\n", i, interfaceName); 554 } else { 555 char* dotted = descriptorToDot(interfaceName); 556 printf("<implements name=\"%s\">\n</implements>\n", dotted); 557 free(dotted); 558 } 559} 560 561/* 562 * Dump the catches table associated with the code. 563 */ 564void dumpCatches(DexFile* pDexFile, const DexCode* pCode) 565{ 566 u4 triesSize = pCode->triesSize; 567 568 if (triesSize == 0) { 569 printf(" catches : (none)\n"); 570 return; 571 } 572 573 printf(" catches : %d\n", triesSize); 574 575 const DexTry* pTries = dexGetTries(pCode); 576 u4 i; 577 578 for (i = 0; i < triesSize; i++) { 579 const DexTry* pTry = &pTries[i]; 580 u4 start = pTry->startAddr; 581 u4 end = start + pTry->insnCount; 582 DexCatchIterator iterator; 583 584 printf(" 0x%04x - 0x%04x\n", start, end); 585 586 dexCatchIteratorInit(&iterator, pCode, pTry->handlerOff); 587 588 for (;;) { 589 DexCatchHandler* handler = dexCatchIteratorNext(&iterator); 590 const char* descriptor; 591 592 if (handler == NULL) { 593 break; 594 } 595 596 descriptor = (handler->typeIdx == kDexNoIndex) ? "<any>" : 597 dexStringByTypeIdx(pDexFile, handler->typeIdx); 598 599 printf(" %s -> 0x%04x\n", descriptor, 600 handler->address); 601 } 602 } 603} 604 605static int dumpPositionsCb(void *cnxt, u4 address, u4 lineNum) 606{ 607 printf(" 0x%04x line=%d\n", address, lineNum); 608 return 0; 609} 610 611/* 612 * Dump the positions list. 613 */ 614void dumpPositions(DexFile* pDexFile, const DexCode* pCode, 615 const DexMethod *pDexMethod) 616{ 617 printf(" positions : \n"); 618 const DexMethodId *pMethodId 619 = dexGetMethodId(pDexFile, pDexMethod->methodIdx); 620 const char *classDescriptor 621 = dexStringByTypeIdx(pDexFile, pMethodId->classIdx); 622 623 dexDecodeDebugInfo(pDexFile, pCode, classDescriptor, pMethodId->protoIdx, 624 pDexMethod->accessFlags, dumpPositionsCb, NULL, NULL); 625} 626 627static void dumpLocalsCb(void *cnxt, u2 reg, u4 startAddress, 628 u4 endAddress, const char *name, const char *descriptor, 629 const char *signature) 630{ 631 printf(" 0x%04x - 0x%04x reg=%d %s %s %s\n", 632 startAddress, endAddress, reg, name, descriptor, 633 signature); 634} 635 636/* 637 * Dump the locals list. 638 */ 639void dumpLocals(DexFile* pDexFile, const DexCode* pCode, 640 const DexMethod *pDexMethod) 641{ 642 printf(" locals : \n"); 643 644 const DexMethodId *pMethodId 645 = dexGetMethodId(pDexFile, pDexMethod->methodIdx); 646 const char *classDescriptor 647 = dexStringByTypeIdx(pDexFile, pMethodId->classIdx); 648 649 dexDecodeDebugInfo(pDexFile, pCode, classDescriptor, pMethodId->protoIdx, 650 pDexMethod->accessFlags, NULL, dumpLocalsCb, NULL); 651} 652 653/* 654 * Get information about a method. 655 */ 656bool getMethodInfo(DexFile* pDexFile, u4 methodIdx, FieldMethodInfo* pMethInfo) 657{ 658 const DexMethodId* pMethodId; 659 660 if (methodIdx >= pDexFile->pHeader->methodIdsSize) 661 return false; 662 663 pMethodId = dexGetMethodId(pDexFile, methodIdx); 664 pMethInfo->name = dexStringById(pDexFile, pMethodId->nameIdx); 665 pMethInfo->signature = dexCopyDescriptorFromMethodId(pDexFile, pMethodId); 666 667 pMethInfo->classDescriptor = 668 dexStringByTypeIdx(pDexFile, pMethodId->classIdx); 669 return true; 670} 671 672/* 673 * Get information about a field. 674 */ 675bool getFieldInfo(DexFile* pDexFile, u4 fieldIdx, FieldMethodInfo* pFieldInfo) 676{ 677 const DexFieldId* pFieldId; 678 679 if (fieldIdx >= pDexFile->pHeader->fieldIdsSize) 680 return false; 681 682 pFieldId = dexGetFieldId(pDexFile, fieldIdx); 683 pFieldInfo->name = dexStringById(pDexFile, pFieldId->nameIdx); 684 pFieldInfo->signature = dexStringByTypeIdx(pDexFile, pFieldId->typeIdx); 685 pFieldInfo->classDescriptor = 686 dexStringByTypeIdx(pDexFile, pFieldId->classIdx); 687 return true; 688} 689 690 691/* 692 * Look up a class' descriptor. 693 */ 694const char* getClassDescriptor(DexFile* pDexFile, u4 classIdx) 695{ 696 return dexStringByTypeIdx(pDexFile, classIdx); 697} 698 699/* 700 * Helper for dumpInstruction(), which builds the string 701 * representation for the index in the given instruction. This will 702 * first try to use the given buffer, but if the result won't fit, 703 * then this will allocate a new buffer to hold the result. A pointer 704 * to the buffer which holds the full result is always returned, and 705 * this can be compared with the one passed in, to see if the result 706 * needs to be free()d. 707 */ 708static char* indexString(DexFile* pDexFile, 709 const DecodedInstruction* pDecInsn, char* buf, size_t bufSize) 710{ 711 int outSize; 712 u4 index; 713 u4 width; 714 715 /* TODO: Make the index *always* be in field B, to simplify this code. */ 716 switch (dexGetFormatFromOpcode(pDecInsn->opcode)) { 717 case kFmt20bc: 718 case kFmt21c: 719 case kFmt35c: 720 case kFmt35ms: 721 case kFmt3rc: 722 case kFmt3rms: 723 case kFmt35mi: 724 case kFmt3rmi: 725 index = pDecInsn->vB; 726 width = 4; 727 break; 728 case kFmt31c: 729 index = pDecInsn->vB; 730 width = 8; 731 break; 732 case kFmt22c: 733 case kFmt22cs: 734 index = pDecInsn->vC; 735 width = 4; 736 break; 737 default: 738 index = 0; 739 width = 4; 740 break; 741 } 742 743 switch (pDecInsn->indexType) { 744 case kIndexUnknown: 745 /* 746 * This function shouldn't ever get called for this type, but do 747 * something sensible here, just to help with debugging. 748 */ 749 outSize = snprintf(buf, bufSize, "<unknown-index>"); 750 break; 751 case kIndexNone: 752 /* 753 * This function shouldn't ever get called for this type, but do 754 * something sensible here, just to help with debugging. 755 */ 756 outSize = snprintf(buf, bufSize, "<no-index>"); 757 break; 758 case kIndexVaries: 759 /* 760 * This one should never show up in a dexdump, so no need to try 761 * to get fancy here. 762 */ 763 outSize = snprintf(buf, bufSize, "<index-varies> // thing@%0*x", 764 width, index); 765 break; 766 case kIndexTypeRef: 767 if (index < pDexFile->pHeader->typeIdsSize) { 768 outSize = snprintf(buf, bufSize, "%s // type@%0*x", 769 getClassDescriptor(pDexFile, index), width, index); 770 } else { 771 outSize = snprintf(buf, bufSize, "<type?> // type@%0*x", width, index); 772 } 773 break; 774 case kIndexStringRef: 775 if (index < pDexFile->pHeader->stringIdsSize) { 776 outSize = snprintf(buf, bufSize, "\"%s\" // string@%0*x", 777 dexStringById(pDexFile, index), width, index); 778 } else { 779 outSize = snprintf(buf, bufSize, "<string?> // string@%0*x", 780 width, index); 781 } 782 break; 783 case kIndexMethodRef: 784 { 785 FieldMethodInfo methInfo; 786 if (getMethodInfo(pDexFile, index, &methInfo)) { 787 outSize = snprintf(buf, bufSize, "%s.%s:%s // method@%0*x", 788 methInfo.classDescriptor, methInfo.name, 789 methInfo.signature, width, index); 790 } else { 791 outSize = snprintf(buf, bufSize, "<method?> // method@%0*x", 792 width, index); 793 } 794 } 795 break; 796 case kIndexFieldRef: 797 { 798 FieldMethodInfo fieldInfo; 799 if (getFieldInfo(pDexFile, index, &fieldInfo)) { 800 outSize = snprintf(buf, bufSize, "%s.%s:%s // field@%0*x", 801 fieldInfo.classDescriptor, fieldInfo.name, 802 fieldInfo.signature, width, index); 803 } else { 804 outSize = snprintf(buf, bufSize, "<field?> // field@%0*x", 805 width, index); 806 } 807 } 808 break; 809 case kIndexInlineMethod: 810 outSize = snprintf(buf, bufSize, "[%0*x] // inline #%0*x", 811 width, index, width, index); 812 break; 813 case kIndexVtableOffset: 814 outSize = snprintf(buf, bufSize, "[%0*x] // vtable #%0*x", 815 width, index, width, index); 816 break; 817 case kIndexFieldOffset: 818 outSize = snprintf(buf, bufSize, "[obj+%0*x]", width, index); 819 break; 820 default: 821 outSize = snprintf(buf, bufSize, "<?>"); 822 break; 823 } 824 825 if (outSize >= (int) bufSize) { 826 /* 827 * The buffer wasn't big enough; allocate and retry. Note: 828 * snprintf() doesn't count the '\0' as part of its returned 829 * size, so we add explicit space for it here. 830 */ 831 outSize++; 832 buf = (char*)malloc(outSize); 833 if (buf == NULL) { 834 return NULL; 835 } 836 return indexString(pDexFile, pDecInsn, buf, outSize); 837 } else { 838 return buf; 839 } 840} 841 842/* 843 * Dump a single instruction. 844 */ 845void dumpInstruction(DexFile* pDexFile, const DexCode* pCode, int insnIdx, 846 int insnWidth, const DecodedInstruction* pDecInsn) 847{ 848 char indexBufChars[200]; 849 char *indexBuf = indexBufChars; 850 const u2* insns = pCode->insns; 851 int i; 852 853 printf("%06x:", ((u1*)insns - pDexFile->baseAddr) + insnIdx*2); 854 for (i = 0; i < 8; i++) { 855 if (i < insnWidth) { 856 if (i == 7) { 857 printf(" ... "); 858 } else { 859 /* print 16-bit value in little-endian order */ 860 const u1* bytePtr = (const u1*) &insns[insnIdx+i]; 861 printf(" %02x%02x", bytePtr[0], bytePtr[1]); 862 } 863 } else { 864 fputs(" ", stdout); 865 } 866 } 867 868 if (pDecInsn->opcode == OP_NOP) { 869 u2 instr = get2LE((const u1*) &insns[insnIdx]); 870 if (instr == kPackedSwitchSignature) { 871 printf("|%04x: packed-switch-data (%d units)", 872 insnIdx, insnWidth); 873 } else if (instr == kSparseSwitchSignature) { 874 printf("|%04x: sparse-switch-data (%d units)", 875 insnIdx, insnWidth); 876 } else if (instr == kArrayDataSignature) { 877 printf("|%04x: array-data (%d units)", 878 insnIdx, insnWidth); 879 } else { 880 printf("|%04x: nop // spacer", insnIdx); 881 } 882 } else { 883 printf("|%04x: %s", insnIdx, dexGetOpcodeName(pDecInsn->opcode)); 884 } 885 886 if (pDecInsn->indexType != kIndexNone) { 887 indexBuf = indexString(pDexFile, pDecInsn, 888 indexBufChars, sizeof(indexBufChars)); 889 } 890 891 switch (dexGetFormatFromOpcode(pDecInsn->opcode)) { 892 case kFmt10x: // op 893 break; 894 case kFmt12x: // op vA, vB 895 printf(" v%d, v%d", pDecInsn->vA, pDecInsn->vB); 896 break; 897 case kFmt11n: // op vA, #+B 898 printf(" v%d, #int %d // #%x", 899 pDecInsn->vA, (s4)pDecInsn->vB, (u1)pDecInsn->vB); 900 break; 901 case kFmt11x: // op vAA 902 printf(" v%d", pDecInsn->vA); 903 break; 904 case kFmt10t: // op +AA 905 case kFmt20t: // op +AAAA 906 { 907 s4 targ = (s4) pDecInsn->vA; 908 printf(" %04x // %c%04x", 909 insnIdx + targ, 910 (targ < 0) ? '-' : '+', 911 (targ < 0) ? -targ : targ); 912 } 913 break; 914 case kFmt22x: // op vAA, vBBBB 915 printf(" v%d, v%d", pDecInsn->vA, pDecInsn->vB); 916 break; 917 case kFmt21t: // op vAA, +BBBB 918 { 919 s4 targ = (s4) pDecInsn->vB; 920 printf(" v%d, %04x // %c%04x", pDecInsn->vA, 921 insnIdx + targ, 922 (targ < 0) ? '-' : '+', 923 (targ < 0) ? -targ : targ); 924 } 925 break; 926 case kFmt21s: // op vAA, #+BBBB 927 printf(" v%d, #int %d // #%x", 928 pDecInsn->vA, (s4)pDecInsn->vB, (u2)pDecInsn->vB); 929 break; 930 case kFmt21h: // op vAA, #+BBBB0000[00000000] 931 // The printed format varies a bit based on the actual opcode. 932 if (pDecInsn->opcode == OP_CONST_HIGH16) { 933 s4 value = pDecInsn->vB << 16; 934 printf(" v%d, #int %d // #%x", 935 pDecInsn->vA, value, (u2)pDecInsn->vB); 936 } else { 937 s8 value = ((s8) pDecInsn->vB) << 48; 938 printf(" v%d, #long %lld // #%x", 939 pDecInsn->vA, value, (u2)pDecInsn->vB); 940 } 941 break; 942 case kFmt21c: // op vAA, thing@BBBB 943 case kFmt31c: // op vAA, thing@BBBBBBBB 944 printf(" v%d, %s", pDecInsn->vA, indexBuf); 945 break; 946 case kFmt23x: // op vAA, vBB, vCC 947 printf(" v%d, v%d, v%d", pDecInsn->vA, pDecInsn->vB, pDecInsn->vC); 948 break; 949 case kFmt22b: // op vAA, vBB, #+CC 950 printf(" v%d, v%d, #int %d // #%02x", 951 pDecInsn->vA, pDecInsn->vB, (s4)pDecInsn->vC, (u1)pDecInsn->vC); 952 break; 953 case kFmt22t: // op vA, vB, +CCCC 954 { 955 s4 targ = (s4) pDecInsn->vC; 956 printf(" v%d, v%d, %04x // %c%04x", pDecInsn->vA, pDecInsn->vB, 957 insnIdx + targ, 958 (targ < 0) ? '-' : '+', 959 (targ < 0) ? -targ : targ); 960 } 961 break; 962 case kFmt22s: // op vA, vB, #+CCCC 963 printf(" v%d, v%d, #int %d // #%04x", 964 pDecInsn->vA, pDecInsn->vB, (s4)pDecInsn->vC, (u2)pDecInsn->vC); 965 break; 966 case kFmt22c: // op vA, vB, thing@CCCC 967 case kFmt22cs: // [opt] op vA, vB, field offset CCCC 968 printf(" v%d, v%d, %s", pDecInsn->vA, pDecInsn->vB, indexBuf); 969 break; 970 case kFmt30t: 971 printf(" #%08x", pDecInsn->vA); 972 break; 973 case kFmt31i: // op vAA, #+BBBBBBBB 974 { 975 /* this is often, but not always, a float */ 976 union { 977 float f; 978 u4 i; 979 } conv; 980 conv.i = pDecInsn->vB; 981 printf(" v%d, #float %f // #%08x", 982 pDecInsn->vA, conv.f, pDecInsn->vB); 983 } 984 break; 985 case kFmt31t: // op vAA, offset +BBBBBBBB 986 printf(" v%d, %08x // +%08x", 987 pDecInsn->vA, insnIdx + pDecInsn->vB, pDecInsn->vB); 988 break; 989 case kFmt32x: // op vAAAA, vBBBB 990 printf(" v%d, v%d", pDecInsn->vA, pDecInsn->vB); 991 break; 992 case kFmt35c: // op {vC, vD, vE, vF, vG}, thing@BBBB 993 case kFmt35ms: // [opt] invoke-virtual+super 994 case kFmt35mi: // [opt] inline invoke 995 { 996 fputs(" {", stdout); 997 for (i = 0; i < (int) pDecInsn->vA; i++) { 998 if (i == 0) 999 printf("v%d", pDecInsn->arg[i]); 1000 else 1001 printf(", v%d", pDecInsn->arg[i]); 1002 } 1003 printf("}, %s", indexBuf); 1004 } 1005 break; 1006 case kFmt3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB 1007 case kFmt3rms: // [opt] invoke-virtual+super/range 1008 case kFmt3rmi: // [opt] execute-inline/range 1009 { 1010 /* 1011 * This doesn't match the "dx" output when some of the args are 1012 * 64-bit values -- dx only shows the first register. 1013 */ 1014 fputs(" {", stdout); 1015 for (i = 0; i < (int) pDecInsn->vA; i++) { 1016 if (i == 0) 1017 printf("v%d", pDecInsn->vC + i); 1018 else 1019 printf(", v%d", pDecInsn->vC + i); 1020 } 1021 printf("}, %s", indexBuf); 1022 } 1023 break; 1024 case kFmt51l: // op vAA, #+BBBBBBBBBBBBBBBB 1025 { 1026 /* this is often, but not always, a double */ 1027 union { 1028 double d; 1029 u8 j; 1030 } conv; 1031 conv.j = pDecInsn->vB_wide; 1032 printf(" v%d, #double %f // #%016llx", 1033 pDecInsn->vA, conv.d, pDecInsn->vB_wide); 1034 } 1035 break; 1036 case kFmt00x: // unknown op or breakpoint 1037 break; 1038 default: 1039 printf(" ???"); 1040 break; 1041 } 1042 1043 putchar('\n'); 1044 1045 if (indexBuf != indexBufChars) { 1046 free(indexBuf); 1047 } 1048} 1049 1050/* 1051 * Dump a bytecode disassembly. 1052 */ 1053void dumpBytecodes(DexFile* pDexFile, const DexMethod* pDexMethod) 1054{ 1055 const DexCode* pCode = dexGetCode(pDexFile, pDexMethod); 1056 const u2* insns; 1057 int insnIdx; 1058 FieldMethodInfo methInfo; 1059 int startAddr; 1060 char* className = NULL; 1061 1062 assert(pCode->insnsSize > 0); 1063 insns = pCode->insns; 1064 1065 getMethodInfo(pDexFile, pDexMethod->methodIdx, &methInfo); 1066 startAddr = ((u1*)pCode - pDexFile->baseAddr); 1067 className = descriptorToDot(methInfo.classDescriptor); 1068 1069 printf("%06x: |[%06x] %s.%s:%s\n", 1070 startAddr, startAddr, 1071 className, methInfo.name, methInfo.signature); 1072 1073 insnIdx = 0; 1074 while (insnIdx < (int) pCode->insnsSize) { 1075 int insnWidth; 1076 DecodedInstruction decInsn; 1077 u2 instr; 1078 1079 /* 1080 * Note: This code parallels the function 1081 * dexGetWidthFromInstruction() in InstrUtils.c, but this version 1082 * can deal with data in either endianness. 1083 * 1084 * TODO: Figure out if this really matters, and possibly change 1085 * this to just use dexGetWidthFromInstruction(). 1086 */ 1087 instr = get2LE((const u1*)insns); 1088 if (instr == kPackedSwitchSignature) { 1089 insnWidth = 4 + get2LE((const u1*)(insns+1)) * 2; 1090 } else if (instr == kSparseSwitchSignature) { 1091 insnWidth = 2 + get2LE((const u1*)(insns+1)) * 4; 1092 } else if (instr == kArrayDataSignature) { 1093 int width = get2LE((const u1*)(insns+1)); 1094 int size = get2LE((const u1*)(insns+2)) | 1095 (get2LE((const u1*)(insns+3))<<16); 1096 // The plus 1 is to round up for odd size and width. 1097 insnWidth = 4 + ((size * width) + 1) / 2; 1098 } else { 1099 Opcode opcode = dexOpcodeFromCodeUnit(instr); 1100 insnWidth = dexGetWidthFromOpcode(opcode); 1101 if (insnWidth == 0) { 1102 fprintf(stderr, 1103 "GLITCH: zero-width instruction at idx=0x%04x\n", insnIdx); 1104 break; 1105 } 1106 } 1107 1108 dexDecodeInstruction(insns, &decInsn); 1109 dumpInstruction(pDexFile, pCode, insnIdx, insnWidth, &decInsn); 1110 1111 insns += insnWidth; 1112 insnIdx += insnWidth; 1113 } 1114 1115 free(className); 1116} 1117 1118/* 1119 * Dump a "code" struct. 1120 */ 1121void dumpCode(DexFile* pDexFile, const DexMethod* pDexMethod) 1122{ 1123 const DexCode* pCode = dexGetCode(pDexFile, pDexMethod); 1124 1125 printf(" registers : %d\n", pCode->registersSize); 1126 printf(" ins : %d\n", pCode->insSize); 1127 printf(" outs : %d\n", pCode->outsSize); 1128 printf(" insns size : %d 16-bit code units\n", pCode->insnsSize); 1129 1130 if (gOptions.disassemble) 1131 dumpBytecodes(pDexFile, pDexMethod); 1132 1133 dumpCatches(pDexFile, pCode); 1134 /* both of these are encoded in debug info */ 1135 dumpPositions(pDexFile, pCode, pDexMethod); 1136 dumpLocals(pDexFile, pCode, pDexMethod); 1137} 1138 1139/* 1140 * Dump a method. 1141 */ 1142void dumpMethod(DexFile* pDexFile, const DexMethod* pDexMethod, int i) 1143{ 1144 const DexMethodId* pMethodId; 1145 const char* backDescriptor; 1146 const char* name; 1147 char* typeDescriptor = NULL; 1148 char* accessStr = NULL; 1149 1150 if (gOptions.exportsOnly && 1151 (pDexMethod->accessFlags & (ACC_PUBLIC | ACC_PROTECTED)) == 0) 1152 { 1153 return; 1154 } 1155 1156 pMethodId = dexGetMethodId(pDexFile, pDexMethod->methodIdx); 1157 name = dexStringById(pDexFile, pMethodId->nameIdx); 1158 typeDescriptor = dexCopyDescriptorFromMethodId(pDexFile, pMethodId); 1159 1160 backDescriptor = dexStringByTypeIdx(pDexFile, pMethodId->classIdx); 1161 1162 accessStr = createAccessFlagStr(pDexMethod->accessFlags, 1163 kAccessForMethod); 1164 1165 if (gOptions.outputFormat == OUTPUT_PLAIN) { 1166 printf(" #%d : (in %s)\n", i, backDescriptor); 1167 printf(" name : '%s'\n", name); 1168 printf(" type : '%s'\n", typeDescriptor); 1169 printf(" access : 0x%04x (%s)\n", 1170 pDexMethod->accessFlags, accessStr); 1171 1172 if (pDexMethod->codeOff == 0) { 1173 printf(" code : (none)\n"); 1174 } else { 1175 printf(" code -\n"); 1176 dumpCode(pDexFile, pDexMethod); 1177 } 1178 1179 if (gOptions.disassemble) 1180 putchar('\n'); 1181 } else if (gOptions.outputFormat == OUTPUT_XML) { 1182 bool constructor = (name[0] == '<'); 1183 1184 if (constructor) { 1185 char* tmp; 1186 1187 tmp = descriptorClassToDot(backDescriptor); 1188 printf("<constructor name=\"%s\"\n", tmp); 1189 free(tmp); 1190 1191 tmp = descriptorToDot(backDescriptor); 1192 printf(" type=\"%s\"\n", tmp); 1193 free(tmp); 1194 } else { 1195 printf("<method name=\"%s\"\n", name); 1196 1197 const char* returnType = strrchr(typeDescriptor, ')'); 1198 if (returnType == NULL) { 1199 fprintf(stderr, "bad method type descriptor '%s'\n", 1200 typeDescriptor); 1201 goto bail; 1202 } 1203 1204 char* tmp = descriptorToDot(returnType+1); 1205 printf(" return=\"%s\"\n", tmp); 1206 free(tmp); 1207 1208 printf(" abstract=%s\n", 1209 quotedBool((pDexMethod->accessFlags & ACC_ABSTRACT) != 0)); 1210 printf(" native=%s\n", 1211 quotedBool((pDexMethod->accessFlags & ACC_NATIVE) != 0)); 1212 1213 bool isSync = 1214 (pDexMethod->accessFlags & ACC_SYNCHRONIZED) != 0 || 1215 (pDexMethod->accessFlags & ACC_DECLARED_SYNCHRONIZED) != 0; 1216 printf(" synchronized=%s\n", quotedBool(isSync)); 1217 } 1218 1219 printf(" static=%s\n", 1220 quotedBool((pDexMethod->accessFlags & ACC_STATIC) != 0)); 1221 printf(" final=%s\n", 1222 quotedBool((pDexMethod->accessFlags & ACC_FINAL) != 0)); 1223 // "deprecated=" not knowable w/o parsing annotations 1224 printf(" visibility=%s\n", 1225 quotedVisibility(pDexMethod->accessFlags)); 1226 1227 printf(">\n"); 1228 1229 /* 1230 * Parameters. 1231 */ 1232 if (typeDescriptor[0] != '(') { 1233 fprintf(stderr, "ERROR: bad descriptor '%s'\n", typeDescriptor); 1234 goto bail; 1235 } 1236 1237 char tmpBuf[strlen(typeDescriptor)+1]; /* more than big enough */ 1238 int argNum = 0; 1239 1240 const char* base = typeDescriptor+1; 1241 1242 while (*base != ')') { 1243 char* cp = tmpBuf; 1244 1245 while (*base == '[') 1246 *cp++ = *base++; 1247 1248 if (*base == 'L') { 1249 /* copy through ';' */ 1250 do { 1251 *cp = *base++; 1252 } while (*cp++ != ';'); 1253 } else { 1254 /* primitive char, copy it */ 1255 if (strchr("ZBCSIFJD", *base) == NULL) { 1256 fprintf(stderr, "ERROR: bad method signature '%s'\n", base); 1257 goto bail; 1258 } 1259 *cp++ = *base++; 1260 } 1261 1262 /* null terminate and display */ 1263 *cp++ = '\0'; 1264 1265 char* tmp = descriptorToDot(tmpBuf); 1266 printf("<parameter name=\"arg%d\" type=\"%s\">\n</parameter>\n", 1267 argNum++, tmp); 1268 free(tmp); 1269 } 1270 1271 if (constructor) 1272 printf("</constructor>\n"); 1273 else 1274 printf("</method>\n"); 1275 } 1276 1277bail: 1278 free(typeDescriptor); 1279 free(accessStr); 1280} 1281 1282/* 1283 * Dump a static (class) field. 1284 */ 1285void dumpSField(const DexFile* pDexFile, const DexField* pSField, int i) 1286{ 1287 const DexFieldId* pFieldId; 1288 const char* backDescriptor; 1289 const char* name; 1290 const char* typeDescriptor; 1291 char* accessStr; 1292 1293 if (gOptions.exportsOnly && 1294 (pSField->accessFlags & (ACC_PUBLIC | ACC_PROTECTED)) == 0) 1295 { 1296 return; 1297 } 1298 1299 pFieldId = dexGetFieldId(pDexFile, pSField->fieldIdx); 1300 name = dexStringById(pDexFile, pFieldId->nameIdx); 1301 typeDescriptor = dexStringByTypeIdx(pDexFile, pFieldId->typeIdx); 1302 backDescriptor = dexStringByTypeIdx(pDexFile, pFieldId->classIdx); 1303 1304 accessStr = createAccessFlagStr(pSField->accessFlags, kAccessForField); 1305 1306 if (gOptions.outputFormat == OUTPUT_PLAIN) { 1307 printf(" #%d : (in %s)\n", i, backDescriptor); 1308 printf(" name : '%s'\n", name); 1309 printf(" type : '%s'\n", typeDescriptor); 1310 printf(" access : 0x%04x (%s)\n", 1311 pSField->accessFlags, accessStr); 1312 } else if (gOptions.outputFormat == OUTPUT_XML) { 1313 char* tmp; 1314 1315 printf("<field name=\"%s\"\n", name); 1316 1317 tmp = descriptorToDot(typeDescriptor); 1318 printf(" type=\"%s\"\n", tmp); 1319 free(tmp); 1320 1321 printf(" transient=%s\n", 1322 quotedBool((pSField->accessFlags & ACC_TRANSIENT) != 0)); 1323 printf(" volatile=%s\n", 1324 quotedBool((pSField->accessFlags & ACC_VOLATILE) != 0)); 1325 // "value=" not knowable w/o parsing annotations 1326 printf(" static=%s\n", 1327 quotedBool((pSField->accessFlags & ACC_STATIC) != 0)); 1328 printf(" final=%s\n", 1329 quotedBool((pSField->accessFlags & ACC_FINAL) != 0)); 1330 // "deprecated=" not knowable w/o parsing annotations 1331 printf(" visibility=%s\n", 1332 quotedVisibility(pSField->accessFlags)); 1333 printf(">\n</field>\n"); 1334 } 1335 1336 free(accessStr); 1337} 1338 1339/* 1340 * Dump an instance field. 1341 */ 1342void dumpIField(const DexFile* pDexFile, const DexField* pIField, int i) 1343{ 1344 dumpSField(pDexFile, pIField, i); 1345} 1346 1347/* 1348 * Dump the class. 1349 * 1350 * Note "idx" is a DexClassDef index, not a DexTypeId index. 1351 * 1352 * If "*pLastPackage" is NULL or does not match the current class' package, 1353 * the value will be replaced with a newly-allocated string. 1354 */ 1355void dumpClass(DexFile* pDexFile, int idx, char** pLastPackage) 1356{ 1357 const DexTypeList* pInterfaces; 1358 const DexClassDef* pClassDef; 1359 DexClassData* pClassData = NULL; 1360 const u1* pEncodedData; 1361 const char* fileName; 1362 const char* classDescriptor; 1363 const char* superclassDescriptor; 1364 char* accessStr = NULL; 1365 int i; 1366 1367 pClassDef = dexGetClassDef(pDexFile, idx); 1368 1369 if (gOptions.exportsOnly && (pClassDef->accessFlags & ACC_PUBLIC) == 0) { 1370 //printf("<!-- omitting non-public class %s -->\n", 1371 // classDescriptor); 1372 goto bail; 1373 } 1374 1375 pEncodedData = dexGetClassData(pDexFile, pClassDef); 1376 pClassData = dexReadAndVerifyClassData(&pEncodedData, NULL); 1377 1378 if (pClassData == NULL) { 1379 printf("Trouble reading class data (#%d)\n", idx); 1380 goto bail; 1381 } 1382 1383 classDescriptor = dexStringByTypeIdx(pDexFile, pClassDef->classIdx); 1384 1385 /* 1386 * For the XML output, show the package name. Ideally we'd gather 1387 * up the classes, sort them, and dump them alphabetically so the 1388 * package name wouldn't jump around, but that's not a great plan 1389 * for something that needs to run on the device. 1390 */ 1391 if (!(classDescriptor[0] == 'L' && 1392 classDescriptor[strlen(classDescriptor)-1] == ';')) 1393 { 1394 /* arrays and primitives should not be defined explicitly */ 1395 fprintf(stderr, "Malformed class name '%s'\n", classDescriptor); 1396 /* keep going? */ 1397 } else if (gOptions.outputFormat == OUTPUT_XML) { 1398 char* mangle; 1399 char* lastSlash; 1400 char* cp; 1401 1402 mangle = strdup(classDescriptor + 1); 1403 mangle[strlen(mangle)-1] = '\0'; 1404 1405 /* reduce to just the package name */ 1406 lastSlash = strrchr(mangle, '/'); 1407 if (lastSlash != NULL) { 1408 *lastSlash = '\0'; 1409 } else { 1410 *mangle = '\0'; 1411 } 1412 1413 for (cp = mangle; *cp != '\0'; cp++) { 1414 if (*cp == '/') 1415 *cp = '.'; 1416 } 1417 1418 if (*pLastPackage == NULL || strcmp(mangle, *pLastPackage) != 0) { 1419 /* start of a new package */ 1420 if (*pLastPackage != NULL) 1421 printf("</package>\n"); 1422 printf("<package name=\"%s\"\n>\n", mangle); 1423 free(*pLastPackage); 1424 *pLastPackage = mangle; 1425 } else { 1426 free(mangle); 1427 } 1428 } 1429 1430 accessStr = createAccessFlagStr(pClassDef->accessFlags, kAccessForClass); 1431 1432 if (pClassDef->superclassIdx == kDexNoIndex) { 1433 superclassDescriptor = NULL; 1434 } else { 1435 superclassDescriptor = 1436 dexStringByTypeIdx(pDexFile, pClassDef->superclassIdx); 1437 } 1438 1439 if (gOptions.outputFormat == OUTPUT_PLAIN) { 1440 printf("Class #%d -\n", idx); 1441 printf(" Class descriptor : '%s'\n", classDescriptor); 1442 printf(" Access flags : 0x%04x (%s)\n", 1443 pClassDef->accessFlags, accessStr); 1444 1445 if (superclassDescriptor != NULL) 1446 printf(" Superclass : '%s'\n", superclassDescriptor); 1447 1448 printf(" Interfaces -\n"); 1449 } else { 1450 char* tmp; 1451 1452 tmp = descriptorClassToDot(classDescriptor); 1453 printf("<class name=\"%s\"\n", tmp); 1454 free(tmp); 1455 1456 if (superclassDescriptor != NULL) { 1457 tmp = descriptorToDot(superclassDescriptor); 1458 printf(" extends=\"%s\"\n", tmp); 1459 free(tmp); 1460 } 1461 printf(" abstract=%s\n", 1462 quotedBool((pClassDef->accessFlags & ACC_ABSTRACT) != 0)); 1463 printf(" static=%s\n", 1464 quotedBool((pClassDef->accessFlags & ACC_STATIC) != 0)); 1465 printf(" final=%s\n", 1466 quotedBool((pClassDef->accessFlags & ACC_FINAL) != 0)); 1467 // "deprecated=" not knowable w/o parsing annotations 1468 printf(" visibility=%s\n", 1469 quotedVisibility(pClassDef->accessFlags)); 1470 printf(">\n"); 1471 } 1472 pInterfaces = dexGetInterfacesList(pDexFile, pClassDef); 1473 if (pInterfaces != NULL) { 1474 for (i = 0; i < (int) pInterfaces->size; i++) 1475 dumpInterface(pDexFile, dexGetTypeItem(pInterfaces, i), i); 1476 } 1477 1478 if (gOptions.outputFormat == OUTPUT_PLAIN) 1479 printf(" Static fields -\n"); 1480 for (i = 0; i < (int) pClassData->header.staticFieldsSize; i++) { 1481 dumpSField(pDexFile, &pClassData->staticFields[i], i); 1482 } 1483 1484 if (gOptions.outputFormat == OUTPUT_PLAIN) 1485 printf(" Instance fields -\n"); 1486 for (i = 0; i < (int) pClassData->header.instanceFieldsSize; i++) { 1487 dumpIField(pDexFile, &pClassData->instanceFields[i], i); 1488 } 1489 1490 if (gOptions.outputFormat == OUTPUT_PLAIN) 1491 printf(" Direct methods -\n"); 1492 for (i = 0; i < (int) pClassData->header.directMethodsSize; i++) { 1493 dumpMethod(pDexFile, &pClassData->directMethods[i], i); 1494 } 1495 1496 if (gOptions.outputFormat == OUTPUT_PLAIN) 1497 printf(" Virtual methods -\n"); 1498 for (i = 0; i < (int) pClassData->header.virtualMethodsSize; i++) { 1499 dumpMethod(pDexFile, &pClassData->virtualMethods[i], i); 1500 } 1501 1502 // TODO: Annotations. 1503 1504 if (pClassDef->sourceFileIdx != kDexNoIndex) 1505 fileName = dexStringById(pDexFile, pClassDef->sourceFileIdx); 1506 else 1507 fileName = "unknown"; 1508 1509 if (gOptions.outputFormat == OUTPUT_PLAIN) { 1510 printf(" source_file_idx : %d (%s)\n", 1511 pClassDef->sourceFileIdx, fileName); 1512 printf("\n"); 1513 } 1514 1515 if (gOptions.outputFormat == OUTPUT_XML) { 1516 printf("</class>\n"); 1517 } 1518 1519bail: 1520 free(pClassData); 1521 free(accessStr); 1522} 1523 1524 1525/* 1526 * Advance "ptr" to ensure 32-bit alignment. 1527 */ 1528static inline const u1* align32(const u1* ptr) 1529{ 1530 return (u1*) (((uintptr_t) ptr + 3) & ~0x03); 1531} 1532 1533 1534/* 1535 * Dump a map in the "differential" format. 1536 * 1537 * TODO: show a hex dump of the compressed data. (We can show the 1538 * uncompressed data if we move the compression code to libdex; otherwise 1539 * it's too complex to merit a fast & fragile implementation here.) 1540 */ 1541void dumpDifferentialCompressedMap(const u1** pData) 1542{ 1543 const u1* data = *pData; 1544 const u1* dataStart = data -1; // format byte already removed 1545 u1 regWidth; 1546 u2 numEntries; 1547 1548 /* standard header */ 1549 regWidth = *data++; 1550 numEntries = *data++; 1551 numEntries |= (*data++) << 8; 1552 1553 /* compressed data begins with the compressed data length */ 1554 int compressedLen = readUnsignedLeb128(&data); 1555 int addrWidth = 1; 1556 if ((*data & 0x80) != 0) 1557 addrWidth++; 1558 1559 int origLen = 4 + (addrWidth + regWidth) * numEntries; 1560 int compLen = (data - dataStart) + compressedLen; 1561 1562 printf(" (differential compression %d -> %d [%d -> %d])\n", 1563 origLen, compLen, 1564 (addrWidth + regWidth) * numEntries, compressedLen); 1565 1566 /* skip past end of entry */ 1567 data += compressedLen; 1568 1569 *pData = data; 1570} 1571 1572/* 1573 * Dump register map contents of the current method. 1574 * 1575 * "*pData" should point to the start of the register map data. Advances 1576 * "*pData" to the start of the next map. 1577 */ 1578void dumpMethodMap(DexFile* pDexFile, const DexMethod* pDexMethod, int idx, 1579 const u1** pData) 1580{ 1581 const u1* data = *pData; 1582 const DexMethodId* pMethodId; 1583 const char* name; 1584 int offset = data - (u1*) pDexFile->pOptHeader; 1585 1586 pMethodId = dexGetMethodId(pDexFile, pDexMethod->methodIdx); 1587 name = dexStringById(pDexFile, pMethodId->nameIdx); 1588 printf(" #%d: 0x%08x %s\n", idx, offset, name); 1589 1590 u1 format; 1591 int addrWidth; 1592 1593 format = *data++; 1594 if (format == 1) { /* kRegMapFormatNone */ 1595 /* no map */ 1596 printf(" (no map)\n"); 1597 addrWidth = 0; 1598 } else if (format == 2) { /* kRegMapFormatCompact8 */ 1599 addrWidth = 1; 1600 } else if (format == 3) { /* kRegMapFormatCompact16 */ 1601 addrWidth = 2; 1602 } else if (format == 4) { /* kRegMapFormatDifferential */ 1603 dumpDifferentialCompressedMap(&data); 1604 goto bail; 1605 } else { 1606 printf(" (unknown format %d!)\n", format); 1607 /* don't know how to skip data; failure will cascade to end of class */ 1608 goto bail; 1609 } 1610 1611 if (addrWidth > 0) { 1612 u1 regWidth; 1613 u2 numEntries; 1614 int idx, addr, byte; 1615 1616 regWidth = *data++; 1617 numEntries = *data++; 1618 numEntries |= (*data++) << 8; 1619 1620 for (idx = 0; idx < numEntries; idx++) { 1621 addr = *data++; 1622 if (addrWidth > 1) 1623 addr |= (*data++) << 8; 1624 1625 printf(" %4x:", addr); 1626 for (byte = 0; byte < regWidth; byte++) { 1627 printf(" %02x", *data++); 1628 } 1629 printf("\n"); 1630 } 1631 } 1632 1633bail: 1634 //if (addrWidth >= 0) 1635 // *pData = align32(data); 1636 *pData = data; 1637} 1638 1639/* 1640 * Dump the contents of the register map area. 1641 * 1642 * These are only present in optimized DEX files, and the structure is 1643 * not really exposed to other parts of the VM itself. We're going to 1644 * dig through them here, but this is pretty fragile. DO NOT rely on 1645 * this or derive other code from it. 1646 */ 1647void dumpRegisterMaps(DexFile* pDexFile) 1648{ 1649 const u1* pClassPool = (const u1*)pDexFile->pRegisterMapPool; 1650 const u4* classOffsets; 1651 const u1* ptr; 1652 u4 numClasses; 1653 int baseFileOffset = (u1*) pClassPool - (u1*) pDexFile->pOptHeader; 1654 int idx; 1655 1656 if (pClassPool == NULL) { 1657 printf("No register maps found\n"); 1658 return; 1659 } 1660 1661 ptr = pClassPool; 1662 numClasses = get4LE(ptr); 1663 ptr += sizeof(u4); 1664 classOffsets = (const u4*) ptr; 1665 1666 printf("RMAP begins at offset 0x%07x\n", baseFileOffset); 1667 printf("Maps for %d classes\n", numClasses); 1668 for (idx = 0; idx < (int) numClasses; idx++) { 1669 const DexClassDef* pClassDef; 1670 const char* classDescriptor; 1671 1672 pClassDef = dexGetClassDef(pDexFile, idx); 1673 classDescriptor = dexStringByTypeIdx(pDexFile, pClassDef->classIdx); 1674 1675 printf("%4d: +%d (0x%08x) %s\n", idx, classOffsets[idx], 1676 baseFileOffset + classOffsets[idx], classDescriptor); 1677 1678 if (classOffsets[idx] == 0) 1679 continue; 1680 1681 /* 1682 * What follows is a series of RegisterMap entries, one for every 1683 * direct method, then one for every virtual method. 1684 */ 1685 DexClassData* pClassData; 1686 const u1* pEncodedData; 1687 const u1* data = (u1*) pClassPool + classOffsets[idx]; 1688 u2 methodCount; 1689 int i; 1690 1691 pEncodedData = dexGetClassData(pDexFile, pClassDef); 1692 pClassData = dexReadAndVerifyClassData(&pEncodedData, NULL); 1693 if (pClassData == NULL) { 1694 fprintf(stderr, "Trouble reading class data\n"); 1695 continue; 1696 } 1697 1698 methodCount = *data++; 1699 methodCount |= (*data++) << 8; 1700 data += 2; /* two pad bytes follow methodCount */ 1701 if (methodCount != pClassData->header.directMethodsSize 1702 + pClassData->header.virtualMethodsSize) 1703 { 1704 printf("NOTE: method count discrepancy (%d != %d + %d)\n", 1705 methodCount, pClassData->header.directMethodsSize, 1706 pClassData->header.virtualMethodsSize); 1707 /* this is bad, but keep going anyway */ 1708 } 1709 1710 printf(" direct methods: %d\n", 1711 pClassData->header.directMethodsSize); 1712 for (i = 0; i < (int) pClassData->header.directMethodsSize; i++) { 1713 dumpMethodMap(pDexFile, &pClassData->directMethods[i], i, &data); 1714 } 1715 1716 printf(" virtual methods: %d\n", 1717 pClassData->header.virtualMethodsSize); 1718 for (i = 0; i < (int) pClassData->header.virtualMethodsSize; i++) { 1719 dumpMethodMap(pDexFile, &pClassData->virtualMethods[i], i, &data); 1720 } 1721 1722 free(pClassData); 1723 } 1724} 1725 1726/* 1727 * Dump the requested sections of the file. 1728 */ 1729void processDexFile(const char* fileName, DexFile* pDexFile) 1730{ 1731 char* package = NULL; 1732 int i; 1733 1734 if (gOptions.verbose) { 1735 printf("Opened '%s', DEX version '%.3s'\n", fileName, 1736 pDexFile->pHeader->magic +4); 1737 } 1738 1739 if (gOptions.dumpRegisterMaps) { 1740 dumpRegisterMaps(pDexFile); 1741 return; 1742 } 1743 1744 if (gOptions.showFileHeaders) { 1745 dumpFileHeader(pDexFile); 1746 dumpOptDirectory(pDexFile); 1747 } 1748 1749 if (gOptions.outputFormat == OUTPUT_XML) 1750 printf("<api>\n"); 1751 1752 for (i = 0; i < (int) pDexFile->pHeader->classDefsSize; i++) { 1753 if (gOptions.showSectionHeaders) 1754 dumpClassDef(pDexFile, i); 1755 1756 dumpClass(pDexFile, i, &package); 1757 } 1758 1759 /* free the last one allocated */ 1760 if (package != NULL) { 1761 printf("</package>\n"); 1762 free(package); 1763 } 1764 1765 if (gOptions.outputFormat == OUTPUT_XML) 1766 printf("</api>\n"); 1767} 1768 1769 1770/* 1771 * Process one file. 1772 */ 1773int process(const char* fileName) 1774{ 1775 DexFile* pDexFile = NULL; 1776 MemMapping map; 1777 bool mapped = false; 1778 int result = -1; 1779 1780 if (gOptions.verbose) 1781 printf("Processing '%s'...\n", fileName); 1782 1783 if (dexOpenAndMap(fileName, gOptions.tempFileName, &map, false) != 0) { 1784 return result; 1785 } 1786 mapped = true; 1787 1788 int flags = kDexParseVerifyChecksum; 1789 if (gOptions.ignoreBadChecksum) 1790 flags |= kDexParseContinueOnError; 1791 1792 pDexFile = dexFileParse((u1*)map.addr, map.length, flags); 1793 if (pDexFile == NULL) { 1794 fprintf(stderr, "ERROR: DEX parse failed\n"); 1795 goto bail; 1796 } 1797 1798 if (gOptions.checksumOnly) { 1799 printf("Checksum verified\n"); 1800 } else { 1801 processDexFile(fileName, pDexFile); 1802 } 1803 1804 result = 0; 1805 1806bail: 1807 if (mapped) 1808 sysReleaseShmem(&map); 1809 if (pDexFile != NULL) 1810 dexFileFree(pDexFile); 1811 return result; 1812} 1813 1814 1815/* 1816 * Show usage. 1817 */ 1818void usage(void) 1819{ 1820 fprintf(stderr, "Copyright (C) 2007 The Android Open Source Project\n\n"); 1821 fprintf(stderr, 1822 "%s: [-c] [-d] [-f] [-h] [-i] [-l layout] [-m] [-t tempfile] dexfile...\n", 1823 gProgName); 1824 fprintf(stderr, "\n"); 1825 fprintf(stderr, " -c : verify checksum and exit\n"); 1826 fprintf(stderr, " -d : disassemble code sections\n"); 1827 fprintf(stderr, " -f : display summary information from file header\n"); 1828 fprintf(stderr, " -h : display file header details\n"); 1829 fprintf(stderr, " -i : ignore checksum failures\n"); 1830 fprintf(stderr, " -l : output layout, either 'plain' or 'xml'\n"); 1831 fprintf(stderr, " -m : dump register maps (and nothing else)\n"); 1832 fprintf(stderr, " -t : temp file name (defaults to /sdcard/dex-temp-*)\n"); 1833} 1834 1835/* 1836 * Parse args. 1837 * 1838 * I'm not using getopt_long() because we may not have it in libc. 1839 */ 1840int main(int argc, char* const argv[]) 1841{ 1842 bool wantUsage = false; 1843 int ic; 1844 1845 memset(&gOptions, 0, sizeof(gOptions)); 1846 gOptions.verbose = true; 1847 1848 while (1) { 1849 ic = getopt(argc, argv, "cdfhil:mt:"); 1850 if (ic < 0) 1851 break; 1852 1853 switch (ic) { 1854 case 'c': // verify the checksum then exit 1855 gOptions.checksumOnly = true; 1856 break; 1857 case 'd': // disassemble Dalvik instructions 1858 gOptions.disassemble = true; 1859 break; 1860 case 'f': // dump outer file header 1861 gOptions.showFileHeaders = true; 1862 break; 1863 case 'h': // dump section headers, i.e. all meta-data 1864 gOptions.showSectionHeaders = true; 1865 break; 1866 case 'i': // continue even if checksum is bad 1867 gOptions.ignoreBadChecksum = true; 1868 break; 1869 case 'l': // layout 1870 if (strcmp(optarg, "plain") == 0) { 1871 gOptions.outputFormat = OUTPUT_PLAIN; 1872 } else if (strcmp(optarg, "xml") == 0) { 1873 gOptions.outputFormat = OUTPUT_XML; 1874 gOptions.verbose = false; 1875 gOptions.exportsOnly = true; 1876 } else { 1877 wantUsage = true; 1878 } 1879 break; 1880 case 'm': // dump register maps only 1881 gOptions.dumpRegisterMaps = true; 1882 break; 1883 case 't': // temp file, used when opening compressed Jar 1884 gOptions.tempFileName = optarg; 1885 break; 1886 default: 1887 wantUsage = true; 1888 break; 1889 } 1890 } 1891 1892 if (optind == argc) { 1893 fprintf(stderr, "%s: no file specified\n", gProgName); 1894 wantUsage = true; 1895 } 1896 1897 if (gOptions.checksumOnly && gOptions.ignoreBadChecksum) { 1898 fprintf(stderr, "Can't specify both -c and -i\n"); 1899 wantUsage = true; 1900 } 1901 1902 if (wantUsage) { 1903 usage(); 1904 return 2; 1905 } 1906 1907 int result = 0; 1908 while (optind < argc) { 1909 result |= process(argv[optind++]); 1910 } 1911 1912 return (result != 0); 1913} 1914