blob: 30de28eaee49a9f66c1c4395f474daaed3f63d4c [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"
48#include "dex_instruction-inl.h"
49
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 Bikdce50862016-06-10 16:04:03 -070069typedef int8_t s1;
70typedef int16_t s2;
Aart Bik69ae54a2015-07-01 14:52:26 -070071typedef int32_t s4;
72typedef int64_t s8;
73
74/*
75 * Basic information about a field or a method.
76 */
77struct FieldMethodInfo {
78 const char* classDescriptor;
79 const char* name;
80 const char* signature;
81};
82
83/*
84 * Flags for use with createAccessFlagStr().
85 */
86enum AccessFor {
87 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
88};
89const int kNumFlags = 18;
90
91/*
92 * Gets 2 little-endian bytes.
93 */
94static inline u2 get2LE(unsigned char const* pSrc) {
95 return pSrc[0] | (pSrc[1] << 8);
96}
97
98/*
99 * Converts a single-character primitive type into human-readable form.
100 */
101static const char* primitiveTypeLabel(char typeChar) {
102 switch (typeChar) {
103 case 'B': return "byte";
104 case 'C': return "char";
105 case 'D': return "double";
106 case 'F': return "float";
107 case 'I': return "int";
108 case 'J': return "long";
109 case 'S': return "short";
110 case 'V': return "void";
111 case 'Z': return "boolean";
112 default: return "UNKNOWN";
113 } // switch
114}
115
116/*
117 * Converts a type descriptor to human-readable "dotted" form. For
118 * example, "Ljava/lang/String;" becomes "java.lang.String", and
119 * "[I" becomes "int[]". Also converts '$' to '.', which means this
120 * form can't be converted back to a descriptor.
121 */
Aart Bikc05e2f22016-07-12 15:53:13 -0700122static std::unique_ptr<char[]> descriptorToDot(const char* str) {
Aart Bik69ae54a2015-07-01 14:52:26 -0700123 int targetLen = strlen(str);
124 int offset = 0;
125
126 // Strip leading [s; will be added to end.
127 while (targetLen > 1 && str[offset] == '[') {
128 offset++;
129 targetLen--;
130 } // while
131
132 const int arrayDepth = offset;
133
134 if (targetLen == 1) {
135 // Primitive type.
136 str = primitiveTypeLabel(str[offset]);
137 offset = 0;
138 targetLen = strlen(str);
139 } else {
140 // Account for leading 'L' and trailing ';'.
141 if (targetLen >= 2 && str[offset] == 'L' &&
142 str[offset + targetLen - 1] == ';') {
143 targetLen -= 2;
144 offset++;
145 }
146 }
147
148 // Copy class name over.
Aart Bikc05e2f22016-07-12 15:53:13 -0700149 std::unique_ptr<char[]> newStr(new char[targetLen + arrayDepth * 2 + 1]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700150 int i = 0;
151 for (; i < targetLen; i++) {
152 const char ch = str[offset + i];
153 newStr[i] = (ch == '/' || ch == '$') ? '.' : ch;
154 } // for
155
156 // Add the appropriate number of brackets for arrays.
157 for (int j = 0; j < arrayDepth; j++) {
158 newStr[i++] = '[';
159 newStr[i++] = ']';
160 } // for
161
162 newStr[i] = '\0';
163 return newStr;
164}
165
166/*
167 * Converts the class name portion of a type descriptor to human-readable
Aart Bikc05e2f22016-07-12 15:53:13 -0700168 * "dotted" form. For example, "Ljava/lang/String;" becomes "String".
Aart Bik69ae54a2015-07-01 14:52:26 -0700169 */
Aart Bikc05e2f22016-07-12 15:53:13 -0700170static std::unique_ptr<char[]> descriptorClassToDot(const char* str) {
171 // Reduce to just the class name prefix.
Aart Bik69ae54a2015-07-01 14:52:26 -0700172 const char* lastSlash = strrchr(str, '/');
173 if (lastSlash == nullptr) {
174 lastSlash = str + 1; // start past 'L'
175 } else {
176 lastSlash++; // start past '/'
177 }
178
Aart Bikc05e2f22016-07-12 15:53:13 -0700179 // Copy class name over, trimming trailing ';'.
180 const int targetLen = strlen(lastSlash);
181 std::unique_ptr<char[]> newStr(new char[targetLen]);
182 for (int i = 0; i < targetLen - 1; i++) {
183 const char ch = lastSlash[i];
184 newStr[i] = ch == '$' ? '.' : ch;
Aart Bik69ae54a2015-07-01 14:52:26 -0700185 } // for
Aart Bikc05e2f22016-07-12 15:53:13 -0700186 newStr[targetLen - 1] = '\0';
Aart Bik69ae54a2015-07-01 14:52:26 -0700187 return newStr;
188}
189
190/*
Aart Bikdce50862016-06-10 16:04:03 -0700191 * Returns string representing the boolean value.
192 */
193static const char* strBool(bool val) {
194 return val ? "true" : "false";
195}
196
197/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700198 * Returns a quoted string representing the boolean value.
199 */
200static const char* quotedBool(bool val) {
201 return val ? "\"true\"" : "\"false\"";
202}
203
204/*
205 * Returns a quoted string representing the access flags.
206 */
207static const char* quotedVisibility(u4 accessFlags) {
208 if (accessFlags & kAccPublic) {
209 return "\"public\"";
210 } else if (accessFlags & kAccProtected) {
211 return "\"protected\"";
212 } else if (accessFlags & kAccPrivate) {
213 return "\"private\"";
214 } else {
215 return "\"package\"";
216 }
217}
218
219/*
220 * Counts the number of '1' bits in a word.
221 */
222static int countOnes(u4 val) {
223 val = val - ((val >> 1) & 0x55555555);
224 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
225 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
226}
227
228/*
229 * Creates a new string with human-readable access flags.
230 *
231 * In the base language the access_flags fields are type u2; in Dalvik
232 * they're u4.
233 */
234static char* createAccessFlagStr(u4 flags, AccessFor forWhat) {
235 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
236 {
237 "PUBLIC", /* 0x00001 */
238 "PRIVATE", /* 0x00002 */
239 "PROTECTED", /* 0x00004 */
240 "STATIC", /* 0x00008 */
241 "FINAL", /* 0x00010 */
242 "?", /* 0x00020 */
243 "?", /* 0x00040 */
244 "?", /* 0x00080 */
245 "?", /* 0x00100 */
246 "INTERFACE", /* 0x00200 */
247 "ABSTRACT", /* 0x00400 */
248 "?", /* 0x00800 */
249 "SYNTHETIC", /* 0x01000 */
250 "ANNOTATION", /* 0x02000 */
251 "ENUM", /* 0x04000 */
252 "?", /* 0x08000 */
253 "VERIFIED", /* 0x10000 */
254 "OPTIMIZED", /* 0x20000 */
255 }, {
256 "PUBLIC", /* 0x00001 */
257 "PRIVATE", /* 0x00002 */
258 "PROTECTED", /* 0x00004 */
259 "STATIC", /* 0x00008 */
260 "FINAL", /* 0x00010 */
261 "SYNCHRONIZED", /* 0x00020 */
262 "BRIDGE", /* 0x00040 */
263 "VARARGS", /* 0x00080 */
264 "NATIVE", /* 0x00100 */
265 "?", /* 0x00200 */
266 "ABSTRACT", /* 0x00400 */
267 "STRICT", /* 0x00800 */
268 "SYNTHETIC", /* 0x01000 */
269 "?", /* 0x02000 */
270 "?", /* 0x04000 */
271 "MIRANDA", /* 0x08000 */
272 "CONSTRUCTOR", /* 0x10000 */
273 "DECLARED_SYNCHRONIZED", /* 0x20000 */
274 }, {
275 "PUBLIC", /* 0x00001 */
276 "PRIVATE", /* 0x00002 */
277 "PROTECTED", /* 0x00004 */
278 "STATIC", /* 0x00008 */
279 "FINAL", /* 0x00010 */
280 "?", /* 0x00020 */
281 "VOLATILE", /* 0x00040 */
282 "TRANSIENT", /* 0x00080 */
283 "?", /* 0x00100 */
284 "?", /* 0x00200 */
285 "?", /* 0x00400 */
286 "?", /* 0x00800 */
287 "SYNTHETIC", /* 0x01000 */
288 "?", /* 0x02000 */
289 "ENUM", /* 0x04000 */
290 "?", /* 0x08000 */
291 "?", /* 0x10000 */
292 "?", /* 0x20000 */
293 },
294 };
295
296 // Allocate enough storage to hold the expected number of strings,
297 // plus a space between each. We over-allocate, using the longest
298 // string above as the base metric.
299 const int kLongest = 21; // The strlen of longest string above.
300 const int count = countOnes(flags);
301 char* str;
302 char* cp;
303 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
304
305 for (int i = 0; i < kNumFlags; i++) {
306 if (flags & 0x01) {
307 const char* accessStr = kAccessStrings[forWhat][i];
308 const int len = strlen(accessStr);
309 if (cp != str) {
310 *cp++ = ' ';
311 }
312 memcpy(cp, accessStr, len);
313 cp += len;
314 }
315 flags >>= 1;
316 } // for
317
318 *cp = '\0';
319 return str;
320}
321
322/*
323 * Copies character data from "data" to "out", converting non-ASCII values
324 * to fprintf format chars or an ASCII filler ('.' or '?').
325 *
326 * The output buffer must be able to hold (2*len)+1 bytes. The result is
327 * NULL-terminated.
328 */
329static void asciify(char* out, const unsigned char* data, size_t len) {
330 while (len--) {
331 if (*data < 0x20) {
332 // Could do more here, but we don't need them yet.
333 switch (*data) {
334 case '\0':
335 *out++ = '\\';
336 *out++ = '0';
337 break;
338 case '\n':
339 *out++ = '\\';
340 *out++ = 'n';
341 break;
342 default:
343 *out++ = '.';
344 break;
345 } // switch
346 } else if (*data >= 0x80) {
347 *out++ = '?';
348 } else {
349 *out++ = *data;
350 }
351 data++;
352 } // while
353 *out = '\0';
354}
355
356/*
Aart Bikdce50862016-06-10 16:04:03 -0700357 * Dumps a string value with some escape characters.
358 */
359static void dumpEscapedString(const char* p) {
360 fputs("\"", gOutFile);
361 for (; *p; p++) {
362 switch (*p) {
363 case '\\':
364 fputs("\\\\", gOutFile);
365 break;
366 case '\"':
367 fputs("\\\"", gOutFile);
368 break;
369 case '\t':
370 fputs("\\t", gOutFile);
371 break;
372 case '\n':
373 fputs("\\n", gOutFile);
374 break;
375 case '\r':
376 fputs("\\r", gOutFile);
377 break;
378 default:
379 putc(*p, gOutFile);
380 } // switch
381 } // for
382 fputs("\"", gOutFile);
383}
384
385/*
386 * Dumps a string as an XML attribute value.
387 */
388static void dumpXmlAttribute(const char* p) {
389 for (; *p; p++) {
390 switch (*p) {
391 case '&':
392 fputs("&amp;", gOutFile);
393 break;
394 case '<':
395 fputs("&lt;", gOutFile);
396 break;
397 case '>':
398 fputs("&gt;", gOutFile);
399 break;
400 case '"':
401 fputs("&quot;", gOutFile);
402 break;
403 case '\t':
404 fputs("&#x9;", gOutFile);
405 break;
406 case '\n':
407 fputs("&#xA;", gOutFile);
408 break;
409 case '\r':
410 fputs("&#xD;", gOutFile);
411 break;
412 default:
413 putc(*p, gOutFile);
414 } // switch
415 } // for
416}
417
418/*
419 * Reads variable width value, possibly sign extended at the last defined byte.
420 */
421static u8 readVarWidth(const u1** data, u1 arg, bool sign_extend) {
422 u8 value = 0;
423 for (u4 i = 0; i <= arg; i++) {
424 value |= static_cast<u8>(*(*data)++) << (i * 8);
425 }
426 if (sign_extend) {
427 int shift = (7 - arg) * 8;
428 return (static_cast<s8>(value) << shift) >> shift;
429 }
430 return value;
431}
432
433/*
434 * Dumps encoded value.
435 */
436static void dumpEncodedValue(const DexFile* pDexFile, const u1** data); // forward
437static void dumpEncodedValue(const DexFile* pDexFile, const u1** data, u1 type, u1 arg) {
438 switch (type) {
439 case DexFile::kDexAnnotationByte:
440 fprintf(gOutFile, "%" PRId8, static_cast<s1>(readVarWidth(data, arg, false)));
441 break;
442 case DexFile::kDexAnnotationShort:
443 fprintf(gOutFile, "%" PRId16, static_cast<s2>(readVarWidth(data, arg, true)));
444 break;
445 case DexFile::kDexAnnotationChar:
446 fprintf(gOutFile, "%" PRIu16, static_cast<u2>(readVarWidth(data, arg, false)));
447 break;
448 case DexFile::kDexAnnotationInt:
449 fprintf(gOutFile, "%" PRId32, static_cast<s4>(readVarWidth(data, arg, true)));
450 break;
451 case DexFile::kDexAnnotationLong:
452 fprintf(gOutFile, "%" PRId64, static_cast<s8>(readVarWidth(data, arg, true)));
453 break;
454 case DexFile::kDexAnnotationFloat: {
455 // Fill on right.
456 union {
457 float f;
458 u4 data;
459 } conv;
460 conv.data = static_cast<u4>(readVarWidth(data, arg, false)) << (3 - arg) * 8;
461 fprintf(gOutFile, "%g", conv.f);
462 break;
463 }
464 case DexFile::kDexAnnotationDouble: {
465 // Fill on right.
466 union {
467 double d;
468 u8 data;
469 } conv;
470 conv.data = readVarWidth(data, arg, false) << (7 - arg) * 8;
471 fprintf(gOutFile, "%g", conv.d);
472 break;
473 }
474 case DexFile::kDexAnnotationString: {
475 const u4 idx = static_cast<u4>(readVarWidth(data, arg, false));
476 if (gOptions.outputFormat == OUTPUT_PLAIN) {
477 dumpEscapedString(pDexFile->StringDataByIdx(idx));
478 } else {
479 dumpXmlAttribute(pDexFile->StringDataByIdx(idx));
480 }
481 break;
482 }
483 case DexFile::kDexAnnotationType: {
484 const u4 str_idx = static_cast<u4>(readVarWidth(data, arg, false));
485 fputs(pDexFile->StringByTypeIdx(str_idx), gOutFile);
486 break;
487 }
488 case DexFile::kDexAnnotationField:
489 case DexFile::kDexAnnotationEnum: {
490 const u4 field_idx = static_cast<u4>(readVarWidth(data, arg, false));
491 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
492 fputs(pDexFile->StringDataByIdx(pFieldId.name_idx_), gOutFile);
493 break;
494 }
495 case DexFile::kDexAnnotationMethod: {
496 const u4 method_idx = static_cast<u4>(readVarWidth(data, arg, false));
497 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
498 fputs(pDexFile->StringDataByIdx(pMethodId.name_idx_), gOutFile);
499 break;
500 }
501 case DexFile::kDexAnnotationArray: {
502 fputc('{', gOutFile);
503 // Decode and display all elements.
504 const u4 size = DecodeUnsignedLeb128(data);
505 for (u4 i = 0; i < size; i++) {
506 fputc(' ', gOutFile);
507 dumpEncodedValue(pDexFile, data);
508 }
509 fputs(" }", gOutFile);
510 break;
511 }
512 case DexFile::kDexAnnotationAnnotation: {
513 const u4 type_idx = DecodeUnsignedLeb128(data);
514 fputs(pDexFile->StringByTypeIdx(type_idx), gOutFile);
515 // Decode and display all name=value pairs.
516 const u4 size = DecodeUnsignedLeb128(data);
517 for (u4 i = 0; i < size; i++) {
518 const u4 name_idx = DecodeUnsignedLeb128(data);
519 fputc(' ', gOutFile);
520 fputs(pDexFile->StringDataByIdx(name_idx), gOutFile);
521 fputc('=', gOutFile);
522 dumpEncodedValue(pDexFile, data);
523 }
524 break;
525 }
526 case DexFile::kDexAnnotationNull:
527 fputs("null", gOutFile);
528 break;
529 case DexFile::kDexAnnotationBoolean:
530 fputs(strBool(arg), gOutFile);
531 break;
532 default:
533 fputs("????", gOutFile);
534 break;
535 } // switch
536}
537
538/*
539 * Dumps encoded value with prefix.
540 */
541static void dumpEncodedValue(const DexFile* pDexFile, const u1** data) {
542 const u1 enc = *(*data)++;
543 dumpEncodedValue(pDexFile, data, enc & 0x1f, enc >> 5);
544}
545
546/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700547 * Dumps the file header.
Aart Bik69ae54a2015-07-01 14:52:26 -0700548 */
549static void dumpFileHeader(const DexFile* pDexFile) {
550 const DexFile::Header& pHeader = pDexFile->GetHeader();
551 char sanitized[sizeof(pHeader.magic_) * 2 + 1];
552 fprintf(gOutFile, "DEX file header:\n");
553 asciify(sanitized, pHeader.magic_, sizeof(pHeader.magic_));
554 fprintf(gOutFile, "magic : '%s'\n", sanitized);
555 fprintf(gOutFile, "checksum : %08x\n", pHeader.checksum_);
556 fprintf(gOutFile, "signature : %02x%02x...%02x%02x\n",
557 pHeader.signature_[0], pHeader.signature_[1],
558 pHeader.signature_[DexFile::kSha1DigestSize - 2],
559 pHeader.signature_[DexFile::kSha1DigestSize - 1]);
560 fprintf(gOutFile, "file_size : %d\n", pHeader.file_size_);
561 fprintf(gOutFile, "header_size : %d\n", pHeader.header_size_);
562 fprintf(gOutFile, "link_size : %d\n", pHeader.link_size_);
563 fprintf(gOutFile, "link_off : %d (0x%06x)\n",
564 pHeader.link_off_, pHeader.link_off_);
565 fprintf(gOutFile, "string_ids_size : %d\n", pHeader.string_ids_size_);
566 fprintf(gOutFile, "string_ids_off : %d (0x%06x)\n",
567 pHeader.string_ids_off_, pHeader.string_ids_off_);
568 fprintf(gOutFile, "type_ids_size : %d\n", pHeader.type_ids_size_);
569 fprintf(gOutFile, "type_ids_off : %d (0x%06x)\n",
570 pHeader.type_ids_off_, pHeader.type_ids_off_);
Aart Bikdce50862016-06-10 16:04:03 -0700571 fprintf(gOutFile, "proto_ids_size : %d\n", pHeader.proto_ids_size_);
572 fprintf(gOutFile, "proto_ids_off : %d (0x%06x)\n",
Aart Bik69ae54a2015-07-01 14:52:26 -0700573 pHeader.proto_ids_off_, pHeader.proto_ids_off_);
574 fprintf(gOutFile, "field_ids_size : %d\n", pHeader.field_ids_size_);
575 fprintf(gOutFile, "field_ids_off : %d (0x%06x)\n",
576 pHeader.field_ids_off_, pHeader.field_ids_off_);
577 fprintf(gOutFile, "method_ids_size : %d\n", pHeader.method_ids_size_);
578 fprintf(gOutFile, "method_ids_off : %d (0x%06x)\n",
579 pHeader.method_ids_off_, pHeader.method_ids_off_);
580 fprintf(gOutFile, "class_defs_size : %d\n", pHeader.class_defs_size_);
581 fprintf(gOutFile, "class_defs_off : %d (0x%06x)\n",
582 pHeader.class_defs_off_, pHeader.class_defs_off_);
583 fprintf(gOutFile, "data_size : %d\n", pHeader.data_size_);
584 fprintf(gOutFile, "data_off : %d (0x%06x)\n\n",
585 pHeader.data_off_, pHeader.data_off_);
586}
587
588/*
589 * Dumps a class_def_item.
590 */
591static void dumpClassDef(const DexFile* pDexFile, int idx) {
592 // General class information.
593 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
594 fprintf(gOutFile, "Class #%d header:\n", idx);
595 fprintf(gOutFile, "class_idx : %d\n", pClassDef.class_idx_);
596 fprintf(gOutFile, "access_flags : %d (0x%04x)\n",
597 pClassDef.access_flags_, pClassDef.access_flags_);
598 fprintf(gOutFile, "superclass_idx : %d\n", pClassDef.superclass_idx_);
599 fprintf(gOutFile, "interfaces_off : %d (0x%06x)\n",
600 pClassDef.interfaces_off_, pClassDef.interfaces_off_);
601 fprintf(gOutFile, "source_file_idx : %d\n", pClassDef.source_file_idx_);
602 fprintf(gOutFile, "annotations_off : %d (0x%06x)\n",
603 pClassDef.annotations_off_, pClassDef.annotations_off_);
604 fprintf(gOutFile, "class_data_off : %d (0x%06x)\n",
605 pClassDef.class_data_off_, pClassDef.class_data_off_);
606
607 // Fields and methods.
608 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
609 if (pEncodedData != nullptr) {
610 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
611 fprintf(gOutFile, "static_fields_size : %d\n", pClassData.NumStaticFields());
612 fprintf(gOutFile, "instance_fields_size: %d\n", pClassData.NumInstanceFields());
613 fprintf(gOutFile, "direct_methods_size : %d\n", pClassData.NumDirectMethods());
614 fprintf(gOutFile, "virtual_methods_size: %d\n", pClassData.NumVirtualMethods());
615 } else {
616 fprintf(gOutFile, "static_fields_size : 0\n");
617 fprintf(gOutFile, "instance_fields_size: 0\n");
618 fprintf(gOutFile, "direct_methods_size : 0\n");
619 fprintf(gOutFile, "virtual_methods_size: 0\n");
620 }
621 fprintf(gOutFile, "\n");
622}
623
Aart Bikdce50862016-06-10 16:04:03 -0700624/**
625 * Dumps an annotation set item.
626 */
627static void dumpAnnotationSetItem(const DexFile* pDexFile, const DexFile::AnnotationSetItem* set_item) {
628 if (set_item == nullptr || set_item->size_ == 0) {
629 fputs(" empty-annotation-set\n", gOutFile);
630 return;
631 }
632 for (u4 i = 0; i < set_item->size_; i++) {
633 const DexFile::AnnotationItem* annotation = pDexFile->GetAnnotationItem(set_item, i);
634 if (annotation == nullptr) {
635 continue;
636 }
637 fputs(" ", gOutFile);
638 switch (annotation->visibility_) {
639 case DexFile::kDexVisibilityBuild: fputs("VISIBILITY_BUILD ", gOutFile); break;
640 case DexFile::kDexVisibilityRuntime: fputs("VISIBILITY_RUNTIME ", gOutFile); break;
641 case DexFile::kDexVisibilitySystem: fputs("VISIBILITY_SYSTEM ", gOutFile); break;
642 default: fputs("VISIBILITY_UNKNOWN ", gOutFile); break;
643 } // switch
644 // Decode raw bytes in annotation.
645 const u1* rData = annotation->annotation_;
646 dumpEncodedValue(pDexFile, &rData, DexFile::kDexAnnotationAnnotation, 0);
647 fputc('\n', gOutFile);
648 }
649}
650
651/*
652 * Dumps class annotations.
653 */
654static void dumpClassAnnotations(const DexFile* pDexFile, int idx) {
655 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
656 const DexFile::AnnotationsDirectoryItem* dir = pDexFile->GetAnnotationsDirectory(pClassDef);
657 if (dir == nullptr) {
658 return; // none
659 }
660
661 fprintf(gOutFile, "Class #%d annotations:\n", idx);
662
663 const DexFile::AnnotationSetItem* class_set_item = pDexFile->GetClassAnnotationSet(dir);
664 const DexFile::FieldAnnotationsItem* fields = pDexFile->GetFieldAnnotations(dir);
665 const DexFile::MethodAnnotationsItem* methods = pDexFile->GetMethodAnnotations(dir);
666 const DexFile::ParameterAnnotationsItem* pars = pDexFile->GetParameterAnnotations(dir);
667
668 // Annotations on the class itself.
669 if (class_set_item != nullptr) {
670 fprintf(gOutFile, "Annotations on class\n");
671 dumpAnnotationSetItem(pDexFile, class_set_item);
672 }
673
674 // Annotations on fields.
675 if (fields != nullptr) {
676 for (u4 i = 0; i < dir->fields_size_; i++) {
677 const u4 field_idx = fields[i].field_idx_;
678 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
679 const char* field_name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
680 fprintf(gOutFile, "Annotations on field #%u '%s'\n", field_idx, field_name);
681 dumpAnnotationSetItem(pDexFile, pDexFile->GetFieldAnnotationSetItem(fields[i]));
682 }
683 }
684
685 // Annotations on methods.
686 if (methods != nullptr) {
687 for (u4 i = 0; i < dir->methods_size_; i++) {
688 const u4 method_idx = methods[i].method_idx_;
689 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
690 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
691 fprintf(gOutFile, "Annotations on method #%u '%s'\n", method_idx, method_name);
692 dumpAnnotationSetItem(pDexFile, pDexFile->GetMethodAnnotationSetItem(methods[i]));
693 }
694 }
695
696 // Annotations on method parameters.
697 if (pars != nullptr) {
698 for (u4 i = 0; i < dir->parameters_size_; i++) {
699 const u4 method_idx = pars[i].method_idx_;
700 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
701 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
702 fprintf(gOutFile, "Annotations on method #%u '%s' parameters\n", method_idx, method_name);
703 const DexFile::AnnotationSetRefList*
704 list = pDexFile->GetParameterAnnotationSetRefList(&pars[i]);
705 if (list != nullptr) {
706 for (u4 j = 0; j < list->size_; j++) {
707 fprintf(gOutFile, "#%u\n", j);
708 dumpAnnotationSetItem(pDexFile, pDexFile->GetSetRefItemItem(&list->list_[j]));
709 }
710 }
711 }
712 }
713
714 fputc('\n', gOutFile);
715}
716
Aart Bik69ae54a2015-07-01 14:52:26 -0700717/*
718 * Dumps an interface that a class declares to implement.
719 */
720static void dumpInterface(const DexFile* pDexFile, const DexFile::TypeItem& pTypeItem, int i) {
721 const char* interfaceName = pDexFile->StringByTypeIdx(pTypeItem.type_idx_);
722 if (gOptions.outputFormat == OUTPUT_PLAIN) {
723 fprintf(gOutFile, " #%d : '%s'\n", i, interfaceName);
724 } else {
Aart Bikc05e2f22016-07-12 15:53:13 -0700725 std::unique_ptr<char[]> dot(descriptorToDot(interfaceName));
726 fprintf(gOutFile, "<implements name=\"%s\">\n</implements>\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -0700727 }
728}
729
730/*
731 * Dumps the catches table associated with the code.
732 */
733static void dumpCatches(const DexFile* pDexFile, const DexFile::CodeItem* pCode) {
734 const u4 triesSize = pCode->tries_size_;
735
736 // No catch table.
737 if (triesSize == 0) {
738 fprintf(gOutFile, " catches : (none)\n");
739 return;
740 }
741
742 // Dump all table entries.
743 fprintf(gOutFile, " catches : %d\n", triesSize);
744 for (u4 i = 0; i < triesSize; i++) {
745 const DexFile::TryItem* pTry = pDexFile->GetTryItems(*pCode, i);
746 const u4 start = pTry->start_addr_;
747 const u4 end = start + pTry->insn_count_;
748 fprintf(gOutFile, " 0x%04x - 0x%04x\n", start, end);
749 for (CatchHandlerIterator it(*pCode, *pTry); it.HasNext(); it.Next()) {
750 const u2 tidx = it.GetHandlerTypeIndex();
751 const char* descriptor =
752 (tidx == DexFile::kDexNoIndex16) ? "<any>" : pDexFile->StringByTypeIdx(tidx);
753 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_) {
837 const char* tp = pDexFile->StringByTypeIdx(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;
1464 if (pClassDef.superclass_idx_ == DexFile::kDexNoIndex16) {
1465 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