blob: 52e6c023fe8229eb9c7df56b9ac2709b78a404a8 [file] [log] [blame]
Aart Bik69ae54a2015-07-01 14:52:26 -07001/*
2 * Copyright (C) 2015 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 * Implementation file of the dexdump utility.
17 *
18 * This is a re-implementation of the original dexdump utility that was
19 * based on Dalvik functions in libdex into a new dexdump that is now
20 * based on Art functions in libart instead. The output is identical to
21 * the original for correct DEX files. Error messages may differ, however.
22 * Also, ODEX files are no longer supported.
23 *
24 * The dexdump tool is intended to mimic objdump. When possible, use
25 * similar command-line arguments.
26 *
27 * Differences between XML output and the "current.xml" file:
28 * - classes in same package are not all grouped together; nothing is sorted
29 * - no "deprecated" on fields and methods
30 * - no "value" on fields
31 * - no parameter names
32 * - no generic signatures on parameters, e.g. type="java.lang.Class<?>"
33 * - class shows declared fields and methods; does not show inherited fields
34 */
35
36#include "dexdump.h"
37
38#include <inttypes.h>
39#include <stdio.h>
40
Andreas Gampe5073fed2015-08-10 11:40:25 -070041#include <iostream>
Aart Bik69ae54a2015-07-01 14:52:26 -070042#include <memory>
Andreas Gampe5073fed2015-08-10 11:40:25 -070043#include <sstream>
Aart Bik69ae54a2015-07-01 14:52:26 -070044#include <vector>
45
46#include "dex_file-inl.h"
47#include "dex_instruction-inl.h"
Andreas Gampe5073fed2015-08-10 11:40:25 -070048#include "utils.h"
Aart Bik69ae54a2015-07-01 14:52:26 -070049
50namespace art {
51
52/*
53 * Options parsed in main driver.
54 */
55struct Options gOptions;
56
57/*
Aart Bik4e149602015-07-09 11:45:28 -070058 * Output file. Defaults to stdout.
Aart Bik69ae54a2015-07-01 14:52:26 -070059 */
60FILE* gOutFile = stdout;
61
62/*
63 * Data types that match the definitions in the VM specification.
64 */
65typedef uint8_t u1;
66typedef uint16_t u2;
67typedef uint32_t u4;
68typedef uint64_t u8;
Aart Bik69ae54a2015-07-01 14:52:26 -070069typedef int32_t s4;
70typedef int64_t s8;
71
72/*
73 * Basic information about a field or a method.
74 */
75struct FieldMethodInfo {
76 const char* classDescriptor;
77 const char* name;
78 const char* signature;
79};
80
81/*
82 * Flags for use with createAccessFlagStr().
83 */
84enum AccessFor {
85 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
86};
87const int kNumFlags = 18;
88
89/*
90 * Gets 2 little-endian bytes.
91 */
92static inline u2 get2LE(unsigned char const* pSrc) {
93 return pSrc[0] | (pSrc[1] << 8);
94}
95
96/*
97 * Converts a single-character primitive type into human-readable form.
98 */
99static const char* primitiveTypeLabel(char typeChar) {
100 switch (typeChar) {
101 case 'B': return "byte";
102 case 'C': return "char";
103 case 'D': return "double";
104 case 'F': return "float";
105 case 'I': return "int";
106 case 'J': return "long";
107 case 'S': return "short";
108 case 'V': return "void";
109 case 'Z': return "boolean";
110 default: return "UNKNOWN";
111 } // switch
112}
113
114/*
115 * Converts a type descriptor to human-readable "dotted" form. For
116 * example, "Ljava/lang/String;" becomes "java.lang.String", and
117 * "[I" becomes "int[]". Also converts '$' to '.', which means this
118 * form can't be converted back to a descriptor.
119 */
120static char* descriptorToDot(const char* str) {
121 int targetLen = strlen(str);
122 int offset = 0;
123
124 // Strip leading [s; will be added to end.
125 while (targetLen > 1 && str[offset] == '[') {
126 offset++;
127 targetLen--;
128 } // while
129
130 const int arrayDepth = offset;
131
132 if (targetLen == 1) {
133 // Primitive type.
134 str = primitiveTypeLabel(str[offset]);
135 offset = 0;
136 targetLen = strlen(str);
137 } else {
138 // Account for leading 'L' and trailing ';'.
139 if (targetLen >= 2 && str[offset] == 'L' &&
140 str[offset + targetLen - 1] == ';') {
141 targetLen -= 2;
142 offset++;
143 }
144 }
145
146 // Copy class name over.
147 char* newStr = reinterpret_cast<char*>(
148 malloc(targetLen + arrayDepth * 2 + 1));
149 int i = 0;
150 for (; i < targetLen; i++) {
151 const char ch = str[offset + i];
152 newStr[i] = (ch == '/' || ch == '$') ? '.' : ch;
153 } // for
154
155 // Add the appropriate number of brackets for arrays.
156 for (int j = 0; j < arrayDepth; j++) {
157 newStr[i++] = '[';
158 newStr[i++] = ']';
159 } // for
160
161 newStr[i] = '\0';
162 return newStr;
163}
164
165/*
166 * Converts the class name portion of a type descriptor to human-readable
167 * "dotted" form.
168 *
169 * Returns a newly-allocated string.
170 */
171static char* descriptorClassToDot(const char* str) {
172 // Reduce to just the class name, trimming trailing ';'.
173 const char* lastSlash = strrchr(str, '/');
174 if (lastSlash == nullptr) {
175 lastSlash = str + 1; // start past 'L'
176 } else {
177 lastSlash++; // start past '/'
178 }
179
180 char* newStr = strdup(lastSlash);
181 newStr[strlen(lastSlash) - 1] = '\0';
182 for (char* cp = newStr; *cp != '\0'; cp++) {
183 if (*cp == '$') {
184 *cp = '.';
185 }
186 } // for
187 return newStr;
188}
189
190/*
191 * Returns a quoted string representing the boolean value.
192 */
193static const char* quotedBool(bool val) {
194 return val ? "\"true\"" : "\"false\"";
195}
196
197/*
198 * Returns a quoted string representing the access flags.
199 */
200static const char* quotedVisibility(u4 accessFlags) {
201 if (accessFlags & kAccPublic) {
202 return "\"public\"";
203 } else if (accessFlags & kAccProtected) {
204 return "\"protected\"";
205 } else if (accessFlags & kAccPrivate) {
206 return "\"private\"";
207 } else {
208 return "\"package\"";
209 }
210}
211
212/*
213 * Counts the number of '1' bits in a word.
214 */
215static int countOnes(u4 val) {
216 val = val - ((val >> 1) & 0x55555555);
217 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
218 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
219}
220
221/*
222 * Creates a new string with human-readable access flags.
223 *
224 * In the base language the access_flags fields are type u2; in Dalvik
225 * they're u4.
226 */
227static char* createAccessFlagStr(u4 flags, AccessFor forWhat) {
228 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
229 {
230 "PUBLIC", /* 0x00001 */
231 "PRIVATE", /* 0x00002 */
232 "PROTECTED", /* 0x00004 */
233 "STATIC", /* 0x00008 */
234 "FINAL", /* 0x00010 */
235 "?", /* 0x00020 */
236 "?", /* 0x00040 */
237 "?", /* 0x00080 */
238 "?", /* 0x00100 */
239 "INTERFACE", /* 0x00200 */
240 "ABSTRACT", /* 0x00400 */
241 "?", /* 0x00800 */
242 "SYNTHETIC", /* 0x01000 */
243 "ANNOTATION", /* 0x02000 */
244 "ENUM", /* 0x04000 */
245 "?", /* 0x08000 */
246 "VERIFIED", /* 0x10000 */
247 "OPTIMIZED", /* 0x20000 */
248 }, {
249 "PUBLIC", /* 0x00001 */
250 "PRIVATE", /* 0x00002 */
251 "PROTECTED", /* 0x00004 */
252 "STATIC", /* 0x00008 */
253 "FINAL", /* 0x00010 */
254 "SYNCHRONIZED", /* 0x00020 */
255 "BRIDGE", /* 0x00040 */
256 "VARARGS", /* 0x00080 */
257 "NATIVE", /* 0x00100 */
258 "?", /* 0x00200 */
259 "ABSTRACT", /* 0x00400 */
260 "STRICT", /* 0x00800 */
261 "SYNTHETIC", /* 0x01000 */
262 "?", /* 0x02000 */
263 "?", /* 0x04000 */
264 "MIRANDA", /* 0x08000 */
265 "CONSTRUCTOR", /* 0x10000 */
266 "DECLARED_SYNCHRONIZED", /* 0x20000 */
267 }, {
268 "PUBLIC", /* 0x00001 */
269 "PRIVATE", /* 0x00002 */
270 "PROTECTED", /* 0x00004 */
271 "STATIC", /* 0x00008 */
272 "FINAL", /* 0x00010 */
273 "?", /* 0x00020 */
274 "VOLATILE", /* 0x00040 */
275 "TRANSIENT", /* 0x00080 */
276 "?", /* 0x00100 */
277 "?", /* 0x00200 */
278 "?", /* 0x00400 */
279 "?", /* 0x00800 */
280 "SYNTHETIC", /* 0x01000 */
281 "?", /* 0x02000 */
282 "ENUM", /* 0x04000 */
283 "?", /* 0x08000 */
284 "?", /* 0x10000 */
285 "?", /* 0x20000 */
286 },
287 };
288
289 // Allocate enough storage to hold the expected number of strings,
290 // plus a space between each. We over-allocate, using the longest
291 // string above as the base metric.
292 const int kLongest = 21; // The strlen of longest string above.
293 const int count = countOnes(flags);
294 char* str;
295 char* cp;
296 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
297
298 for (int i = 0; i < kNumFlags; i++) {
299 if (flags & 0x01) {
300 const char* accessStr = kAccessStrings[forWhat][i];
301 const int len = strlen(accessStr);
302 if (cp != str) {
303 *cp++ = ' ';
304 }
305 memcpy(cp, accessStr, len);
306 cp += len;
307 }
308 flags >>= 1;
309 } // for
310
311 *cp = '\0';
312 return str;
313}
314
315/*
316 * Copies character data from "data" to "out", converting non-ASCII values
317 * to fprintf format chars or an ASCII filler ('.' or '?').
318 *
319 * The output buffer must be able to hold (2*len)+1 bytes. The result is
320 * NULL-terminated.
321 */
322static void asciify(char* out, const unsigned char* data, size_t len) {
323 while (len--) {
324 if (*data < 0x20) {
325 // Could do more here, but we don't need them yet.
326 switch (*data) {
327 case '\0':
328 *out++ = '\\';
329 *out++ = '0';
330 break;
331 case '\n':
332 *out++ = '\\';
333 *out++ = 'n';
334 break;
335 default:
336 *out++ = '.';
337 break;
338 } // switch
339 } else if (*data >= 0x80) {
340 *out++ = '?';
341 } else {
342 *out++ = *data;
343 }
344 data++;
345 } // while
346 *out = '\0';
347}
348
349/*
350 * Dumps the file header.
351 *
352 * Note that some of the : are misaligned on purpose to preserve
353 * the exact output of the original Dalvik dexdump.
354 */
355static void dumpFileHeader(const DexFile* pDexFile) {
356 const DexFile::Header& pHeader = pDexFile->GetHeader();
357 char sanitized[sizeof(pHeader.magic_) * 2 + 1];
358 fprintf(gOutFile, "DEX file header:\n");
359 asciify(sanitized, pHeader.magic_, sizeof(pHeader.magic_));
360 fprintf(gOutFile, "magic : '%s'\n", sanitized);
361 fprintf(gOutFile, "checksum : %08x\n", pHeader.checksum_);
362 fprintf(gOutFile, "signature : %02x%02x...%02x%02x\n",
363 pHeader.signature_[0], pHeader.signature_[1],
364 pHeader.signature_[DexFile::kSha1DigestSize - 2],
365 pHeader.signature_[DexFile::kSha1DigestSize - 1]);
366 fprintf(gOutFile, "file_size : %d\n", pHeader.file_size_);
367 fprintf(gOutFile, "header_size : %d\n", pHeader.header_size_);
368 fprintf(gOutFile, "link_size : %d\n", pHeader.link_size_);
369 fprintf(gOutFile, "link_off : %d (0x%06x)\n",
370 pHeader.link_off_, pHeader.link_off_);
371 fprintf(gOutFile, "string_ids_size : %d\n", pHeader.string_ids_size_);
372 fprintf(gOutFile, "string_ids_off : %d (0x%06x)\n",
373 pHeader.string_ids_off_, pHeader.string_ids_off_);
374 fprintf(gOutFile, "type_ids_size : %d\n", pHeader.type_ids_size_);
375 fprintf(gOutFile, "type_ids_off : %d (0x%06x)\n",
376 pHeader.type_ids_off_, pHeader.type_ids_off_);
377 fprintf(gOutFile, "proto_ids_size : %d\n", pHeader.proto_ids_size_);
378 fprintf(gOutFile, "proto_ids_off : %d (0x%06x)\n",
379 pHeader.proto_ids_off_, pHeader.proto_ids_off_);
380 fprintf(gOutFile, "field_ids_size : %d\n", pHeader.field_ids_size_);
381 fprintf(gOutFile, "field_ids_off : %d (0x%06x)\n",
382 pHeader.field_ids_off_, pHeader.field_ids_off_);
383 fprintf(gOutFile, "method_ids_size : %d\n", pHeader.method_ids_size_);
384 fprintf(gOutFile, "method_ids_off : %d (0x%06x)\n",
385 pHeader.method_ids_off_, pHeader.method_ids_off_);
386 fprintf(gOutFile, "class_defs_size : %d\n", pHeader.class_defs_size_);
387 fprintf(gOutFile, "class_defs_off : %d (0x%06x)\n",
388 pHeader.class_defs_off_, pHeader.class_defs_off_);
389 fprintf(gOutFile, "data_size : %d\n", pHeader.data_size_);
390 fprintf(gOutFile, "data_off : %d (0x%06x)\n\n",
391 pHeader.data_off_, pHeader.data_off_);
392}
393
394/*
395 * Dumps a class_def_item.
396 */
397static void dumpClassDef(const DexFile* pDexFile, int idx) {
398 // General class information.
399 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
400 fprintf(gOutFile, "Class #%d header:\n", idx);
401 fprintf(gOutFile, "class_idx : %d\n", pClassDef.class_idx_);
402 fprintf(gOutFile, "access_flags : %d (0x%04x)\n",
403 pClassDef.access_flags_, pClassDef.access_flags_);
404 fprintf(gOutFile, "superclass_idx : %d\n", pClassDef.superclass_idx_);
405 fprintf(gOutFile, "interfaces_off : %d (0x%06x)\n",
406 pClassDef.interfaces_off_, pClassDef.interfaces_off_);
407 fprintf(gOutFile, "source_file_idx : %d\n", pClassDef.source_file_idx_);
408 fprintf(gOutFile, "annotations_off : %d (0x%06x)\n",
409 pClassDef.annotations_off_, pClassDef.annotations_off_);
410 fprintf(gOutFile, "class_data_off : %d (0x%06x)\n",
411 pClassDef.class_data_off_, pClassDef.class_data_off_);
412
413 // Fields and methods.
414 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
415 if (pEncodedData != nullptr) {
416 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
417 fprintf(gOutFile, "static_fields_size : %d\n", pClassData.NumStaticFields());
418 fprintf(gOutFile, "instance_fields_size: %d\n", pClassData.NumInstanceFields());
419 fprintf(gOutFile, "direct_methods_size : %d\n", pClassData.NumDirectMethods());
420 fprintf(gOutFile, "virtual_methods_size: %d\n", pClassData.NumVirtualMethods());
421 } else {
422 fprintf(gOutFile, "static_fields_size : 0\n");
423 fprintf(gOutFile, "instance_fields_size: 0\n");
424 fprintf(gOutFile, "direct_methods_size : 0\n");
425 fprintf(gOutFile, "virtual_methods_size: 0\n");
426 }
427 fprintf(gOutFile, "\n");
428}
429
430/*
431 * Dumps an interface that a class declares to implement.
432 */
433static void dumpInterface(const DexFile* pDexFile, const DexFile::TypeItem& pTypeItem, int i) {
434 const char* interfaceName = pDexFile->StringByTypeIdx(pTypeItem.type_idx_);
435 if (gOptions.outputFormat == OUTPUT_PLAIN) {
436 fprintf(gOutFile, " #%d : '%s'\n", i, interfaceName);
437 } else {
438 char* dotted = descriptorToDot(interfaceName);
439 fprintf(gOutFile, "<implements name=\"%s\">\n</implements>\n", dotted);
440 free(dotted);
441 }
442}
443
444/*
445 * Dumps the catches table associated with the code.
446 */
447static void dumpCatches(const DexFile* pDexFile, const DexFile::CodeItem* pCode) {
448 const u4 triesSize = pCode->tries_size_;
449
450 // No catch table.
451 if (triesSize == 0) {
452 fprintf(gOutFile, " catches : (none)\n");
453 return;
454 }
455
456 // Dump all table entries.
457 fprintf(gOutFile, " catches : %d\n", triesSize);
458 for (u4 i = 0; i < triesSize; i++) {
459 const DexFile::TryItem* pTry = pDexFile->GetTryItems(*pCode, i);
460 const u4 start = pTry->start_addr_;
461 const u4 end = start + pTry->insn_count_;
462 fprintf(gOutFile, " 0x%04x - 0x%04x\n", start, end);
463 for (CatchHandlerIterator it(*pCode, *pTry); it.HasNext(); it.Next()) {
464 const u2 tidx = it.GetHandlerTypeIndex();
465 const char* descriptor =
466 (tidx == DexFile::kDexNoIndex16) ? "<any>" : pDexFile->StringByTypeIdx(tidx);
467 fprintf(gOutFile, " %s -> 0x%04x\n", descriptor, it.GetHandlerAddress());
468 } // for
469 } // for
470}
471
472/*
473 * Callback for dumping each positions table entry.
474 */
475static bool dumpPositionsCb(void* /*context*/, u4 address, u4 lineNum) {
476 fprintf(gOutFile, " 0x%04x line=%d\n", address, lineNum);
477 return false;
478}
479
480/*
481 * Callback for dumping locals table entry.
482 */
483static void dumpLocalsCb(void* /*context*/, u2 slot, u4 startAddress, u4 endAddress,
484 const char* name, const char* descriptor, const char* signature) {
485 fprintf(gOutFile, " 0x%04x - 0x%04x reg=%d %s %s %s\n",
486 startAddress, endAddress, slot, name, descriptor, signature);
487}
488
489/*
490 * Helper for dumpInstruction(), which builds the string
491 * representation for the index in the given instruction. This will
492 * first try to use the given buffer, but if the result won't fit,
493 * then this will allocate a new buffer to hold the result. A pointer
494 * to the buffer which holds the full result is always returned, and
495 * this can be compared with the one passed in, to see if the result
496 * needs to be free()d.
497 */
498static char* indexString(const DexFile* pDexFile,
499 const Instruction* pDecInsn, char* buf, size_t bufSize) {
500 // Determine index and width of the string.
501 u4 index = 0;
502 u4 width = 4;
503 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
504 // SOME NOT SUPPORTED:
505 // case Instruction::k20bc:
506 case Instruction::k21c:
507 case Instruction::k35c:
508 // case Instruction::k35ms:
509 case Instruction::k3rc:
510 // case Instruction::k3rms:
511 // case Instruction::k35mi:
512 // case Instruction::k3rmi:
513 index = pDecInsn->VRegB();
514 width = 4;
515 break;
516 case Instruction::k31c:
517 index = pDecInsn->VRegB();
518 width = 8;
519 break;
520 case Instruction::k22c:
521 // case Instruction::k22cs:
522 index = pDecInsn->VRegC();
523 width = 4;
524 break;
525 default:
526 break;
527 } // switch
528
529 // Determine index type.
530 size_t outSize = 0;
531 switch (Instruction::IndexTypeOf(pDecInsn->Opcode())) {
532 case Instruction::kIndexUnknown:
533 // This function should never get called for this type, but do
534 // something sensible here, just to help with debugging.
535 outSize = snprintf(buf, bufSize, "<unknown-index>");
536 break;
537 case Instruction::kIndexNone:
538 // This function should never get called for this type, but do
539 // something sensible here, just to help with debugging.
540 outSize = snprintf(buf, bufSize, "<no-index>");
541 break;
542 case Instruction::kIndexTypeRef:
543 if (index < pDexFile->GetHeader().type_ids_size_) {
544 const char* tp = pDexFile->StringByTypeIdx(index);
545 outSize = snprintf(buf, bufSize, "%s // type@%0*x", tp, width, index);
546 } else {
547 outSize = snprintf(buf, bufSize, "<type?> // type@%0*x", width, index);
548 }
549 break;
550 case Instruction::kIndexStringRef:
551 if (index < pDexFile->GetHeader().string_ids_size_) {
552 const char* st = pDexFile->StringDataByIdx(index);
553 outSize = snprintf(buf, bufSize, "\"%s\" // string@%0*x", st, width, index);
554 } else {
555 outSize = snprintf(buf, bufSize, "<string?> // string@%0*x", width, index);
556 }
557 break;
558 case Instruction::kIndexMethodRef:
559 if (index < pDexFile->GetHeader().method_ids_size_) {
560 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
561 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
562 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
563 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
564 outSize = snprintf(buf, bufSize, "%s.%s:%s // method@%0*x",
565 backDescriptor, name, signature.ToString().c_str(), width, index);
566 } else {
567 outSize = snprintf(buf, bufSize, "<method?> // method@%0*x", width, index);
568 }
569 break;
570 case Instruction::kIndexFieldRef:
571 if (index < pDexFile->GetHeader().field_ids_size_) {
572 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(index);
573 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
574 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
575 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
576 outSize = snprintf(buf, bufSize, "%s.%s:%s // field@%0*x",
577 backDescriptor, name, typeDescriptor, width, index);
578 } else {
579 outSize = snprintf(buf, bufSize, "<field?> // field@%0*x", width, index);
580 }
581 break;
582 case Instruction::kIndexVtableOffset:
583 outSize = snprintf(buf, bufSize, "[%0*x] // vtable #%0*x",
584 width, index, width, index);
585 break;
586 case Instruction::kIndexFieldOffset:
587 outSize = snprintf(buf, bufSize, "[obj+%0*x]", width, index);
588 break;
589 // SOME NOT SUPPORTED:
590 // case Instruction::kIndexVaries:
591 // case Instruction::kIndexInlineMethod:
592 default:
593 outSize = snprintf(buf, bufSize, "<?>");
594 break;
595 } // switch
596
597 // Determine success of string construction.
598 if (outSize >= bufSize) {
599 // The buffer wasn't big enough; allocate and retry. Note:
600 // snprintf() doesn't count the '\0' as part of its returned
601 // size, so we add explicit space for it here.
602 outSize++;
603 buf = reinterpret_cast<char*>(malloc(outSize));
604 if (buf == nullptr) {
605 return nullptr;
606 }
607 return indexString(pDexFile, pDecInsn, buf, outSize);
608 }
609 return buf;
610}
611
612/*
613 * Dumps a single instruction.
614 */
615static void dumpInstruction(const DexFile* pDexFile,
616 const DexFile::CodeItem* pCode,
617 u4 codeOffset, u4 insnIdx, u4 insnWidth,
618 const Instruction* pDecInsn) {
619 // Address of instruction (expressed as byte offset).
620 fprintf(gOutFile, "%06x:", codeOffset + 0x10 + insnIdx * 2);
621
622 // Dump (part of) raw bytes.
623 const u2* insns = pCode->insns_;
624 for (u4 i = 0; i < 8; i++) {
625 if (i < insnWidth) {
626 if (i == 7) {
627 fprintf(gOutFile, " ... ");
628 } else {
629 // Print 16-bit value in little-endian order.
630 const u1* bytePtr = (const u1*) &insns[insnIdx + i];
631 fprintf(gOutFile, " %02x%02x", bytePtr[0], bytePtr[1]);
632 }
633 } else {
634 fputs(" ", gOutFile);
635 }
636 } // for
637
638 // Dump pseudo-instruction or opcode.
639 if (pDecInsn->Opcode() == Instruction::NOP) {
640 const u2 instr = get2LE((const u1*) &insns[insnIdx]);
641 if (instr == Instruction::kPackedSwitchSignature) {
642 fprintf(gOutFile, "|%04x: packed-switch-data (%d units)", insnIdx, insnWidth);
643 } else if (instr == Instruction::kSparseSwitchSignature) {
644 fprintf(gOutFile, "|%04x: sparse-switch-data (%d units)", insnIdx, insnWidth);
645 } else if (instr == Instruction::kArrayDataSignature) {
646 fprintf(gOutFile, "|%04x: array-data (%d units)", insnIdx, insnWidth);
647 } else {
648 fprintf(gOutFile, "|%04x: nop // spacer", insnIdx);
649 }
650 } else {
651 fprintf(gOutFile, "|%04x: %s", insnIdx, pDecInsn->Name());
652 }
653
654 // Set up additional argument.
655 char indexBufChars[200];
656 char *indexBuf = indexBufChars;
657 if (Instruction::IndexTypeOf(pDecInsn->Opcode()) != Instruction::kIndexNone) {
658 indexBuf = indexString(pDexFile, pDecInsn,
659 indexBufChars, sizeof(indexBufChars));
660 }
661
662 // Dump the instruction.
663 //
664 // NOTE: pDecInsn->DumpString(pDexFile) differs too much from original.
665 //
666 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
667 case Instruction::k10x: // op
668 break;
669 case Instruction::k12x: // op vA, vB
670 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
671 break;
672 case Instruction::k11n: // op vA, #+B
673 fprintf(gOutFile, " v%d, #int %d // #%x",
674 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u1)pDecInsn->VRegB());
675 break;
676 case Instruction::k11x: // op vAA
677 fprintf(gOutFile, " v%d", pDecInsn->VRegA());
678 break;
679 case Instruction::k10t: // op +AA
680 case Instruction::k20t: // op +AAAA
681 {
682 const s4 targ = (s4) pDecInsn->VRegA();
683 fprintf(gOutFile, " %04x // %c%04x",
684 insnIdx + targ,
685 (targ < 0) ? '-' : '+',
686 (targ < 0) ? -targ : targ);
687 }
688 break;
689 case Instruction::k22x: // op vAA, vBBBB
690 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
691 break;
692 case Instruction::k21t: // op vAA, +BBBB
693 {
694 const s4 targ = (s4) pDecInsn->VRegB();
695 fprintf(gOutFile, " v%d, %04x // %c%04x", pDecInsn->VRegA(),
696 insnIdx + targ,
697 (targ < 0) ? '-' : '+',
698 (targ < 0) ? -targ : targ);
699 }
700 break;
701 case Instruction::k21s: // op vAA, #+BBBB
702 fprintf(gOutFile, " v%d, #int %d // #%x",
703 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u2)pDecInsn->VRegB());
704 break;
705 case Instruction::k21h: // op vAA, #+BBBB0000[00000000]
706 // The printed format varies a bit based on the actual opcode.
707 if (pDecInsn->Opcode() == Instruction::CONST_HIGH16) {
708 const s4 value = pDecInsn->VRegB() << 16;
709 fprintf(gOutFile, " v%d, #int %d // #%x",
710 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
711 } else {
712 const s8 value = ((s8) pDecInsn->VRegB()) << 48;
713 fprintf(gOutFile, " v%d, #long %" PRId64 " // #%x",
714 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
715 }
716 break;
717 case Instruction::k21c: // op vAA, thing@BBBB
718 case Instruction::k31c: // op vAA, thing@BBBBBBBB
719 fprintf(gOutFile, " v%d, %s", pDecInsn->VRegA(), indexBuf);
720 break;
721 case Instruction::k23x: // op vAA, vBB, vCC
722 fprintf(gOutFile, " v%d, v%d, v%d",
723 pDecInsn->VRegA(), pDecInsn->VRegB(), pDecInsn->VRegC());
724 break;
725 case Instruction::k22b: // op vAA, vBB, #+CC
726 fprintf(gOutFile, " v%d, v%d, #int %d // #%02x",
727 pDecInsn->VRegA(), pDecInsn->VRegB(),
728 (s4) pDecInsn->VRegC(), (u1) pDecInsn->VRegC());
729 break;
730 case Instruction::k22t: // op vA, vB, +CCCC
731 {
732 const s4 targ = (s4) pDecInsn->VRegC();
733 fprintf(gOutFile, " v%d, v%d, %04x // %c%04x",
734 pDecInsn->VRegA(), pDecInsn->VRegB(),
735 insnIdx + targ,
736 (targ < 0) ? '-' : '+',
737 (targ < 0) ? -targ : targ);
738 }
739 break;
740 case Instruction::k22s: // op vA, vB, #+CCCC
741 fprintf(gOutFile, " v%d, v%d, #int %d // #%04x",
742 pDecInsn->VRegA(), pDecInsn->VRegB(),
743 (s4) pDecInsn->VRegC(), (u2) pDecInsn->VRegC());
744 break;
745 case Instruction::k22c: // op vA, vB, thing@CCCC
746 // NOT SUPPORTED:
747 // case Instruction::k22cs: // [opt] op vA, vB, field offset CCCC
748 fprintf(gOutFile, " v%d, v%d, %s",
749 pDecInsn->VRegA(), pDecInsn->VRegB(), indexBuf);
750 break;
751 case Instruction::k30t:
752 fprintf(gOutFile, " #%08x", pDecInsn->VRegA());
753 break;
754 case Instruction::k31i: // op vAA, #+BBBBBBBB
755 {
756 // This is often, but not always, a float.
757 union {
758 float f;
759 u4 i;
760 } conv;
761 conv.i = pDecInsn->VRegB();
762 fprintf(gOutFile, " v%d, #float %f // #%08x",
763 pDecInsn->VRegA(), conv.f, pDecInsn->VRegB());
764 }
765 break;
766 case Instruction::k31t: // op vAA, offset +BBBBBBBB
767 fprintf(gOutFile, " v%d, %08x // +%08x",
768 pDecInsn->VRegA(), insnIdx + pDecInsn->VRegB(), pDecInsn->VRegB());
769 break;
770 case Instruction::k32x: // op vAAAA, vBBBB
771 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
772 break;
773 case Instruction::k35c: // op {vC, vD, vE, vF, vG}, thing@BBBB
774 // NOT SUPPORTED:
775 // case Instruction::k35ms: // [opt] invoke-virtual+super
776 // case Instruction::k35mi: // [opt] inline invoke
777 {
Aart Bika3bb7202015-10-26 17:24:09 -0700778 u4 arg[Instruction::kMaxVarArgRegs];
Aart Bik69ae54a2015-07-01 14:52:26 -0700779 pDecInsn->GetVarArgs(arg);
780 fputs(" {", gOutFile);
781 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
782 if (i == 0) {
783 fprintf(gOutFile, "v%d", arg[i]);
784 } else {
785 fprintf(gOutFile, ", v%d", arg[i]);
786 }
787 } // for
788 fprintf(gOutFile, "}, %s", indexBuf);
789 }
790 break;
Aart Bika3bb7202015-10-26 17:24:09 -0700791 case Instruction::k25x: // op vC, {vD, vE, vF, vG} (B: count)
792 {
793 u4 arg[Instruction::kMaxVarArgRegs25x];
794 pDecInsn->GetAllArgs25x(arg);
795 fprintf(gOutFile, " v%d, {", arg[0]);
796 for (int i = 0, n = pDecInsn->VRegB(); i < n; i++) {
797 if (i == 0) {
798 fprintf(gOutFile, "v%d", arg[Instruction::kLambdaVirtualRegisterWidth + i]);
799 } else {
800 fprintf(gOutFile, ", v%d", arg[Instruction::kLambdaVirtualRegisterWidth + i]);
801 }
802 } // for
803 fputc('}', gOutFile);
804 }
805 break;
Aart Bik69ae54a2015-07-01 14:52:26 -0700806 case Instruction::k3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB
807 // NOT SUPPORTED:
808 // case Instruction::k3rms: // [opt] invoke-virtual+super/range
809 // case Instruction::k3rmi: // [opt] execute-inline/range
810 {
811 // This doesn't match the "dx" output when some of the args are
812 // 64-bit values -- dx only shows the first register.
813 fputs(" {", gOutFile);
814 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
815 if (i == 0) {
816 fprintf(gOutFile, "v%d", pDecInsn->VRegC() + i);
817 } else {
818 fprintf(gOutFile, ", v%d", pDecInsn->VRegC() + i);
819 }
820 } // for
821 fprintf(gOutFile, "}, %s", indexBuf);
822 }
823 break;
824 case Instruction::k51l: // op vAA, #+BBBBBBBBBBBBBBBB
825 {
826 // This is often, but not always, a double.
827 union {
828 double d;
829 u8 j;
830 } conv;
831 conv.j = pDecInsn->WideVRegB();
832 fprintf(gOutFile, " v%d, #double %f // #%016" PRIx64,
833 pDecInsn->VRegA(), conv.d, pDecInsn->WideVRegB());
834 }
835 break;
836 // NOT SUPPORTED:
837 // case Instruction::k00x: // unknown op or breakpoint
838 // break;
839 default:
840 fprintf(gOutFile, " ???");
841 break;
842 } // switch
843
844 fputc('\n', gOutFile);
845
846 if (indexBuf != indexBufChars) {
847 free(indexBuf);
848 }
849}
850
851/*
852 * Dumps a bytecode disassembly.
853 */
854static void dumpBytecodes(const DexFile* pDexFile, u4 idx,
855 const DexFile::CodeItem* pCode, u4 codeOffset) {
856 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
857 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
858 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
859 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
860
861 // Generate header.
862 char* tmp = descriptorToDot(backDescriptor);
863 fprintf(gOutFile, "%06x: "
864 "|[%06x] %s.%s:%s\n",
865 codeOffset, codeOffset, tmp, name, signature.ToString().c_str());
866 free(tmp);
867
868 // Iterate over all instructions.
869 const u2* insns = pCode->insns_;
870 for (u4 insnIdx = 0; insnIdx < pCode->insns_size_in_code_units_;) {
871 const Instruction* instruction = Instruction::At(&insns[insnIdx]);
872 const u4 insnWidth = instruction->SizeInCodeUnits();
873 if (insnWidth == 0) {
874 fprintf(stderr, "GLITCH: zero-width instruction at idx=0x%04x\n", insnIdx);
875 break;
876 }
877 dumpInstruction(pDexFile, pCode, codeOffset, insnIdx, insnWidth, instruction);
878 insnIdx += insnWidth;
879 } // for
880}
881
882/*
883 * Dumps code of a method.
884 */
885static void dumpCode(const DexFile* pDexFile, u4 idx, u4 flags,
886 const DexFile::CodeItem* pCode, u4 codeOffset) {
887 fprintf(gOutFile, " registers : %d\n", pCode->registers_size_);
888 fprintf(gOutFile, " ins : %d\n", pCode->ins_size_);
889 fprintf(gOutFile, " outs : %d\n", pCode->outs_size_);
890 fprintf(gOutFile, " insns size : %d 16-bit code units\n",
891 pCode->insns_size_in_code_units_);
892
893 // Bytecode disassembly, if requested.
894 if (gOptions.disassemble) {
895 dumpBytecodes(pDexFile, idx, pCode, codeOffset);
896 }
897
898 // Try-catch blocks.
899 dumpCatches(pDexFile, pCode);
900
901 // Positions and locals table in the debug info.
902 bool is_static = (flags & kAccStatic) != 0;
903 fprintf(gOutFile, " positions : \n");
904 pDexFile->DecodeDebugInfo(
905 pCode, is_static, idx, dumpPositionsCb, nullptr, nullptr);
906 fprintf(gOutFile, " locals : \n");
907 pDexFile->DecodeDebugInfo(
908 pCode, is_static, idx, nullptr, dumpLocalsCb, nullptr);
909}
910
911/*
912 * Dumps a method.
913 */
914static void dumpMethod(const DexFile* pDexFile, u4 idx, u4 flags,
915 const DexFile::CodeItem* pCode, u4 codeOffset, int i) {
916 // Bail for anything private if export only requested.
917 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
918 return;
919 }
920
921 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
922 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
923 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
924 char* typeDescriptor = strdup(signature.ToString().c_str());
925 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
926 char* accessStr = createAccessFlagStr(flags, kAccessForMethod);
927
928 if (gOptions.outputFormat == OUTPUT_PLAIN) {
929 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
930 fprintf(gOutFile, " name : '%s'\n", name);
931 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
932 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
933 if (pCode == nullptr) {
934 fprintf(gOutFile, " code : (none)\n");
935 } else {
936 fprintf(gOutFile, " code -\n");
937 dumpCode(pDexFile, idx, flags, pCode, codeOffset);
938 }
939 if (gOptions.disassemble) {
940 fputc('\n', gOutFile);
941 }
942 } else if (gOptions.outputFormat == OUTPUT_XML) {
943 const bool constructor = (name[0] == '<');
944
945 // Method name and prototype.
946 if (constructor) {
947 char* tmp = descriptorClassToDot(backDescriptor);
948 fprintf(gOutFile, "<constructor name=\"%s\"\n", tmp);
949 free(tmp);
950 tmp = descriptorToDot(backDescriptor);
951 fprintf(gOutFile, " type=\"%s\"\n", tmp);
952 free(tmp);
953 } else {
954 fprintf(gOutFile, "<method name=\"%s\"\n", name);
955 const char* returnType = strrchr(typeDescriptor, ')');
956 if (returnType == nullptr) {
957 fprintf(stderr, "bad method type descriptor '%s'\n", typeDescriptor);
958 goto bail;
959 }
960 char* tmp = descriptorToDot(returnType+1);
961 fprintf(gOutFile, " return=\"%s\"\n", tmp);
962 free(tmp);
963 fprintf(gOutFile, " abstract=%s\n", quotedBool((flags & kAccAbstract) != 0));
964 fprintf(gOutFile, " native=%s\n", quotedBool((flags & kAccNative) != 0));
965 fprintf(gOutFile, " synchronized=%s\n", quotedBool(
966 (flags & (kAccSynchronized | kAccDeclaredSynchronized)) != 0));
967 }
968
969 // Additional method flags.
970 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
971 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
972 // The "deprecated=" not knowable w/o parsing annotations.
973 fprintf(gOutFile, " visibility=%s\n>\n", quotedVisibility(flags));
974
975 // Parameters.
976 if (typeDescriptor[0] != '(') {
977 fprintf(stderr, "ERROR: bad descriptor '%s'\n", typeDescriptor);
978 goto bail;
979 }
980 char* tmpBuf = reinterpret_cast<char*>(malloc(strlen(typeDescriptor) + 1));
981 const char* base = typeDescriptor + 1;
982 int argNum = 0;
983 while (*base != ')') {
984 char* cp = tmpBuf;
985 while (*base == '[') {
986 *cp++ = *base++;
987 }
988 if (*base == 'L') {
989 // Copy through ';'.
990 do {
991 *cp = *base++;
992 } while (*cp++ != ';');
993 } else {
994 // Primitive char, copy it.
995 if (strchr("ZBCSIFJD", *base) == NULL) {
996 fprintf(stderr, "ERROR: bad method signature '%s'\n", base);
997 goto bail;
998 }
999 *cp++ = *base++;
1000 }
1001 // Null terminate and display.
1002 *cp++ = '\0';
1003 char* tmp = descriptorToDot(tmpBuf);
1004 fprintf(gOutFile, "<parameter name=\"arg%d\" type=\"%s\">\n"
1005 "</parameter>\n", argNum++, tmp);
1006 free(tmp);
1007 } // while
1008 free(tmpBuf);
1009 if (constructor) {
1010 fprintf(gOutFile, "</constructor>\n");
1011 } else {
1012 fprintf(gOutFile, "</method>\n");
1013 }
1014 }
1015
1016 bail:
1017 free(typeDescriptor);
1018 free(accessStr);
1019}
1020
1021/*
1022 * Dumps a static (class) field.
1023 */
1024static void dumpSField(const DexFile* pDexFile, u4 idx, u4 flags, int i) {
1025 // Bail for anything private if export only requested.
1026 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1027 return;
1028 }
1029
1030 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(idx);
1031 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
1032 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
1033 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
1034 char* accessStr = createAccessFlagStr(flags, kAccessForField);
1035
1036 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1037 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1038 fprintf(gOutFile, " name : '%s'\n", name);
1039 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1040 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
1041 } else if (gOptions.outputFormat == OUTPUT_XML) {
1042 fprintf(gOutFile, "<field name=\"%s\"\n", name);
1043 char *tmp = descriptorToDot(typeDescriptor);
1044 fprintf(gOutFile, " type=\"%s\"\n", tmp);
1045 free(tmp);
1046 fprintf(gOutFile, " transient=%s\n", quotedBool((flags & kAccTransient) != 0));
1047 fprintf(gOutFile, " volatile=%s\n", quotedBool((flags & kAccVolatile) != 0));
1048 // The "value=" is not knowable w/o parsing annotations.
1049 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1050 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1051 // The "deprecated=" is not knowable w/o parsing annotations.
1052 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(flags));
1053 fprintf(gOutFile, ">\n</field>\n");
1054 }
1055
1056 free(accessStr);
1057}
1058
1059/*
1060 * Dumps an instance field.
1061 */
1062static void dumpIField(const DexFile* pDexFile, u4 idx, u4 flags, int i) {
1063 dumpSField(pDexFile, idx, flags, i);
1064}
1065
1066/*
Andreas Gampe5073fed2015-08-10 11:40:25 -07001067 * Dumping a CFG. Note that this will do duplicate work. utils.h doesn't expose the code-item
1068 * version, so the DumpMethodCFG code will have to iterate again to find it. But dexdump is a
1069 * tool, so this is not performance-critical.
1070 */
1071
1072static void dumpCfg(const DexFile* dex_file,
1073 uint32_t dex_method_idx,
1074 const DexFile::CodeItem* code_item) {
1075 if (code_item != nullptr) {
1076 std::ostringstream oss;
1077 DumpMethodCFG(dex_file, dex_method_idx, oss);
1078 fprintf(gOutFile, "%s", oss.str().c_str());
1079 }
1080}
1081
1082static void dumpCfg(const DexFile* dex_file, int idx) {
1083 const DexFile::ClassDef& class_def = dex_file->GetClassDef(idx);
1084 const uint8_t* class_data = dex_file->GetClassData(class_def);
1085 if (class_data == nullptr) { // empty class such as a marker interface?
1086 return;
1087 }
1088 ClassDataItemIterator it(*dex_file, class_data);
1089 while (it.HasNextStaticField()) {
1090 it.Next();
1091 }
1092 while (it.HasNextInstanceField()) {
1093 it.Next();
1094 }
1095 while (it.HasNextDirectMethod()) {
1096 dumpCfg(dex_file,
1097 it.GetMemberIndex(),
1098 it.GetMethodCodeItem());
1099 it.Next();
1100 }
1101 while (it.HasNextVirtualMethod()) {
1102 dumpCfg(dex_file,
1103 it.GetMemberIndex(),
1104 it.GetMethodCodeItem());
1105 it.Next();
1106 }
1107}
1108
1109/*
Aart Bik69ae54a2015-07-01 14:52:26 -07001110 * Dumps the class.
1111 *
1112 * Note "idx" is a DexClassDef index, not a DexTypeId index.
1113 *
1114 * If "*pLastPackage" is nullptr or does not match the current class' package,
1115 * the value will be replaced with a newly-allocated string.
1116 */
1117static void dumpClass(const DexFile* pDexFile, int idx, char** pLastPackage) {
1118 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
1119
1120 // Omitting non-public class.
1121 if (gOptions.exportsOnly && (pClassDef.access_flags_ & kAccPublic) == 0) {
1122 return;
1123 }
1124
Andreas Gampe5073fed2015-08-10 11:40:25 -07001125 if (gOptions.cfg) {
1126 dumpCfg(pDexFile, idx);
1127 return;
1128 }
1129
Aart Bik69ae54a2015-07-01 14:52:26 -07001130 // For the XML output, show the package name. Ideally we'd gather
1131 // up the classes, sort them, and dump them alphabetically so the
1132 // package name wouldn't jump around, but that's not a great plan
1133 // for something that needs to run on the device.
1134 const char* classDescriptor = pDexFile->StringByTypeIdx(pClassDef.class_idx_);
1135 if (!(classDescriptor[0] == 'L' &&
1136 classDescriptor[strlen(classDescriptor)-1] == ';')) {
1137 // Arrays and primitives should not be defined explicitly. Keep going?
1138 fprintf(stderr, "Malformed class name '%s'\n", classDescriptor);
1139 } else if (gOptions.outputFormat == OUTPUT_XML) {
1140 char* mangle = strdup(classDescriptor + 1);
1141 mangle[strlen(mangle)-1] = '\0';
1142
1143 // Reduce to just the package name.
1144 char* lastSlash = strrchr(mangle, '/');
1145 if (lastSlash != nullptr) {
1146 *lastSlash = '\0';
1147 } else {
1148 *mangle = '\0';
1149 }
1150
1151 for (char* cp = mangle; *cp != '\0'; cp++) {
1152 if (*cp == '/') {
1153 *cp = '.';
1154 }
1155 } // for
1156
1157 if (*pLastPackage == nullptr || strcmp(mangle, *pLastPackage) != 0) {
1158 // Start of a new package.
1159 if (*pLastPackage != nullptr) {
1160 fprintf(gOutFile, "</package>\n");
1161 }
1162 fprintf(gOutFile, "<package name=\"%s\"\n>\n", mangle);
1163 free(*pLastPackage);
1164 *pLastPackage = mangle;
1165 } else {
1166 free(mangle);
1167 }
1168 }
1169
1170 // General class information.
1171 char* accessStr = createAccessFlagStr(pClassDef.access_flags_, kAccessForClass);
1172 const char* superclassDescriptor;
1173 if (pClassDef.superclass_idx_ == DexFile::kDexNoIndex16) {
1174 superclassDescriptor = nullptr;
1175 } else {
1176 superclassDescriptor = pDexFile->StringByTypeIdx(pClassDef.superclass_idx_);
1177 }
1178 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1179 fprintf(gOutFile, "Class #%d -\n", idx);
1180 fprintf(gOutFile, " Class descriptor : '%s'\n", classDescriptor);
1181 fprintf(gOutFile, " Access flags : 0x%04x (%s)\n", pClassDef.access_flags_, accessStr);
1182 if (superclassDescriptor != nullptr) {
1183 fprintf(gOutFile, " Superclass : '%s'\n", superclassDescriptor);
1184 }
1185 fprintf(gOutFile, " Interfaces -\n");
1186 } else {
1187 char* tmp = descriptorClassToDot(classDescriptor);
1188 fprintf(gOutFile, "<class name=\"%s\"\n", tmp);
1189 free(tmp);
1190 if (superclassDescriptor != nullptr) {
1191 tmp = descriptorToDot(superclassDescriptor);
1192 fprintf(gOutFile, " extends=\"%s\"\n", tmp);
1193 free(tmp);
1194 }
1195 fprintf(gOutFile, " abstract=%s\n", quotedBool((pClassDef.access_flags_ & kAccAbstract) != 0));
1196 fprintf(gOutFile, " static=%s\n", quotedBool((pClassDef.access_flags_ & kAccStatic) != 0));
1197 fprintf(gOutFile, " final=%s\n", quotedBool((pClassDef.access_flags_ & kAccFinal) != 0));
1198 // The "deprecated=" not knowable w/o parsing annotations.
1199 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(pClassDef.access_flags_));
1200 fprintf(gOutFile, ">\n");
1201 }
1202
1203 // Interfaces.
1204 const DexFile::TypeList* pInterfaces = pDexFile->GetInterfacesList(pClassDef);
1205 if (pInterfaces != nullptr) {
1206 for (u4 i = 0; i < pInterfaces->Size(); i++) {
1207 dumpInterface(pDexFile, pInterfaces->GetTypeItem(i), i);
1208 } // for
1209 }
1210
1211 // Fields and methods.
1212 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
1213 if (pEncodedData == nullptr) {
1214 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1215 fprintf(gOutFile, " Static fields -\n");
1216 fprintf(gOutFile, " Instance fields -\n");
1217 fprintf(gOutFile, " Direct methods -\n");
1218 fprintf(gOutFile, " Virtual methods -\n");
1219 }
1220 } else {
1221 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
1222 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1223 fprintf(gOutFile, " Static fields -\n");
1224 }
1225 for (int i = 0; pClassData.HasNextStaticField(); i++, pClassData.Next()) {
1226 dumpSField(pDexFile, pClassData.GetMemberIndex(),
1227 pClassData.GetRawMemberAccessFlags(), i);
1228 } // for
1229 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1230 fprintf(gOutFile, " Instance fields -\n");
1231 }
1232 for (int i = 0; pClassData.HasNextInstanceField(); i++, pClassData.Next()) {
1233 dumpIField(pDexFile, pClassData.GetMemberIndex(),
1234 pClassData.GetRawMemberAccessFlags(), i);
1235 } // for
1236 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1237 fprintf(gOutFile, " Direct methods -\n");
1238 }
1239 for (int i = 0; pClassData.HasNextDirectMethod(); i++, pClassData.Next()) {
1240 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1241 pClassData.GetRawMemberAccessFlags(),
1242 pClassData.GetMethodCodeItem(),
1243 pClassData.GetMethodCodeItemOffset(), i);
1244 } // for
1245 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1246 fprintf(gOutFile, " Virtual methods -\n");
1247 }
1248 for (int i = 0; pClassData.HasNextVirtualMethod(); i++, pClassData.Next()) {
1249 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1250 pClassData.GetRawMemberAccessFlags(),
1251 pClassData.GetMethodCodeItem(),
1252 pClassData.GetMethodCodeItemOffset(), i);
1253 } // for
1254 }
1255
1256 // End of class.
1257 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1258 const char* fileName;
1259 if (pClassDef.source_file_idx_ != DexFile::kDexNoIndex) {
1260 fileName = pDexFile->StringDataByIdx(pClassDef.source_file_idx_);
1261 } else {
1262 fileName = "unknown";
1263 }
1264 fprintf(gOutFile, " source_file_idx : %d (%s)\n\n",
1265 pClassDef.source_file_idx_, fileName);
1266 } else if (gOptions.outputFormat == OUTPUT_XML) {
1267 fprintf(gOutFile, "</class>\n");
1268 }
1269
1270 free(accessStr);
1271}
1272
1273/*
1274 * Dumps the requested sections of the file.
1275 */
1276static void processDexFile(const char* fileName, const DexFile* pDexFile) {
1277 if (gOptions.verbose) {
1278 fprintf(gOutFile, "Opened '%s', DEX version '%.3s'\n",
1279 fileName, pDexFile->GetHeader().magic_ + 4);
1280 }
1281
1282 // Headers.
1283 if (gOptions.showFileHeaders) {
1284 dumpFileHeader(pDexFile);
1285 }
1286
1287 // Open XML context.
1288 if (gOptions.outputFormat == OUTPUT_XML) {
1289 fprintf(gOutFile, "<api>\n");
1290 }
1291
1292 // Iterate over all classes.
1293 char* package = nullptr;
1294 const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
1295 for (u4 i = 0; i < classDefsSize; i++) {
1296 if (gOptions.showSectionHeaders) {
1297 dumpClassDef(pDexFile, i);
1298 }
1299 dumpClass(pDexFile, i, &package);
1300 } // for
1301
1302 // Free the last package allocated.
1303 if (package != nullptr) {
1304 fprintf(gOutFile, "</package>\n");
1305 free(package);
1306 }
1307
1308 // Close XML context.
1309 if (gOptions.outputFormat == OUTPUT_XML) {
1310 fprintf(gOutFile, "</api>\n");
1311 }
1312}
1313
1314/*
1315 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
1316 */
1317int processFile(const char* fileName) {
1318 if (gOptions.verbose) {
1319 fprintf(gOutFile, "Processing '%s'...\n", fileName);
1320 }
1321
1322 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
1323 // all of which are Zip archives with "classes.dex" inside. The compressed
1324 // data needs to be extracted to a temp file, the location of which varies.
1325 //
1326 // TODO(ajcbik): fix following issues
1327 //
1328 // (1) gOptions.tempFileName is not accounted for
1329 // (2) gOptions.ignoreBadChecksum is not accounted for
1330 //
1331 std::string error_msg;
1332 std::vector<std::unique_ptr<const DexFile>> dex_files;
1333 if (!DexFile::Open(fileName, fileName, &error_msg, &dex_files)) {
1334 // Display returned error message to user. Note that this error behavior
1335 // differs from the error messages shown by the original Dalvik dexdump.
1336 fputs(error_msg.c_str(), stderr);
1337 fputc('\n', stderr);
1338 return -1;
1339 }
1340
Aart Bik4e149602015-07-09 11:45:28 -07001341 // Success. Either report checksum verification or process
1342 // all dex files found in given file.
Aart Bik69ae54a2015-07-01 14:52:26 -07001343 if (gOptions.checksumOnly) {
1344 fprintf(gOutFile, "Checksum verified\n");
1345 } else {
Aart Bik4e149602015-07-09 11:45:28 -07001346 for (size_t i = 0; i < dex_files.size(); i++) {
1347 processDexFile(fileName, dex_files[i].get());
1348 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001349 }
1350 return 0;
1351}
1352
1353} // namespace art