blob: 03d6227ae2ef51dc18c0afc3074d55da1d07f1fc [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
Aart Bikdce50862016-06-10 16:04:03 -070020 * based on Art functions in libart instead. The output is very similar to
21 * to the original for correct DEX files. Error messages may differ, however.
Aart Bik69ae54a2015-07-01 14:52:26 -070022 * 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
Aart Bik69ae54a2015-07-01 14:52:26 -070030 * - no parameter names
31 * - no generic signatures on parameters, e.g. type="java.lang.Class<?>"
32 * - class shows declared fields and methods; does not show inherited fields
33 */
34
35#include "dexdump.h"
36
37#include <inttypes.h>
38#include <stdio.h>
39
Andreas Gampe5073fed2015-08-10 11:40:25 -070040#include <iostream>
Aart Bik69ae54a2015-07-01 14:52:26 -070041#include <memory>
Andreas Gampe5073fed2015-08-10 11:40:25 -070042#include <sstream>
Aart Bik69ae54a2015-07-01 14:52:26 -070043#include <vector>
44
Orion Hodsonb34bb192016-10-18 17:02:58 +010045#include "base/stringprintf.h"
David Sehrcaacd112016-10-20 16:27:02 -070046#include "dexdump_cfg.h"
Aart Bik69ae54a2015-07-01 14:52:26 -070047#include "dex_file-inl.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080048#include "dex_file_types.h"
Aart Bik69ae54a2015-07-01 14:52:26 -070049#include "dex_instruction-inl.h"
50
51namespace art {
52
53/*
54 * Options parsed in main driver.
55 */
56struct Options gOptions;
57
58/*
Aart Bik4e149602015-07-09 11:45:28 -070059 * Output file. Defaults to stdout.
Aart Bik69ae54a2015-07-01 14:52:26 -070060 */
61FILE* gOutFile = stdout;
62
63/*
64 * Data types that match the definitions in the VM specification.
65 */
66typedef uint8_t u1;
67typedef uint16_t u2;
68typedef uint32_t u4;
69typedef uint64_t u8;
Aart Bikdce50862016-06-10 16:04:03 -070070typedef int8_t s1;
71typedef int16_t s2;
Aart Bik69ae54a2015-07-01 14:52:26 -070072typedef int32_t s4;
73typedef int64_t s8;
74
75/*
76 * Basic information about a field or a method.
77 */
78struct FieldMethodInfo {
79 const char* classDescriptor;
80 const char* name;
81 const char* signature;
82};
83
84/*
85 * Flags for use with createAccessFlagStr().
86 */
87enum AccessFor {
88 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
89};
90const int kNumFlags = 18;
91
92/*
93 * Gets 2 little-endian bytes.
94 */
95static inline u2 get2LE(unsigned char const* pSrc) {
96 return pSrc[0] | (pSrc[1] << 8);
97}
98
99/*
100 * Converts a single-character primitive type into human-readable form.
101 */
102static const char* primitiveTypeLabel(char typeChar) {
103 switch (typeChar) {
104 case 'B': return "byte";
105 case 'C': return "char";
106 case 'D': return "double";
107 case 'F': return "float";
108 case 'I': return "int";
109 case 'J': return "long";
110 case 'S': return "short";
111 case 'V': return "void";
112 case 'Z': return "boolean";
113 default: return "UNKNOWN";
114 } // switch
115}
116
117/*
118 * Converts a type descriptor to human-readable "dotted" form. For
119 * example, "Ljava/lang/String;" becomes "java.lang.String", and
120 * "[I" becomes "int[]". Also converts '$' to '.', which means this
121 * form can't be converted back to a descriptor.
122 */
Aart Bikc05e2f22016-07-12 15:53:13 -0700123static std::unique_ptr<char[]> descriptorToDot(const char* str) {
Aart Bik69ae54a2015-07-01 14:52:26 -0700124 int targetLen = strlen(str);
125 int offset = 0;
126
127 // Strip leading [s; will be added to end.
128 while (targetLen > 1 && str[offset] == '[') {
129 offset++;
130 targetLen--;
131 } // while
132
133 const int arrayDepth = offset;
134
135 if (targetLen == 1) {
136 // Primitive type.
137 str = primitiveTypeLabel(str[offset]);
138 offset = 0;
139 targetLen = strlen(str);
140 } else {
141 // Account for leading 'L' and trailing ';'.
142 if (targetLen >= 2 && str[offset] == 'L' &&
143 str[offset + targetLen - 1] == ';') {
144 targetLen -= 2;
145 offset++;
146 }
147 }
148
149 // Copy class name over.
Aart Bikc05e2f22016-07-12 15:53:13 -0700150 std::unique_ptr<char[]> newStr(new char[targetLen + arrayDepth * 2 + 1]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700151 int i = 0;
152 for (; i < targetLen; i++) {
153 const char ch = str[offset + i];
154 newStr[i] = (ch == '/' || ch == '$') ? '.' : ch;
155 } // for
156
157 // Add the appropriate number of brackets for arrays.
158 for (int j = 0; j < arrayDepth; j++) {
159 newStr[i++] = '[';
160 newStr[i++] = ']';
161 } // for
162
163 newStr[i] = '\0';
164 return newStr;
165}
166
167/*
168 * Converts the class name portion of a type descriptor to human-readable
Aart Bikc05e2f22016-07-12 15:53:13 -0700169 * "dotted" form. For example, "Ljava/lang/String;" becomes "String".
Aart Bik69ae54a2015-07-01 14:52:26 -0700170 */
Aart Bikc05e2f22016-07-12 15:53:13 -0700171static std::unique_ptr<char[]> descriptorClassToDot(const char* str) {
172 // Reduce to just the class name prefix.
Aart Bik69ae54a2015-07-01 14:52:26 -0700173 const char* lastSlash = strrchr(str, '/');
174 if (lastSlash == nullptr) {
175 lastSlash = str + 1; // start past 'L'
176 } else {
177 lastSlash++; // start past '/'
178 }
179
Aart Bikc05e2f22016-07-12 15:53:13 -0700180 // Copy class name over, trimming trailing ';'.
181 const int targetLen = strlen(lastSlash);
182 std::unique_ptr<char[]> newStr(new char[targetLen]);
183 for (int i = 0; i < targetLen - 1; i++) {
184 const char ch = lastSlash[i];
185 newStr[i] = ch == '$' ? '.' : ch;
Aart Bik69ae54a2015-07-01 14:52:26 -0700186 } // for
Aart Bikc05e2f22016-07-12 15:53:13 -0700187 newStr[targetLen - 1] = '\0';
Aart Bik69ae54a2015-07-01 14:52:26 -0700188 return newStr;
189}
190
191/*
Aart Bikdce50862016-06-10 16:04:03 -0700192 * Returns string representing the boolean value.
193 */
194static const char* strBool(bool val) {
195 return val ? "true" : "false";
196}
197
198/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700199 * Returns a quoted string representing the boolean value.
200 */
201static const char* quotedBool(bool val) {
202 return val ? "\"true\"" : "\"false\"";
203}
204
205/*
206 * Returns a quoted string representing the access flags.
207 */
208static const char* quotedVisibility(u4 accessFlags) {
209 if (accessFlags & kAccPublic) {
210 return "\"public\"";
211 } else if (accessFlags & kAccProtected) {
212 return "\"protected\"";
213 } else if (accessFlags & kAccPrivate) {
214 return "\"private\"";
215 } else {
216 return "\"package\"";
217 }
218}
219
220/*
221 * Counts the number of '1' bits in a word.
222 */
223static int countOnes(u4 val) {
224 val = val - ((val >> 1) & 0x55555555);
225 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
226 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
227}
228
229/*
230 * Creates a new string with human-readable access flags.
231 *
232 * In the base language the access_flags fields are type u2; in Dalvik
233 * they're u4.
234 */
235static char* createAccessFlagStr(u4 flags, AccessFor forWhat) {
236 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
237 {
238 "PUBLIC", /* 0x00001 */
239 "PRIVATE", /* 0x00002 */
240 "PROTECTED", /* 0x00004 */
241 "STATIC", /* 0x00008 */
242 "FINAL", /* 0x00010 */
243 "?", /* 0x00020 */
244 "?", /* 0x00040 */
245 "?", /* 0x00080 */
246 "?", /* 0x00100 */
247 "INTERFACE", /* 0x00200 */
248 "ABSTRACT", /* 0x00400 */
249 "?", /* 0x00800 */
250 "SYNTHETIC", /* 0x01000 */
251 "ANNOTATION", /* 0x02000 */
252 "ENUM", /* 0x04000 */
253 "?", /* 0x08000 */
254 "VERIFIED", /* 0x10000 */
255 "OPTIMIZED", /* 0x20000 */
256 }, {
257 "PUBLIC", /* 0x00001 */
258 "PRIVATE", /* 0x00002 */
259 "PROTECTED", /* 0x00004 */
260 "STATIC", /* 0x00008 */
261 "FINAL", /* 0x00010 */
262 "SYNCHRONIZED", /* 0x00020 */
263 "BRIDGE", /* 0x00040 */
264 "VARARGS", /* 0x00080 */
265 "NATIVE", /* 0x00100 */
266 "?", /* 0x00200 */
267 "ABSTRACT", /* 0x00400 */
268 "STRICT", /* 0x00800 */
269 "SYNTHETIC", /* 0x01000 */
270 "?", /* 0x02000 */
271 "?", /* 0x04000 */
272 "MIRANDA", /* 0x08000 */
273 "CONSTRUCTOR", /* 0x10000 */
274 "DECLARED_SYNCHRONIZED", /* 0x20000 */
275 }, {
276 "PUBLIC", /* 0x00001 */
277 "PRIVATE", /* 0x00002 */
278 "PROTECTED", /* 0x00004 */
279 "STATIC", /* 0x00008 */
280 "FINAL", /* 0x00010 */
281 "?", /* 0x00020 */
282 "VOLATILE", /* 0x00040 */
283 "TRANSIENT", /* 0x00080 */
284 "?", /* 0x00100 */
285 "?", /* 0x00200 */
286 "?", /* 0x00400 */
287 "?", /* 0x00800 */
288 "SYNTHETIC", /* 0x01000 */
289 "?", /* 0x02000 */
290 "ENUM", /* 0x04000 */
291 "?", /* 0x08000 */
292 "?", /* 0x10000 */
293 "?", /* 0x20000 */
294 },
295 };
296
297 // Allocate enough storage to hold the expected number of strings,
298 // plus a space between each. We over-allocate, using the longest
299 // string above as the base metric.
300 const int kLongest = 21; // The strlen of longest string above.
301 const int count = countOnes(flags);
302 char* str;
303 char* cp;
304 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
305
306 for (int i = 0; i < kNumFlags; i++) {
307 if (flags & 0x01) {
308 const char* accessStr = kAccessStrings[forWhat][i];
309 const int len = strlen(accessStr);
310 if (cp != str) {
311 *cp++ = ' ';
312 }
313 memcpy(cp, accessStr, len);
314 cp += len;
315 }
316 flags >>= 1;
317 } // for
318
319 *cp = '\0';
320 return str;
321}
322
323/*
324 * Copies character data from "data" to "out", converting non-ASCII values
325 * to fprintf format chars or an ASCII filler ('.' or '?').
326 *
327 * The output buffer must be able to hold (2*len)+1 bytes. The result is
328 * NULL-terminated.
329 */
330static void asciify(char* out, const unsigned char* data, size_t len) {
331 while (len--) {
332 if (*data < 0x20) {
333 // Could do more here, but we don't need them yet.
334 switch (*data) {
335 case '\0':
336 *out++ = '\\';
337 *out++ = '0';
338 break;
339 case '\n':
340 *out++ = '\\';
341 *out++ = 'n';
342 break;
343 default:
344 *out++ = '.';
345 break;
346 } // switch
347 } else if (*data >= 0x80) {
348 *out++ = '?';
349 } else {
350 *out++ = *data;
351 }
352 data++;
353 } // while
354 *out = '\0';
355}
356
357/*
Aart Bikdce50862016-06-10 16:04:03 -0700358 * Dumps a string value with some escape characters.
359 */
360static void dumpEscapedString(const char* p) {
361 fputs("\"", gOutFile);
362 for (; *p; p++) {
363 switch (*p) {
364 case '\\':
365 fputs("\\\\", gOutFile);
366 break;
367 case '\"':
368 fputs("\\\"", gOutFile);
369 break;
370 case '\t':
371 fputs("\\t", gOutFile);
372 break;
373 case '\n':
374 fputs("\\n", gOutFile);
375 break;
376 case '\r':
377 fputs("\\r", gOutFile);
378 break;
379 default:
380 putc(*p, gOutFile);
381 } // switch
382 } // for
383 fputs("\"", gOutFile);
384}
385
386/*
387 * Dumps a string as an XML attribute value.
388 */
389static void dumpXmlAttribute(const char* p) {
390 for (; *p; p++) {
391 switch (*p) {
392 case '&':
393 fputs("&amp;", gOutFile);
394 break;
395 case '<':
396 fputs("&lt;", gOutFile);
397 break;
398 case '>':
399 fputs("&gt;", gOutFile);
400 break;
401 case '"':
402 fputs("&quot;", gOutFile);
403 break;
404 case '\t':
405 fputs("&#x9;", gOutFile);
406 break;
407 case '\n':
408 fputs("&#xA;", gOutFile);
409 break;
410 case '\r':
411 fputs("&#xD;", gOutFile);
412 break;
413 default:
414 putc(*p, gOutFile);
415 } // switch
416 } // for
417}
418
419/*
420 * Reads variable width value, possibly sign extended at the last defined byte.
421 */
422static u8 readVarWidth(const u1** data, u1 arg, bool sign_extend) {
423 u8 value = 0;
424 for (u4 i = 0; i <= arg; i++) {
425 value |= static_cast<u8>(*(*data)++) << (i * 8);
426 }
427 if (sign_extend) {
428 int shift = (7 - arg) * 8;
429 return (static_cast<s8>(value) << shift) >> shift;
430 }
431 return value;
432}
433
434/*
435 * Dumps encoded value.
436 */
437static void dumpEncodedValue(const DexFile* pDexFile, const u1** data); // forward
438static void dumpEncodedValue(const DexFile* pDexFile, const u1** data, u1 type, u1 arg) {
439 switch (type) {
440 case DexFile::kDexAnnotationByte:
441 fprintf(gOutFile, "%" PRId8, static_cast<s1>(readVarWidth(data, arg, false)));
442 break;
443 case DexFile::kDexAnnotationShort:
444 fprintf(gOutFile, "%" PRId16, static_cast<s2>(readVarWidth(data, arg, true)));
445 break;
446 case DexFile::kDexAnnotationChar:
447 fprintf(gOutFile, "%" PRIu16, static_cast<u2>(readVarWidth(data, arg, false)));
448 break;
449 case DexFile::kDexAnnotationInt:
450 fprintf(gOutFile, "%" PRId32, static_cast<s4>(readVarWidth(data, arg, true)));
451 break;
452 case DexFile::kDexAnnotationLong:
453 fprintf(gOutFile, "%" PRId64, static_cast<s8>(readVarWidth(data, arg, true)));
454 break;
455 case DexFile::kDexAnnotationFloat: {
456 // Fill on right.
457 union {
458 float f;
459 u4 data;
460 } conv;
461 conv.data = static_cast<u4>(readVarWidth(data, arg, false)) << (3 - arg) * 8;
462 fprintf(gOutFile, "%g", conv.f);
463 break;
464 }
465 case DexFile::kDexAnnotationDouble: {
466 // Fill on right.
467 union {
468 double d;
469 u8 data;
470 } conv;
471 conv.data = readVarWidth(data, arg, false) << (7 - arg) * 8;
472 fprintf(gOutFile, "%g", conv.d);
473 break;
474 }
475 case DexFile::kDexAnnotationString: {
476 const u4 idx = static_cast<u4>(readVarWidth(data, arg, false));
477 if (gOptions.outputFormat == OUTPUT_PLAIN) {
478 dumpEscapedString(pDexFile->StringDataByIdx(idx));
479 } else {
480 dumpXmlAttribute(pDexFile->StringDataByIdx(idx));
481 }
482 break;
483 }
484 case DexFile::kDexAnnotationType: {
485 const u4 str_idx = static_cast<u4>(readVarWidth(data, arg, false));
Andreas Gampea5b09a62016-11-17 15:21:22 -0800486 fputs(pDexFile->StringByTypeIdx(dex::TypeIndex(str_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700487 break;
488 }
489 case DexFile::kDexAnnotationField:
490 case DexFile::kDexAnnotationEnum: {
491 const u4 field_idx = static_cast<u4>(readVarWidth(data, arg, false));
492 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
493 fputs(pDexFile->StringDataByIdx(pFieldId.name_idx_), gOutFile);
494 break;
495 }
496 case DexFile::kDexAnnotationMethod: {
497 const u4 method_idx = static_cast<u4>(readVarWidth(data, arg, false));
498 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
499 fputs(pDexFile->StringDataByIdx(pMethodId.name_idx_), gOutFile);
500 break;
501 }
502 case DexFile::kDexAnnotationArray: {
503 fputc('{', gOutFile);
504 // Decode and display all elements.
505 const u4 size = DecodeUnsignedLeb128(data);
506 for (u4 i = 0; i < size; i++) {
507 fputc(' ', gOutFile);
508 dumpEncodedValue(pDexFile, data);
509 }
510 fputs(" }", gOutFile);
511 break;
512 }
513 case DexFile::kDexAnnotationAnnotation: {
514 const u4 type_idx = DecodeUnsignedLeb128(data);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800515 fputs(pDexFile->StringByTypeIdx(dex::TypeIndex(type_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700516 // Decode and display all name=value pairs.
517 const u4 size = DecodeUnsignedLeb128(data);
518 for (u4 i = 0; i < size; i++) {
519 const u4 name_idx = DecodeUnsignedLeb128(data);
520 fputc(' ', gOutFile);
521 fputs(pDexFile->StringDataByIdx(name_idx), gOutFile);
522 fputc('=', gOutFile);
523 dumpEncodedValue(pDexFile, data);
524 }
525 break;
526 }
527 case DexFile::kDexAnnotationNull:
528 fputs("null", gOutFile);
529 break;
530 case DexFile::kDexAnnotationBoolean:
531 fputs(strBool(arg), gOutFile);
532 break;
533 default:
534 fputs("????", gOutFile);
535 break;
536 } // switch
537}
538
539/*
540 * Dumps encoded value with prefix.
541 */
542static void dumpEncodedValue(const DexFile* pDexFile, const u1** data) {
543 const u1 enc = *(*data)++;
544 dumpEncodedValue(pDexFile, data, enc & 0x1f, enc >> 5);
545}
546
547/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700548 * Dumps the file header.
Aart Bik69ae54a2015-07-01 14:52:26 -0700549 */
550static void dumpFileHeader(const DexFile* pDexFile) {
551 const DexFile::Header& pHeader = pDexFile->GetHeader();
552 char sanitized[sizeof(pHeader.magic_) * 2 + 1];
553 fprintf(gOutFile, "DEX file header:\n");
554 asciify(sanitized, pHeader.magic_, sizeof(pHeader.magic_));
555 fprintf(gOutFile, "magic : '%s'\n", sanitized);
556 fprintf(gOutFile, "checksum : %08x\n", pHeader.checksum_);
557 fprintf(gOutFile, "signature : %02x%02x...%02x%02x\n",
558 pHeader.signature_[0], pHeader.signature_[1],
559 pHeader.signature_[DexFile::kSha1DigestSize - 2],
560 pHeader.signature_[DexFile::kSha1DigestSize - 1]);
561 fprintf(gOutFile, "file_size : %d\n", pHeader.file_size_);
562 fprintf(gOutFile, "header_size : %d\n", pHeader.header_size_);
563 fprintf(gOutFile, "link_size : %d\n", pHeader.link_size_);
564 fprintf(gOutFile, "link_off : %d (0x%06x)\n",
565 pHeader.link_off_, pHeader.link_off_);
566 fprintf(gOutFile, "string_ids_size : %d\n", pHeader.string_ids_size_);
567 fprintf(gOutFile, "string_ids_off : %d (0x%06x)\n",
568 pHeader.string_ids_off_, pHeader.string_ids_off_);
569 fprintf(gOutFile, "type_ids_size : %d\n", pHeader.type_ids_size_);
570 fprintf(gOutFile, "type_ids_off : %d (0x%06x)\n",
571 pHeader.type_ids_off_, pHeader.type_ids_off_);
Aart Bikdce50862016-06-10 16:04:03 -0700572 fprintf(gOutFile, "proto_ids_size : %d\n", pHeader.proto_ids_size_);
573 fprintf(gOutFile, "proto_ids_off : %d (0x%06x)\n",
Aart Bik69ae54a2015-07-01 14:52:26 -0700574 pHeader.proto_ids_off_, pHeader.proto_ids_off_);
575 fprintf(gOutFile, "field_ids_size : %d\n", pHeader.field_ids_size_);
576 fprintf(gOutFile, "field_ids_off : %d (0x%06x)\n",
577 pHeader.field_ids_off_, pHeader.field_ids_off_);
578 fprintf(gOutFile, "method_ids_size : %d\n", pHeader.method_ids_size_);
579 fprintf(gOutFile, "method_ids_off : %d (0x%06x)\n",
580 pHeader.method_ids_off_, pHeader.method_ids_off_);
581 fprintf(gOutFile, "class_defs_size : %d\n", pHeader.class_defs_size_);
582 fprintf(gOutFile, "class_defs_off : %d (0x%06x)\n",
583 pHeader.class_defs_off_, pHeader.class_defs_off_);
584 fprintf(gOutFile, "data_size : %d\n", pHeader.data_size_);
585 fprintf(gOutFile, "data_off : %d (0x%06x)\n\n",
586 pHeader.data_off_, pHeader.data_off_);
587}
588
589/*
590 * Dumps a class_def_item.
591 */
592static void dumpClassDef(const DexFile* pDexFile, int idx) {
593 // General class information.
594 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
595 fprintf(gOutFile, "Class #%d header:\n", idx);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800596 fprintf(gOutFile, "class_idx : %d\n", pClassDef.class_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700597 fprintf(gOutFile, "access_flags : %d (0x%04x)\n",
598 pClassDef.access_flags_, pClassDef.access_flags_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800599 fprintf(gOutFile, "superclass_idx : %d\n", pClassDef.superclass_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700600 fprintf(gOutFile, "interfaces_off : %d (0x%06x)\n",
601 pClassDef.interfaces_off_, pClassDef.interfaces_off_);
602 fprintf(gOutFile, "source_file_idx : %d\n", pClassDef.source_file_idx_);
603 fprintf(gOutFile, "annotations_off : %d (0x%06x)\n",
604 pClassDef.annotations_off_, pClassDef.annotations_off_);
605 fprintf(gOutFile, "class_data_off : %d (0x%06x)\n",
606 pClassDef.class_data_off_, pClassDef.class_data_off_);
607
608 // Fields and methods.
609 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
610 if (pEncodedData != nullptr) {
611 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
612 fprintf(gOutFile, "static_fields_size : %d\n", pClassData.NumStaticFields());
613 fprintf(gOutFile, "instance_fields_size: %d\n", pClassData.NumInstanceFields());
614 fprintf(gOutFile, "direct_methods_size : %d\n", pClassData.NumDirectMethods());
615 fprintf(gOutFile, "virtual_methods_size: %d\n", pClassData.NumVirtualMethods());
616 } else {
617 fprintf(gOutFile, "static_fields_size : 0\n");
618 fprintf(gOutFile, "instance_fields_size: 0\n");
619 fprintf(gOutFile, "direct_methods_size : 0\n");
620 fprintf(gOutFile, "virtual_methods_size: 0\n");
621 }
622 fprintf(gOutFile, "\n");
623}
624
Aart Bikdce50862016-06-10 16:04:03 -0700625/**
626 * Dumps an annotation set item.
627 */
628static void dumpAnnotationSetItem(const DexFile* pDexFile, const DexFile::AnnotationSetItem* set_item) {
629 if (set_item == nullptr || set_item->size_ == 0) {
630 fputs(" empty-annotation-set\n", gOutFile);
631 return;
632 }
633 for (u4 i = 0; i < set_item->size_; i++) {
634 const DexFile::AnnotationItem* annotation = pDexFile->GetAnnotationItem(set_item, i);
635 if (annotation == nullptr) {
636 continue;
637 }
638 fputs(" ", gOutFile);
639 switch (annotation->visibility_) {
640 case DexFile::kDexVisibilityBuild: fputs("VISIBILITY_BUILD ", gOutFile); break;
641 case DexFile::kDexVisibilityRuntime: fputs("VISIBILITY_RUNTIME ", gOutFile); break;
642 case DexFile::kDexVisibilitySystem: fputs("VISIBILITY_SYSTEM ", gOutFile); break;
643 default: fputs("VISIBILITY_UNKNOWN ", gOutFile); break;
644 } // switch
645 // Decode raw bytes in annotation.
646 const u1* rData = annotation->annotation_;
647 dumpEncodedValue(pDexFile, &rData, DexFile::kDexAnnotationAnnotation, 0);
648 fputc('\n', gOutFile);
649 }
650}
651
652/*
653 * Dumps class annotations.
654 */
655static void dumpClassAnnotations(const DexFile* pDexFile, int idx) {
656 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
657 const DexFile::AnnotationsDirectoryItem* dir = pDexFile->GetAnnotationsDirectory(pClassDef);
658 if (dir == nullptr) {
659 return; // none
660 }
661
662 fprintf(gOutFile, "Class #%d annotations:\n", idx);
663
664 const DexFile::AnnotationSetItem* class_set_item = pDexFile->GetClassAnnotationSet(dir);
665 const DexFile::FieldAnnotationsItem* fields = pDexFile->GetFieldAnnotations(dir);
666 const DexFile::MethodAnnotationsItem* methods = pDexFile->GetMethodAnnotations(dir);
667 const DexFile::ParameterAnnotationsItem* pars = pDexFile->GetParameterAnnotations(dir);
668
669 // Annotations on the class itself.
670 if (class_set_item != nullptr) {
671 fprintf(gOutFile, "Annotations on class\n");
672 dumpAnnotationSetItem(pDexFile, class_set_item);
673 }
674
675 // Annotations on fields.
676 if (fields != nullptr) {
677 for (u4 i = 0; i < dir->fields_size_; i++) {
678 const u4 field_idx = fields[i].field_idx_;
679 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
680 const char* field_name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
681 fprintf(gOutFile, "Annotations on field #%u '%s'\n", field_idx, field_name);
682 dumpAnnotationSetItem(pDexFile, pDexFile->GetFieldAnnotationSetItem(fields[i]));
683 }
684 }
685
686 // Annotations on methods.
687 if (methods != nullptr) {
688 for (u4 i = 0; i < dir->methods_size_; i++) {
689 const u4 method_idx = methods[i].method_idx_;
690 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
691 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
692 fprintf(gOutFile, "Annotations on method #%u '%s'\n", method_idx, method_name);
693 dumpAnnotationSetItem(pDexFile, pDexFile->GetMethodAnnotationSetItem(methods[i]));
694 }
695 }
696
697 // Annotations on method parameters.
698 if (pars != nullptr) {
699 for (u4 i = 0; i < dir->parameters_size_; i++) {
700 const u4 method_idx = pars[i].method_idx_;
701 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
702 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
703 fprintf(gOutFile, "Annotations on method #%u '%s' parameters\n", method_idx, method_name);
704 const DexFile::AnnotationSetRefList*
705 list = pDexFile->GetParameterAnnotationSetRefList(&pars[i]);
706 if (list != nullptr) {
707 for (u4 j = 0; j < list->size_; j++) {
708 fprintf(gOutFile, "#%u\n", j);
709 dumpAnnotationSetItem(pDexFile, pDexFile->GetSetRefItemItem(&list->list_[j]));
710 }
711 }
712 }
713 }
714
715 fputc('\n', gOutFile);
716}
717
Aart Bik69ae54a2015-07-01 14:52:26 -0700718/*
719 * Dumps an interface that a class declares to implement.
720 */
721static void dumpInterface(const DexFile* pDexFile, const DexFile::TypeItem& pTypeItem, int i) {
722 const char* interfaceName = pDexFile->StringByTypeIdx(pTypeItem.type_idx_);
723 if (gOptions.outputFormat == OUTPUT_PLAIN) {
724 fprintf(gOutFile, " #%d : '%s'\n", i, interfaceName);
725 } else {
Aart Bikc05e2f22016-07-12 15:53:13 -0700726 std::unique_ptr<char[]> dot(descriptorToDot(interfaceName));
727 fprintf(gOutFile, "<implements name=\"%s\">\n</implements>\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -0700728 }
729}
730
731/*
732 * Dumps the catches table associated with the code.
733 */
734static void dumpCatches(const DexFile* pDexFile, const DexFile::CodeItem* pCode) {
735 const u4 triesSize = pCode->tries_size_;
736
737 // No catch table.
738 if (triesSize == 0) {
739 fprintf(gOutFile, " catches : (none)\n");
740 return;
741 }
742
743 // Dump all table entries.
744 fprintf(gOutFile, " catches : %d\n", triesSize);
745 for (u4 i = 0; i < triesSize; i++) {
746 const DexFile::TryItem* pTry = pDexFile->GetTryItems(*pCode, i);
747 const u4 start = pTry->start_addr_;
748 const u4 end = start + pTry->insn_count_;
749 fprintf(gOutFile, " 0x%04x - 0x%04x\n", start, end);
750 for (CatchHandlerIterator it(*pCode, *pTry); it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800751 const dex::TypeIndex tidx = it.GetHandlerTypeIndex();
752 const char* descriptor = (!tidx.IsValid()) ? "<any>" : pDexFile->StringByTypeIdx(tidx);
Aart Bik69ae54a2015-07-01 14:52:26 -0700753 fprintf(gOutFile, " %s -> 0x%04x\n", descriptor, it.GetHandlerAddress());
754 } // for
755 } // for
756}
757
758/*
759 * Callback for dumping each positions table entry.
760 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000761static bool dumpPositionsCb(void* /*context*/, const DexFile::PositionInfo& entry) {
762 fprintf(gOutFile, " 0x%04x line=%d\n", entry.address_, entry.line_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700763 return false;
764}
765
766/*
767 * Callback for dumping locals table entry.
768 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000769static void dumpLocalsCb(void* /*context*/, const DexFile::LocalInfo& entry) {
770 const char* signature = entry.signature_ != nullptr ? entry.signature_ : "";
Aart Bik69ae54a2015-07-01 14:52:26 -0700771 fprintf(gOutFile, " 0x%04x - 0x%04x reg=%d %s %s %s\n",
David Srbeckyb06e28e2015-12-10 13:15:00 +0000772 entry.start_address_, entry.end_address_, entry.reg_,
773 entry.name_, entry.descriptor_, signature);
Aart Bik69ae54a2015-07-01 14:52:26 -0700774}
775
776/*
777 * Helper for dumpInstruction(), which builds the string
Aart Bika0e33fd2016-07-08 18:32:45 -0700778 * representation for the index in the given instruction.
779 * Returns a pointer to a buffer of sufficient size.
Aart Bik69ae54a2015-07-01 14:52:26 -0700780 */
Aart Bika0e33fd2016-07-08 18:32:45 -0700781static std::unique_ptr<char[]> indexString(const DexFile* pDexFile,
782 const Instruction* pDecInsn,
783 size_t bufSize) {
Orion Hodsonb34bb192016-10-18 17:02:58 +0100784 static const u4 kInvalidIndex = std::numeric_limits<u4>::max();
Aart Bika0e33fd2016-07-08 18:32:45 -0700785 std::unique_ptr<char[]> buf(new char[bufSize]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700786 // Determine index and width of the string.
787 u4 index = 0;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100788 u4 secondary_index = kInvalidIndex;
Aart Bik69ae54a2015-07-01 14:52:26 -0700789 u4 width = 4;
790 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
791 // SOME NOT SUPPORTED:
792 // case Instruction::k20bc:
793 case Instruction::k21c:
794 case Instruction::k35c:
795 // case Instruction::k35ms:
796 case Instruction::k3rc:
797 // case Instruction::k3rms:
798 // case Instruction::k35mi:
799 // case Instruction::k3rmi:
800 index = pDecInsn->VRegB();
801 width = 4;
802 break;
803 case Instruction::k31c:
804 index = pDecInsn->VRegB();
805 width = 8;
806 break;
807 case Instruction::k22c:
808 // case Instruction::k22cs:
809 index = pDecInsn->VRegC();
810 width = 4;
811 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100812 case Instruction::k45cc:
813 case Instruction::k4rcc:
814 index = pDecInsn->VRegB();
815 secondary_index = pDecInsn->VRegH();
816 width = 4;
817 break;
Aart Bik69ae54a2015-07-01 14:52:26 -0700818 default:
819 break;
820 } // switch
821
822 // Determine index type.
823 size_t outSize = 0;
824 switch (Instruction::IndexTypeOf(pDecInsn->Opcode())) {
825 case Instruction::kIndexUnknown:
826 // This function should never get called for this type, but do
827 // something sensible here, just to help with debugging.
Aart Bika0e33fd2016-07-08 18:32:45 -0700828 outSize = snprintf(buf.get(), bufSize, "<unknown-index>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700829 break;
830 case Instruction::kIndexNone:
831 // This function should never get called for this type, but do
832 // something sensible here, just to help with debugging.
Aart Bika0e33fd2016-07-08 18:32:45 -0700833 outSize = snprintf(buf.get(), bufSize, "<no-index>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700834 break;
835 case Instruction::kIndexTypeRef:
836 if (index < pDexFile->GetHeader().type_ids_size_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800837 const char* tp = pDexFile->StringByTypeIdx(dex::TypeIndex(index));
Aart Bika0e33fd2016-07-08 18:32:45 -0700838 outSize = snprintf(buf.get(), bufSize, "%s // type@%0*x", tp, width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700839 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700840 outSize = snprintf(buf.get(), bufSize, "<type?> // type@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700841 }
842 break;
843 case Instruction::kIndexStringRef:
844 if (index < pDexFile->GetHeader().string_ids_size_) {
845 const char* st = pDexFile->StringDataByIdx(index);
Aart Bika0e33fd2016-07-08 18:32:45 -0700846 outSize = snprintf(buf.get(), bufSize, "\"%s\" // string@%0*x", st, width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700847 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700848 outSize = snprintf(buf.get(), bufSize, "<string?> // string@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700849 }
850 break;
851 case Instruction::kIndexMethodRef:
852 if (index < pDexFile->GetHeader().method_ids_size_) {
853 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
854 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
855 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
856 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
Aart Bika0e33fd2016-07-08 18:32:45 -0700857 outSize = snprintf(buf.get(), bufSize, "%s.%s:%s // method@%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700858 backDescriptor, name, signature.ToString().c_str(), width, index);
859 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700860 outSize = snprintf(buf.get(), bufSize, "<method?> // method@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700861 }
862 break;
863 case Instruction::kIndexFieldRef:
864 if (index < pDexFile->GetHeader().field_ids_size_) {
865 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(index);
866 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
867 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
868 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
Aart Bika0e33fd2016-07-08 18:32:45 -0700869 outSize = snprintf(buf.get(), bufSize, "%s.%s:%s // field@%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700870 backDescriptor, name, typeDescriptor, width, index);
871 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700872 outSize = snprintf(buf.get(), bufSize, "<field?> // field@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700873 }
874 break;
875 case Instruction::kIndexVtableOffset:
Aart Bika0e33fd2016-07-08 18:32:45 -0700876 outSize = snprintf(buf.get(), bufSize, "[%0*x] // vtable #%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700877 width, index, width, index);
878 break;
879 case Instruction::kIndexFieldOffset:
Aart Bika0e33fd2016-07-08 18:32:45 -0700880 outSize = snprintf(buf.get(), bufSize, "[obj+%0*x]", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700881 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100882 case Instruction::kIndexMethodAndProtoRef: {
883 std::string method("<method?>");
884 std::string proto("<proto?>");
885 if (index < pDexFile->GetHeader().method_ids_size_) {
886 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
887 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
888 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
889 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
890 method = StringPrintf("%s.%s:%s",
891 backDescriptor, name, signature.ToString().c_str());
892 }
893 if (secondary_index < pDexFile->GetHeader().proto_ids_size_) {
894 const DexFile::ProtoId& protoId = pDexFile->GetProtoId(secondary_index);
895 const Signature signature = pDexFile->GetProtoSignature(protoId);
896 proto = signature.ToString();
897 }
898 outSize = snprintf(buf.get(), bufSize, "%s, %s // method@%0*x, proto@%0*x",
899 method.c_str(), proto.c_str(), width, index, width, secondary_index);
900 }
901 break;
Aart Bik69ae54a2015-07-01 14:52:26 -0700902 // SOME NOT SUPPORTED:
903 // case Instruction::kIndexVaries:
904 // case Instruction::kIndexInlineMethod:
905 default:
Aart Bika0e33fd2016-07-08 18:32:45 -0700906 outSize = snprintf(buf.get(), bufSize, "<?>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700907 break;
908 } // switch
909
910 // Determine success of string construction.
911 if (outSize >= bufSize) {
Aart Bika0e33fd2016-07-08 18:32:45 -0700912 // The buffer wasn't big enough; retry with computed size. Note: snprintf()
913 // doesn't count/ the '\0' as part of its returned size, so we add explicit
914 // space for it here.
915 return indexString(pDexFile, pDecInsn, outSize + 1);
Aart Bik69ae54a2015-07-01 14:52:26 -0700916 }
917 return buf;
918}
919
920/*
921 * Dumps a single instruction.
922 */
923static void dumpInstruction(const DexFile* pDexFile,
924 const DexFile::CodeItem* pCode,
925 u4 codeOffset, u4 insnIdx, u4 insnWidth,
926 const Instruction* pDecInsn) {
927 // Address of instruction (expressed as byte offset).
928 fprintf(gOutFile, "%06x:", codeOffset + 0x10 + insnIdx * 2);
929
930 // Dump (part of) raw bytes.
931 const u2* insns = pCode->insns_;
932 for (u4 i = 0; i < 8; i++) {
933 if (i < insnWidth) {
934 if (i == 7) {
935 fprintf(gOutFile, " ... ");
936 } else {
937 // Print 16-bit value in little-endian order.
938 const u1* bytePtr = (const u1*) &insns[insnIdx + i];
939 fprintf(gOutFile, " %02x%02x", bytePtr[0], bytePtr[1]);
940 }
941 } else {
942 fputs(" ", gOutFile);
943 }
944 } // for
945
946 // Dump pseudo-instruction or opcode.
947 if (pDecInsn->Opcode() == Instruction::NOP) {
948 const u2 instr = get2LE((const u1*) &insns[insnIdx]);
949 if (instr == Instruction::kPackedSwitchSignature) {
950 fprintf(gOutFile, "|%04x: packed-switch-data (%d units)", insnIdx, insnWidth);
951 } else if (instr == Instruction::kSparseSwitchSignature) {
952 fprintf(gOutFile, "|%04x: sparse-switch-data (%d units)", insnIdx, insnWidth);
953 } else if (instr == Instruction::kArrayDataSignature) {
954 fprintf(gOutFile, "|%04x: array-data (%d units)", insnIdx, insnWidth);
955 } else {
956 fprintf(gOutFile, "|%04x: nop // spacer", insnIdx);
957 }
958 } else {
959 fprintf(gOutFile, "|%04x: %s", insnIdx, pDecInsn->Name());
960 }
961
962 // Set up additional argument.
Aart Bika0e33fd2016-07-08 18:32:45 -0700963 std::unique_ptr<char[]> indexBuf;
Aart Bik69ae54a2015-07-01 14:52:26 -0700964 if (Instruction::IndexTypeOf(pDecInsn->Opcode()) != Instruction::kIndexNone) {
Aart Bika0e33fd2016-07-08 18:32:45 -0700965 indexBuf = indexString(pDexFile, pDecInsn, 200);
Aart Bik69ae54a2015-07-01 14:52:26 -0700966 }
967
968 // Dump the instruction.
969 //
970 // NOTE: pDecInsn->DumpString(pDexFile) differs too much from original.
971 //
972 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
973 case Instruction::k10x: // op
974 break;
975 case Instruction::k12x: // op vA, vB
976 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
977 break;
978 case Instruction::k11n: // op vA, #+B
979 fprintf(gOutFile, " v%d, #int %d // #%x",
980 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u1)pDecInsn->VRegB());
981 break;
982 case Instruction::k11x: // op vAA
983 fprintf(gOutFile, " v%d", pDecInsn->VRegA());
984 break;
985 case Instruction::k10t: // op +AA
Aart Bikdce50862016-06-10 16:04:03 -0700986 case Instruction::k20t: { // op +AAAA
987 const s4 targ = (s4) pDecInsn->VRegA();
988 fprintf(gOutFile, " %04x // %c%04x",
989 insnIdx + targ,
990 (targ < 0) ? '-' : '+',
991 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -0700992 break;
Aart Bikdce50862016-06-10 16:04:03 -0700993 }
Aart Bik69ae54a2015-07-01 14:52:26 -0700994 case Instruction::k22x: // op vAA, vBBBB
995 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
996 break;
Aart Bikdce50862016-06-10 16:04:03 -0700997 case Instruction::k21t: { // op vAA, +BBBB
998 const s4 targ = (s4) pDecInsn->VRegB();
999 fprintf(gOutFile, " v%d, %04x // %c%04x", pDecInsn->VRegA(),
1000 insnIdx + targ,
1001 (targ < 0) ? '-' : '+',
1002 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001003 break;
Aart Bikdce50862016-06-10 16:04:03 -07001004 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001005 case Instruction::k21s: // op vAA, #+BBBB
1006 fprintf(gOutFile, " v%d, #int %d // #%x",
1007 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u2)pDecInsn->VRegB());
1008 break;
1009 case Instruction::k21h: // op vAA, #+BBBB0000[00000000]
1010 // The printed format varies a bit based on the actual opcode.
1011 if (pDecInsn->Opcode() == Instruction::CONST_HIGH16) {
1012 const s4 value = pDecInsn->VRegB() << 16;
1013 fprintf(gOutFile, " v%d, #int %d // #%x",
1014 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
1015 } else {
1016 const s8 value = ((s8) pDecInsn->VRegB()) << 48;
1017 fprintf(gOutFile, " v%d, #long %" PRId64 " // #%x",
1018 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
1019 }
1020 break;
1021 case Instruction::k21c: // op vAA, thing@BBBB
1022 case Instruction::k31c: // op vAA, thing@BBBBBBBB
Aart Bika0e33fd2016-07-08 18:32:45 -07001023 fprintf(gOutFile, " v%d, %s", pDecInsn->VRegA(), indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001024 break;
1025 case Instruction::k23x: // op vAA, vBB, vCC
1026 fprintf(gOutFile, " v%d, v%d, v%d",
1027 pDecInsn->VRegA(), pDecInsn->VRegB(), pDecInsn->VRegC());
1028 break;
1029 case Instruction::k22b: // op vAA, vBB, #+CC
1030 fprintf(gOutFile, " v%d, v%d, #int %d // #%02x",
1031 pDecInsn->VRegA(), pDecInsn->VRegB(),
1032 (s4) pDecInsn->VRegC(), (u1) pDecInsn->VRegC());
1033 break;
Aart Bikdce50862016-06-10 16:04:03 -07001034 case Instruction::k22t: { // op vA, vB, +CCCC
1035 const s4 targ = (s4) pDecInsn->VRegC();
1036 fprintf(gOutFile, " v%d, v%d, %04x // %c%04x",
1037 pDecInsn->VRegA(), pDecInsn->VRegB(),
1038 insnIdx + targ,
1039 (targ < 0) ? '-' : '+',
1040 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001041 break;
Aart Bikdce50862016-06-10 16:04:03 -07001042 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001043 case Instruction::k22s: // op vA, vB, #+CCCC
1044 fprintf(gOutFile, " v%d, v%d, #int %d // #%04x",
1045 pDecInsn->VRegA(), pDecInsn->VRegB(),
1046 (s4) pDecInsn->VRegC(), (u2) pDecInsn->VRegC());
1047 break;
1048 case Instruction::k22c: // op vA, vB, thing@CCCC
1049 // NOT SUPPORTED:
1050 // case Instruction::k22cs: // [opt] op vA, vB, field offset CCCC
1051 fprintf(gOutFile, " v%d, v%d, %s",
Aart Bika0e33fd2016-07-08 18:32:45 -07001052 pDecInsn->VRegA(), pDecInsn->VRegB(), indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001053 break;
1054 case Instruction::k30t:
1055 fprintf(gOutFile, " #%08x", pDecInsn->VRegA());
1056 break;
Aart Bikdce50862016-06-10 16:04:03 -07001057 case Instruction::k31i: { // op vAA, #+BBBBBBBB
1058 // This is often, but not always, a float.
1059 union {
1060 float f;
1061 u4 i;
1062 } conv;
1063 conv.i = pDecInsn->VRegB();
1064 fprintf(gOutFile, " v%d, #float %g // #%08x",
1065 pDecInsn->VRegA(), conv.f, pDecInsn->VRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001066 break;
Aart Bikdce50862016-06-10 16:04:03 -07001067 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001068 case Instruction::k31t: // op vAA, offset +BBBBBBBB
1069 fprintf(gOutFile, " v%d, %08x // +%08x",
1070 pDecInsn->VRegA(), insnIdx + pDecInsn->VRegB(), pDecInsn->VRegB());
1071 break;
1072 case Instruction::k32x: // op vAAAA, vBBBB
1073 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
1074 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +01001075 case Instruction::k35c: // op {vC, vD, vE, vF, vG}, thing@BBBB
1076 case Instruction::k45cc: { // op {vC, vD, vE, vF, vG}, method@BBBB, proto@HHHH
Aart Bik69ae54a2015-07-01 14:52:26 -07001077 // NOT SUPPORTED:
1078 // case Instruction::k35ms: // [opt] invoke-virtual+super
1079 // case Instruction::k35mi: // [opt] inline invoke
Aart Bikdce50862016-06-10 16:04:03 -07001080 u4 arg[Instruction::kMaxVarArgRegs];
1081 pDecInsn->GetVarArgs(arg);
1082 fputs(" {", gOutFile);
1083 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1084 if (i == 0) {
1085 fprintf(gOutFile, "v%d", arg[i]);
1086 } else {
1087 fprintf(gOutFile, ", v%d", arg[i]);
1088 }
1089 } // for
Aart Bika0e33fd2016-07-08 18:32:45 -07001090 fprintf(gOutFile, "}, %s", indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001091 break;
Aart Bikdce50862016-06-10 16:04:03 -07001092 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001093 case Instruction::k3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB
Orion Hodsonb34bb192016-10-18 17:02:58 +01001094 case Instruction::k4rcc: { // op {vCCCC .. v(CCCC+AA-1)}, method@BBBB, proto@HHHH
Aart Bik69ae54a2015-07-01 14:52:26 -07001095 // NOT SUPPORTED:
1096 // case Instruction::k3rms: // [opt] invoke-virtual+super/range
1097 // case Instruction::k3rmi: // [opt] execute-inline/range
Aart Bik69ae54a2015-07-01 14:52:26 -07001098 // This doesn't match the "dx" output when some of the args are
1099 // 64-bit values -- dx only shows the first register.
1100 fputs(" {", gOutFile);
1101 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1102 if (i == 0) {
1103 fprintf(gOutFile, "v%d", pDecInsn->VRegC() + i);
1104 } else {
1105 fprintf(gOutFile, ", v%d", pDecInsn->VRegC() + i);
1106 }
1107 } // for
Aart Bika0e33fd2016-07-08 18:32:45 -07001108 fprintf(gOutFile, "}, %s", indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001109 }
1110 break;
Aart Bikdce50862016-06-10 16:04:03 -07001111 case Instruction::k51l: { // op vAA, #+BBBBBBBBBBBBBBBB
1112 // This is often, but not always, a double.
1113 union {
1114 double d;
1115 u8 j;
1116 } conv;
1117 conv.j = pDecInsn->WideVRegB();
1118 fprintf(gOutFile, " v%d, #double %g // #%016" PRIx64,
1119 pDecInsn->VRegA(), conv.d, pDecInsn->WideVRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001120 break;
Aart Bikdce50862016-06-10 16:04:03 -07001121 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001122 // NOT SUPPORTED:
1123 // case Instruction::k00x: // unknown op or breakpoint
1124 // break;
1125 default:
1126 fprintf(gOutFile, " ???");
1127 break;
1128 } // switch
1129
1130 fputc('\n', gOutFile);
Aart Bik69ae54a2015-07-01 14:52:26 -07001131}
1132
1133/*
1134 * Dumps a bytecode disassembly.
1135 */
1136static void dumpBytecodes(const DexFile* pDexFile, u4 idx,
1137 const DexFile::CodeItem* pCode, u4 codeOffset) {
1138 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
1139 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
1140 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
1141 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
1142
1143 // Generate header.
Aart Bikc05e2f22016-07-12 15:53:13 -07001144 std::unique_ptr<char[]> dot(descriptorToDot(backDescriptor));
1145 fprintf(gOutFile, "%06x: |[%06x] %s.%s:%s\n",
1146 codeOffset, codeOffset, dot.get(), name, signature.ToString().c_str());
Aart Bik69ae54a2015-07-01 14:52:26 -07001147
1148 // Iterate over all instructions.
1149 const u2* insns = pCode->insns_;
1150 for (u4 insnIdx = 0; insnIdx < pCode->insns_size_in_code_units_;) {
1151 const Instruction* instruction = Instruction::At(&insns[insnIdx]);
1152 const u4 insnWidth = instruction->SizeInCodeUnits();
1153 if (insnWidth == 0) {
1154 fprintf(stderr, "GLITCH: zero-width instruction at idx=0x%04x\n", insnIdx);
1155 break;
1156 }
1157 dumpInstruction(pDexFile, pCode, codeOffset, insnIdx, insnWidth, instruction);
1158 insnIdx += insnWidth;
1159 } // for
1160}
1161
1162/*
1163 * Dumps code of a method.
1164 */
1165static void dumpCode(const DexFile* pDexFile, u4 idx, u4 flags,
1166 const DexFile::CodeItem* pCode, u4 codeOffset) {
1167 fprintf(gOutFile, " registers : %d\n", pCode->registers_size_);
1168 fprintf(gOutFile, " ins : %d\n", pCode->ins_size_);
1169 fprintf(gOutFile, " outs : %d\n", pCode->outs_size_);
1170 fprintf(gOutFile, " insns size : %d 16-bit code units\n",
1171 pCode->insns_size_in_code_units_);
1172
1173 // Bytecode disassembly, if requested.
1174 if (gOptions.disassemble) {
1175 dumpBytecodes(pDexFile, idx, pCode, codeOffset);
1176 }
1177
1178 // Try-catch blocks.
1179 dumpCatches(pDexFile, pCode);
1180
1181 // Positions and locals table in the debug info.
1182 bool is_static = (flags & kAccStatic) != 0;
1183 fprintf(gOutFile, " positions : \n");
David Srbeckyb06e28e2015-12-10 13:15:00 +00001184 pDexFile->DecodeDebugPositionInfo(pCode, dumpPositionsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001185 fprintf(gOutFile, " locals : \n");
David Srbeckyb06e28e2015-12-10 13:15:00 +00001186 pDexFile->DecodeDebugLocalInfo(pCode, is_static, idx, dumpLocalsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001187}
1188
1189/*
1190 * Dumps a method.
1191 */
1192static void dumpMethod(const DexFile* pDexFile, u4 idx, u4 flags,
1193 const DexFile::CodeItem* pCode, u4 codeOffset, int i) {
1194 // Bail for anything private if export only requested.
1195 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1196 return;
1197 }
1198
1199 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
1200 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
1201 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
1202 char* typeDescriptor = strdup(signature.ToString().c_str());
1203 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
1204 char* accessStr = createAccessFlagStr(flags, kAccessForMethod);
1205
1206 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1207 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1208 fprintf(gOutFile, " name : '%s'\n", name);
1209 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1210 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
1211 if (pCode == nullptr) {
1212 fprintf(gOutFile, " code : (none)\n");
1213 } else {
1214 fprintf(gOutFile, " code -\n");
1215 dumpCode(pDexFile, idx, flags, pCode, codeOffset);
1216 }
1217 if (gOptions.disassemble) {
1218 fputc('\n', gOutFile);
1219 }
1220 } else if (gOptions.outputFormat == OUTPUT_XML) {
1221 const bool constructor = (name[0] == '<');
1222
1223 // Method name and prototype.
1224 if (constructor) {
Aart Bikc05e2f22016-07-12 15:53:13 -07001225 std::unique_ptr<char[]> dot(descriptorClassToDot(backDescriptor));
1226 fprintf(gOutFile, "<constructor name=\"%s\"\n", dot.get());
1227 dot = descriptorToDot(backDescriptor);
1228 fprintf(gOutFile, " type=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001229 } else {
1230 fprintf(gOutFile, "<method name=\"%s\"\n", name);
1231 const char* returnType = strrchr(typeDescriptor, ')');
1232 if (returnType == nullptr) {
1233 fprintf(stderr, "bad method type descriptor '%s'\n", typeDescriptor);
1234 goto bail;
1235 }
Aart Bikc05e2f22016-07-12 15:53:13 -07001236 std::unique_ptr<char[]> dot(descriptorToDot(returnType + 1));
1237 fprintf(gOutFile, " return=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001238 fprintf(gOutFile, " abstract=%s\n", quotedBool((flags & kAccAbstract) != 0));
1239 fprintf(gOutFile, " native=%s\n", quotedBool((flags & kAccNative) != 0));
1240 fprintf(gOutFile, " synchronized=%s\n", quotedBool(
1241 (flags & (kAccSynchronized | kAccDeclaredSynchronized)) != 0));
1242 }
1243
1244 // Additional method flags.
1245 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1246 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1247 // The "deprecated=" not knowable w/o parsing annotations.
1248 fprintf(gOutFile, " visibility=%s\n>\n", quotedVisibility(flags));
1249
1250 // Parameters.
1251 if (typeDescriptor[0] != '(') {
1252 fprintf(stderr, "ERROR: bad descriptor '%s'\n", typeDescriptor);
1253 goto bail;
1254 }
1255 char* tmpBuf = reinterpret_cast<char*>(malloc(strlen(typeDescriptor) + 1));
1256 const char* base = typeDescriptor + 1;
1257 int argNum = 0;
1258 while (*base != ')') {
1259 char* cp = tmpBuf;
1260 while (*base == '[') {
1261 *cp++ = *base++;
1262 }
1263 if (*base == 'L') {
1264 // Copy through ';'.
1265 do {
1266 *cp = *base++;
1267 } while (*cp++ != ';');
1268 } else {
1269 // Primitive char, copy it.
Aart Bikc05e2f22016-07-12 15:53:13 -07001270 if (strchr("ZBCSIFJD", *base) == nullptr) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001271 fprintf(stderr, "ERROR: bad method signature '%s'\n", base);
Aart Bika0e33fd2016-07-08 18:32:45 -07001272 break; // while
Aart Bik69ae54a2015-07-01 14:52:26 -07001273 }
1274 *cp++ = *base++;
1275 }
1276 // Null terminate and display.
1277 *cp++ = '\0';
Aart Bikc05e2f22016-07-12 15:53:13 -07001278 std::unique_ptr<char[]> dot(descriptorToDot(tmpBuf));
Aart Bik69ae54a2015-07-01 14:52:26 -07001279 fprintf(gOutFile, "<parameter name=\"arg%d\" type=\"%s\">\n"
Aart Bikc05e2f22016-07-12 15:53:13 -07001280 "</parameter>\n", argNum++, dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001281 } // while
1282 free(tmpBuf);
1283 if (constructor) {
1284 fprintf(gOutFile, "</constructor>\n");
1285 } else {
1286 fprintf(gOutFile, "</method>\n");
1287 }
1288 }
1289
1290 bail:
1291 free(typeDescriptor);
1292 free(accessStr);
1293}
1294
1295/*
1296 * Dumps a static (class) field.
1297 */
Aart Bikdce50862016-06-10 16:04:03 -07001298static void dumpSField(const DexFile* pDexFile, u4 idx, u4 flags, int i, const u1** data) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001299 // Bail for anything private if export only requested.
1300 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1301 return;
1302 }
1303
1304 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(idx);
1305 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
1306 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
1307 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
1308 char* accessStr = createAccessFlagStr(flags, kAccessForField);
1309
1310 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1311 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1312 fprintf(gOutFile, " name : '%s'\n", name);
1313 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1314 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
Aart Bikdce50862016-06-10 16:04:03 -07001315 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001316 fputs(" value : ", gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -07001317 dumpEncodedValue(pDexFile, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001318 fputs("\n", gOutFile);
1319 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001320 } else if (gOptions.outputFormat == OUTPUT_XML) {
1321 fprintf(gOutFile, "<field name=\"%s\"\n", name);
Aart Bikc05e2f22016-07-12 15:53:13 -07001322 std::unique_ptr<char[]> dot(descriptorToDot(typeDescriptor));
1323 fprintf(gOutFile, " type=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001324 fprintf(gOutFile, " transient=%s\n", quotedBool((flags & kAccTransient) != 0));
1325 fprintf(gOutFile, " volatile=%s\n", quotedBool((flags & kAccVolatile) != 0));
1326 // The "value=" is not knowable w/o parsing annotations.
1327 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1328 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1329 // The "deprecated=" is not knowable w/o parsing annotations.
1330 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(flags));
Aart Bikdce50862016-06-10 16:04:03 -07001331 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001332 fputs(" value=\"", gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -07001333 dumpEncodedValue(pDexFile, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001334 fputs("\"\n", gOutFile);
1335 }
1336 fputs(">\n</field>\n", gOutFile);
Aart Bik69ae54a2015-07-01 14:52:26 -07001337 }
1338
1339 free(accessStr);
1340}
1341
1342/*
1343 * Dumps an instance field.
1344 */
1345static void dumpIField(const DexFile* pDexFile, u4 idx, u4 flags, int i) {
Aart Bikdce50862016-06-10 16:04:03 -07001346 dumpSField(pDexFile, idx, flags, i, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001347}
1348
1349/*
Andreas Gampe5073fed2015-08-10 11:40:25 -07001350 * Dumping a CFG. Note that this will do duplicate work. utils.h doesn't expose the code-item
1351 * version, so the DumpMethodCFG code will have to iterate again to find it. But dexdump is a
1352 * tool, so this is not performance-critical.
1353 */
1354
1355static void dumpCfg(const DexFile* dex_file,
Aart Bikdce50862016-06-10 16:04:03 -07001356 u4 dex_method_idx,
Andreas Gampe5073fed2015-08-10 11:40:25 -07001357 const DexFile::CodeItem* code_item) {
1358 if (code_item != nullptr) {
1359 std::ostringstream oss;
1360 DumpMethodCFG(dex_file, dex_method_idx, oss);
David Sehrcaacd112016-10-20 16:27:02 -07001361 fputs(oss.str().c_str(), gOutFile);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001362 }
1363}
1364
1365static void dumpCfg(const DexFile* dex_file, int idx) {
1366 const DexFile::ClassDef& class_def = dex_file->GetClassDef(idx);
Aart Bikdce50862016-06-10 16:04:03 -07001367 const u1* class_data = dex_file->GetClassData(class_def);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001368 if (class_data == nullptr) { // empty class such as a marker interface?
1369 return;
1370 }
1371 ClassDataItemIterator it(*dex_file, class_data);
1372 while (it.HasNextStaticField()) {
1373 it.Next();
1374 }
1375 while (it.HasNextInstanceField()) {
1376 it.Next();
1377 }
1378 while (it.HasNextDirectMethod()) {
1379 dumpCfg(dex_file,
1380 it.GetMemberIndex(),
1381 it.GetMethodCodeItem());
1382 it.Next();
1383 }
1384 while (it.HasNextVirtualMethod()) {
1385 dumpCfg(dex_file,
1386 it.GetMemberIndex(),
1387 it.GetMethodCodeItem());
1388 it.Next();
1389 }
1390}
1391
1392/*
Aart Bik69ae54a2015-07-01 14:52:26 -07001393 * Dumps the class.
1394 *
1395 * Note "idx" is a DexClassDef index, not a DexTypeId index.
1396 *
1397 * If "*pLastPackage" is nullptr or does not match the current class' package,
1398 * the value will be replaced with a newly-allocated string.
1399 */
1400static void dumpClass(const DexFile* pDexFile, int idx, char** pLastPackage) {
1401 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
1402
1403 // Omitting non-public class.
1404 if (gOptions.exportsOnly && (pClassDef.access_flags_ & kAccPublic) == 0) {
1405 return;
1406 }
1407
Aart Bikdce50862016-06-10 16:04:03 -07001408 if (gOptions.showSectionHeaders) {
1409 dumpClassDef(pDexFile, idx);
1410 }
1411
1412 if (gOptions.showAnnotations) {
1413 dumpClassAnnotations(pDexFile, idx);
1414 }
1415
1416 if (gOptions.showCfg) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001417 dumpCfg(pDexFile, idx);
1418 return;
1419 }
1420
Aart Bik69ae54a2015-07-01 14:52:26 -07001421 // For the XML output, show the package name. Ideally we'd gather
1422 // up the classes, sort them, and dump them alphabetically so the
1423 // package name wouldn't jump around, but that's not a great plan
1424 // for something that needs to run on the device.
1425 const char* classDescriptor = pDexFile->StringByTypeIdx(pClassDef.class_idx_);
1426 if (!(classDescriptor[0] == 'L' &&
1427 classDescriptor[strlen(classDescriptor)-1] == ';')) {
1428 // Arrays and primitives should not be defined explicitly. Keep going?
1429 fprintf(stderr, "Malformed class name '%s'\n", classDescriptor);
1430 } else if (gOptions.outputFormat == OUTPUT_XML) {
1431 char* mangle = strdup(classDescriptor + 1);
1432 mangle[strlen(mangle)-1] = '\0';
1433
1434 // Reduce to just the package name.
1435 char* lastSlash = strrchr(mangle, '/');
1436 if (lastSlash != nullptr) {
1437 *lastSlash = '\0';
1438 } else {
1439 *mangle = '\0';
1440 }
1441
1442 for (char* cp = mangle; *cp != '\0'; cp++) {
1443 if (*cp == '/') {
1444 *cp = '.';
1445 }
1446 } // for
1447
1448 if (*pLastPackage == nullptr || strcmp(mangle, *pLastPackage) != 0) {
1449 // Start of a new package.
1450 if (*pLastPackage != nullptr) {
1451 fprintf(gOutFile, "</package>\n");
1452 }
1453 fprintf(gOutFile, "<package name=\"%s\"\n>\n", mangle);
1454 free(*pLastPackage);
1455 *pLastPackage = mangle;
1456 } else {
1457 free(mangle);
1458 }
1459 }
1460
1461 // General class information.
1462 char* accessStr = createAccessFlagStr(pClassDef.access_flags_, kAccessForClass);
1463 const char* superclassDescriptor;
Andreas Gampea5b09a62016-11-17 15:21:22 -08001464 if (!pClassDef.superclass_idx_.IsValid()) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001465 superclassDescriptor = nullptr;
1466 } else {
1467 superclassDescriptor = pDexFile->StringByTypeIdx(pClassDef.superclass_idx_);
1468 }
1469 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1470 fprintf(gOutFile, "Class #%d -\n", idx);
1471 fprintf(gOutFile, " Class descriptor : '%s'\n", classDescriptor);
1472 fprintf(gOutFile, " Access flags : 0x%04x (%s)\n", pClassDef.access_flags_, accessStr);
1473 if (superclassDescriptor != nullptr) {
1474 fprintf(gOutFile, " Superclass : '%s'\n", superclassDescriptor);
1475 }
1476 fprintf(gOutFile, " Interfaces -\n");
1477 } else {
Aart Bikc05e2f22016-07-12 15:53:13 -07001478 std::unique_ptr<char[]> dot(descriptorClassToDot(classDescriptor));
1479 fprintf(gOutFile, "<class name=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001480 if (superclassDescriptor != nullptr) {
Aart Bikc05e2f22016-07-12 15:53:13 -07001481 dot = descriptorToDot(superclassDescriptor);
1482 fprintf(gOutFile, " extends=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001483 }
Alex Light1f12e282015-12-10 16:49:47 -08001484 fprintf(gOutFile, " interface=%s\n",
1485 quotedBool((pClassDef.access_flags_ & kAccInterface) != 0));
Aart Bik69ae54a2015-07-01 14:52:26 -07001486 fprintf(gOutFile, " abstract=%s\n", quotedBool((pClassDef.access_flags_ & kAccAbstract) != 0));
1487 fprintf(gOutFile, " static=%s\n", quotedBool((pClassDef.access_flags_ & kAccStatic) != 0));
1488 fprintf(gOutFile, " final=%s\n", quotedBool((pClassDef.access_flags_ & kAccFinal) != 0));
1489 // The "deprecated=" not knowable w/o parsing annotations.
1490 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(pClassDef.access_flags_));
1491 fprintf(gOutFile, ">\n");
1492 }
1493
1494 // Interfaces.
1495 const DexFile::TypeList* pInterfaces = pDexFile->GetInterfacesList(pClassDef);
1496 if (pInterfaces != nullptr) {
1497 for (u4 i = 0; i < pInterfaces->Size(); i++) {
1498 dumpInterface(pDexFile, pInterfaces->GetTypeItem(i), i);
1499 } // for
1500 }
1501
1502 // Fields and methods.
1503 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
1504 if (pEncodedData == nullptr) {
1505 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1506 fprintf(gOutFile, " Static fields -\n");
1507 fprintf(gOutFile, " Instance fields -\n");
1508 fprintf(gOutFile, " Direct methods -\n");
1509 fprintf(gOutFile, " Virtual methods -\n");
1510 }
1511 } else {
1512 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
Aart Bikdce50862016-06-10 16:04:03 -07001513
1514 // Prepare data for static fields.
1515 const u1* sData = pDexFile->GetEncodedStaticFieldValuesArray(pClassDef);
1516 const u4 sSize = sData != nullptr ? DecodeUnsignedLeb128(&sData) : 0;
1517
1518 // Static fields.
Aart Bik69ae54a2015-07-01 14:52:26 -07001519 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1520 fprintf(gOutFile, " Static fields -\n");
1521 }
Aart Bikdce50862016-06-10 16:04:03 -07001522 for (u4 i = 0; pClassData.HasNextStaticField(); i++, pClassData.Next()) {
1523 dumpSField(pDexFile,
1524 pClassData.GetMemberIndex(),
1525 pClassData.GetRawMemberAccessFlags(),
1526 i,
1527 i < sSize ? &sData : nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001528 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001529
1530 // Instance fields.
Aart Bik69ae54a2015-07-01 14:52:26 -07001531 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1532 fprintf(gOutFile, " Instance fields -\n");
1533 }
Aart Bikdce50862016-06-10 16:04:03 -07001534 for (u4 i = 0; pClassData.HasNextInstanceField(); i++, pClassData.Next()) {
1535 dumpIField(pDexFile,
1536 pClassData.GetMemberIndex(),
1537 pClassData.GetRawMemberAccessFlags(),
1538 i);
Aart Bik69ae54a2015-07-01 14:52:26 -07001539 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001540
1541 // Direct methods.
Aart Bik69ae54a2015-07-01 14:52:26 -07001542 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1543 fprintf(gOutFile, " Direct methods -\n");
1544 }
1545 for (int i = 0; pClassData.HasNextDirectMethod(); i++, pClassData.Next()) {
1546 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1547 pClassData.GetRawMemberAccessFlags(),
1548 pClassData.GetMethodCodeItem(),
1549 pClassData.GetMethodCodeItemOffset(), i);
1550 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001551
1552 // Virtual methods.
Aart Bik69ae54a2015-07-01 14:52:26 -07001553 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1554 fprintf(gOutFile, " Virtual methods -\n");
1555 }
1556 for (int i = 0; pClassData.HasNextVirtualMethod(); i++, pClassData.Next()) {
1557 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1558 pClassData.GetRawMemberAccessFlags(),
1559 pClassData.GetMethodCodeItem(),
1560 pClassData.GetMethodCodeItemOffset(), i);
1561 } // for
1562 }
1563
1564 // End of class.
1565 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1566 const char* fileName;
1567 if (pClassDef.source_file_idx_ != DexFile::kDexNoIndex) {
1568 fileName = pDexFile->StringDataByIdx(pClassDef.source_file_idx_);
1569 } else {
1570 fileName = "unknown";
1571 }
1572 fprintf(gOutFile, " source_file_idx : %d (%s)\n\n",
1573 pClassDef.source_file_idx_, fileName);
1574 } else if (gOptions.outputFormat == OUTPUT_XML) {
1575 fprintf(gOutFile, "</class>\n");
1576 }
1577
1578 free(accessStr);
1579}
1580
1581/*
1582 * Dumps the requested sections of the file.
1583 */
Aart Bik7b45a8a2016-10-24 16:07:59 -07001584static void processDexFile(const char* fileName,
1585 const DexFile* pDexFile, size_t i, size_t n) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001586 if (gOptions.verbose) {
Aart Bik7b45a8a2016-10-24 16:07:59 -07001587 fputs("Opened '", gOutFile);
1588 fputs(fileName, gOutFile);
1589 if (n > 1) {
1590 fprintf(gOutFile, ":%s", DexFile::GetMultiDexClassesDexName(i).c_str());
1591 }
1592 fprintf(gOutFile, "', DEX version '%.3s'\n", pDexFile->GetHeader().magic_ + 4);
Aart Bik69ae54a2015-07-01 14:52:26 -07001593 }
1594
1595 // Headers.
1596 if (gOptions.showFileHeaders) {
1597 dumpFileHeader(pDexFile);
1598 }
1599
1600 // Open XML context.
1601 if (gOptions.outputFormat == OUTPUT_XML) {
1602 fprintf(gOutFile, "<api>\n");
1603 }
1604
1605 // Iterate over all classes.
1606 char* package = nullptr;
1607 const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
1608 for (u4 i = 0; i < classDefsSize; i++) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001609 dumpClass(pDexFile, i, &package);
1610 } // for
1611
1612 // Free the last package allocated.
1613 if (package != nullptr) {
1614 fprintf(gOutFile, "</package>\n");
1615 free(package);
1616 }
1617
1618 // Close XML context.
1619 if (gOptions.outputFormat == OUTPUT_XML) {
1620 fprintf(gOutFile, "</api>\n");
1621 }
1622}
1623
1624/*
1625 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
1626 */
1627int processFile(const char* fileName) {
1628 if (gOptions.verbose) {
1629 fprintf(gOutFile, "Processing '%s'...\n", fileName);
1630 }
1631
1632 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
Aart Bikdce50862016-06-10 16:04:03 -07001633 // all of which are Zip archives with "classes.dex" inside.
Aart Bik37d6a3b2016-06-21 18:30:10 -07001634 const bool kVerifyChecksum = !gOptions.ignoreBadChecksum;
Aart Bik69ae54a2015-07-01 14:52:26 -07001635 std::string error_msg;
1636 std::vector<std::unique_ptr<const DexFile>> dex_files;
Aart Bik37d6a3b2016-06-21 18:30:10 -07001637 if (!DexFile::Open(fileName, fileName, kVerifyChecksum, &error_msg, &dex_files)) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001638 // Display returned error message to user. Note that this error behavior
1639 // differs from the error messages shown by the original Dalvik dexdump.
1640 fputs(error_msg.c_str(), stderr);
1641 fputc('\n', stderr);
1642 return -1;
1643 }
1644
Aart Bik4e149602015-07-09 11:45:28 -07001645 // Success. Either report checksum verification or process
1646 // all dex files found in given file.
Aart Bik69ae54a2015-07-01 14:52:26 -07001647 if (gOptions.checksumOnly) {
1648 fprintf(gOutFile, "Checksum verified\n");
1649 } else {
Aart Bik7b45a8a2016-10-24 16:07:59 -07001650 for (size_t i = 0, n = dex_files.size(); i < n; i++) {
1651 processDexFile(fileName, dex_files[i].get(), i, n);
Aart Bik4e149602015-07-09 11:45:28 -07001652 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001653 }
1654 return 0;
1655}
1656
1657} // namespace art