blob: d5776fa61eda0d4571436e3526f07a7cf4a9fcb0 [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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080045#include "android-base/stringprintf.h"
46
David Sehrcaacd112016-10-20 16:27:02 -070047#include "dexdump_cfg.h"
Aart Bik69ae54a2015-07-01 14:52:26 -070048#include "dex_file-inl.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080049#include "dex_file_types.h"
Aart Bik69ae54a2015-07-01 14:52:26 -070050#include "dex_instruction-inl.h"
51
52namespace art {
53
54/*
55 * Options parsed in main driver.
56 */
57struct Options gOptions;
58
59/*
Aart Bik4e149602015-07-09 11:45:28 -070060 * Output file. Defaults to stdout.
Aart Bik69ae54a2015-07-01 14:52:26 -070061 */
62FILE* gOutFile = stdout;
63
64/*
65 * Data types that match the definitions in the VM specification.
66 */
67typedef uint8_t u1;
68typedef uint16_t u2;
69typedef uint32_t u4;
70typedef uint64_t u8;
Aart Bikdce50862016-06-10 16:04:03 -070071typedef int8_t s1;
72typedef int16_t s2;
Aart Bik69ae54a2015-07-01 14:52:26 -070073typedef int32_t s4;
74typedef int64_t s8;
75
76/*
77 * Basic information about a field or a method.
78 */
79struct FieldMethodInfo {
80 const char* classDescriptor;
81 const char* name;
82 const char* signature;
83};
84
85/*
86 * Flags for use with createAccessFlagStr().
87 */
88enum AccessFor {
89 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
90};
91const int kNumFlags = 18;
92
93/*
94 * Gets 2 little-endian bytes.
95 */
96static inline u2 get2LE(unsigned char const* pSrc) {
97 return pSrc[0] | (pSrc[1] << 8);
98}
99
100/*
101 * Converts a single-character primitive type into human-readable form.
102 */
103static const char* primitiveTypeLabel(char typeChar) {
104 switch (typeChar) {
105 case 'B': return "byte";
106 case 'C': return "char";
107 case 'D': return "double";
108 case 'F': return "float";
109 case 'I': return "int";
110 case 'J': return "long";
111 case 'S': return "short";
112 case 'V': return "void";
113 case 'Z': return "boolean";
114 default: return "UNKNOWN";
115 } // switch
116}
117
118/*
119 * Converts a type descriptor to human-readable "dotted" form. For
120 * example, "Ljava/lang/String;" becomes "java.lang.String", and
121 * "[I" becomes "int[]". Also converts '$' to '.', which means this
122 * form can't be converted back to a descriptor.
123 */
Aart Bikc05e2f22016-07-12 15:53:13 -0700124static std::unique_ptr<char[]> descriptorToDot(const char* str) {
Aart Bik69ae54a2015-07-01 14:52:26 -0700125 int targetLen = strlen(str);
126 int offset = 0;
127
128 // Strip leading [s; will be added to end.
129 while (targetLen > 1 && str[offset] == '[') {
130 offset++;
131 targetLen--;
132 } // while
133
134 const int arrayDepth = offset;
135
136 if (targetLen == 1) {
137 // Primitive type.
138 str = primitiveTypeLabel(str[offset]);
139 offset = 0;
140 targetLen = strlen(str);
141 } else {
142 // Account for leading 'L' and trailing ';'.
143 if (targetLen >= 2 && str[offset] == 'L' &&
144 str[offset + targetLen - 1] == ';') {
145 targetLen -= 2;
146 offset++;
147 }
148 }
149
150 // Copy class name over.
Aart Bikc05e2f22016-07-12 15:53:13 -0700151 std::unique_ptr<char[]> newStr(new char[targetLen + arrayDepth * 2 + 1]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700152 int i = 0;
153 for (; i < targetLen; i++) {
154 const char ch = str[offset + i];
155 newStr[i] = (ch == '/' || ch == '$') ? '.' : ch;
156 } // for
157
158 // Add the appropriate number of brackets for arrays.
159 for (int j = 0; j < arrayDepth; j++) {
160 newStr[i++] = '[';
161 newStr[i++] = ']';
162 } // for
163
164 newStr[i] = '\0';
165 return newStr;
166}
167
168/*
169 * Converts the class name portion of a type descriptor to human-readable
Aart Bikc05e2f22016-07-12 15:53:13 -0700170 * "dotted" form. For example, "Ljava/lang/String;" becomes "String".
Aart Bik69ae54a2015-07-01 14:52:26 -0700171 */
Aart Bikc05e2f22016-07-12 15:53:13 -0700172static std::unique_ptr<char[]> descriptorClassToDot(const char* str) {
173 // Reduce to just the class name prefix.
Aart Bik69ae54a2015-07-01 14:52:26 -0700174 const char* lastSlash = strrchr(str, '/');
175 if (lastSlash == nullptr) {
176 lastSlash = str + 1; // start past 'L'
177 } else {
178 lastSlash++; // start past '/'
179 }
180
Aart Bikc05e2f22016-07-12 15:53:13 -0700181 // Copy class name over, trimming trailing ';'.
182 const int targetLen = strlen(lastSlash);
183 std::unique_ptr<char[]> newStr(new char[targetLen]);
184 for (int i = 0; i < targetLen - 1; i++) {
185 const char ch = lastSlash[i];
186 newStr[i] = ch == '$' ? '.' : ch;
Aart Bik69ae54a2015-07-01 14:52:26 -0700187 } // for
Aart Bikc05e2f22016-07-12 15:53:13 -0700188 newStr[targetLen - 1] = '\0';
Aart Bik69ae54a2015-07-01 14:52:26 -0700189 return newStr;
190}
191
192/*
Aart Bikdce50862016-06-10 16:04:03 -0700193 * Returns string representing the boolean value.
194 */
195static const char* strBool(bool val) {
196 return val ? "true" : "false";
197}
198
199/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700200 * Returns a quoted string representing the boolean value.
201 */
202static const char* quotedBool(bool val) {
203 return val ? "\"true\"" : "\"false\"";
204}
205
206/*
207 * Returns a quoted string representing the access flags.
208 */
209static const char* quotedVisibility(u4 accessFlags) {
210 if (accessFlags & kAccPublic) {
211 return "\"public\"";
212 } else if (accessFlags & kAccProtected) {
213 return "\"protected\"";
214 } else if (accessFlags & kAccPrivate) {
215 return "\"private\"";
216 } else {
217 return "\"package\"";
218 }
219}
220
221/*
222 * Counts the number of '1' bits in a word.
223 */
224static int countOnes(u4 val) {
225 val = val - ((val >> 1) & 0x55555555);
226 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
227 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
228}
229
230/*
231 * Creates a new string with human-readable access flags.
232 *
233 * In the base language the access_flags fields are type u2; in Dalvik
234 * they're u4.
235 */
236static char* createAccessFlagStr(u4 flags, AccessFor forWhat) {
237 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
238 {
239 "PUBLIC", /* 0x00001 */
240 "PRIVATE", /* 0x00002 */
241 "PROTECTED", /* 0x00004 */
242 "STATIC", /* 0x00008 */
243 "FINAL", /* 0x00010 */
244 "?", /* 0x00020 */
245 "?", /* 0x00040 */
246 "?", /* 0x00080 */
247 "?", /* 0x00100 */
248 "INTERFACE", /* 0x00200 */
249 "ABSTRACT", /* 0x00400 */
250 "?", /* 0x00800 */
251 "SYNTHETIC", /* 0x01000 */
252 "ANNOTATION", /* 0x02000 */
253 "ENUM", /* 0x04000 */
254 "?", /* 0x08000 */
255 "VERIFIED", /* 0x10000 */
256 "OPTIMIZED", /* 0x20000 */
257 }, {
258 "PUBLIC", /* 0x00001 */
259 "PRIVATE", /* 0x00002 */
260 "PROTECTED", /* 0x00004 */
261 "STATIC", /* 0x00008 */
262 "FINAL", /* 0x00010 */
263 "SYNCHRONIZED", /* 0x00020 */
264 "BRIDGE", /* 0x00040 */
265 "VARARGS", /* 0x00080 */
266 "NATIVE", /* 0x00100 */
267 "?", /* 0x00200 */
268 "ABSTRACT", /* 0x00400 */
269 "STRICT", /* 0x00800 */
270 "SYNTHETIC", /* 0x01000 */
271 "?", /* 0x02000 */
272 "?", /* 0x04000 */
273 "MIRANDA", /* 0x08000 */
274 "CONSTRUCTOR", /* 0x10000 */
275 "DECLARED_SYNCHRONIZED", /* 0x20000 */
276 }, {
277 "PUBLIC", /* 0x00001 */
278 "PRIVATE", /* 0x00002 */
279 "PROTECTED", /* 0x00004 */
280 "STATIC", /* 0x00008 */
281 "FINAL", /* 0x00010 */
282 "?", /* 0x00020 */
283 "VOLATILE", /* 0x00040 */
284 "TRANSIENT", /* 0x00080 */
285 "?", /* 0x00100 */
286 "?", /* 0x00200 */
287 "?", /* 0x00400 */
288 "?", /* 0x00800 */
289 "SYNTHETIC", /* 0x01000 */
290 "?", /* 0x02000 */
291 "ENUM", /* 0x04000 */
292 "?", /* 0x08000 */
293 "?", /* 0x10000 */
294 "?", /* 0x20000 */
295 },
296 };
297
298 // Allocate enough storage to hold the expected number of strings,
299 // plus a space between each. We over-allocate, using the longest
300 // string above as the base metric.
301 const int kLongest = 21; // The strlen of longest string above.
302 const int count = countOnes(flags);
303 char* str;
304 char* cp;
305 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
306
307 for (int i = 0; i < kNumFlags; i++) {
308 if (flags & 0x01) {
309 const char* accessStr = kAccessStrings[forWhat][i];
310 const int len = strlen(accessStr);
311 if (cp != str) {
312 *cp++ = ' ';
313 }
314 memcpy(cp, accessStr, len);
315 cp += len;
316 }
317 flags >>= 1;
318 } // for
319
320 *cp = '\0';
321 return str;
322}
323
324/*
325 * Copies character data from "data" to "out", converting non-ASCII values
326 * to fprintf format chars or an ASCII filler ('.' or '?').
327 *
328 * The output buffer must be able to hold (2*len)+1 bytes. The result is
329 * NULL-terminated.
330 */
331static void asciify(char* out, const unsigned char* data, size_t len) {
332 while (len--) {
333 if (*data < 0x20) {
334 // Could do more here, but we don't need them yet.
335 switch (*data) {
336 case '\0':
337 *out++ = '\\';
338 *out++ = '0';
339 break;
340 case '\n':
341 *out++ = '\\';
342 *out++ = 'n';
343 break;
344 default:
345 *out++ = '.';
346 break;
347 } // switch
348 } else if (*data >= 0x80) {
349 *out++ = '?';
350 } else {
351 *out++ = *data;
352 }
353 data++;
354 } // while
355 *out = '\0';
356}
357
358/*
Aart Bikdce50862016-06-10 16:04:03 -0700359 * Dumps a string value with some escape characters.
360 */
361static void dumpEscapedString(const char* p) {
362 fputs("\"", gOutFile);
363 for (; *p; p++) {
364 switch (*p) {
365 case '\\':
366 fputs("\\\\", gOutFile);
367 break;
368 case '\"':
369 fputs("\\\"", gOutFile);
370 break;
371 case '\t':
372 fputs("\\t", gOutFile);
373 break;
374 case '\n':
375 fputs("\\n", gOutFile);
376 break;
377 case '\r':
378 fputs("\\r", gOutFile);
379 break;
380 default:
381 putc(*p, gOutFile);
382 } // switch
383 } // for
384 fputs("\"", gOutFile);
385}
386
387/*
388 * Dumps a string as an XML attribute value.
389 */
390static void dumpXmlAttribute(const char* p) {
391 for (; *p; p++) {
392 switch (*p) {
393 case '&':
394 fputs("&amp;", gOutFile);
395 break;
396 case '<':
397 fputs("&lt;", gOutFile);
398 break;
399 case '>':
400 fputs("&gt;", gOutFile);
401 break;
402 case '"':
403 fputs("&quot;", gOutFile);
404 break;
405 case '\t':
406 fputs("&#x9;", gOutFile);
407 break;
408 case '\n':
409 fputs("&#xA;", gOutFile);
410 break;
411 case '\r':
412 fputs("&#xD;", gOutFile);
413 break;
414 default:
415 putc(*p, gOutFile);
416 } // switch
417 } // for
418}
419
420/*
421 * Reads variable width value, possibly sign extended at the last defined byte.
422 */
423static u8 readVarWidth(const u1** data, u1 arg, bool sign_extend) {
424 u8 value = 0;
425 for (u4 i = 0; i <= arg; i++) {
426 value |= static_cast<u8>(*(*data)++) << (i * 8);
427 }
428 if (sign_extend) {
429 int shift = (7 - arg) * 8;
430 return (static_cast<s8>(value) << shift) >> shift;
431 }
432 return value;
433}
434
435/*
436 * Dumps encoded value.
437 */
438static void dumpEncodedValue(const DexFile* pDexFile, const u1** data); // forward
439static void dumpEncodedValue(const DexFile* pDexFile, const u1** data, u1 type, u1 arg) {
440 switch (type) {
441 case DexFile::kDexAnnotationByte:
442 fprintf(gOutFile, "%" PRId8, static_cast<s1>(readVarWidth(data, arg, false)));
443 break;
444 case DexFile::kDexAnnotationShort:
445 fprintf(gOutFile, "%" PRId16, static_cast<s2>(readVarWidth(data, arg, true)));
446 break;
447 case DexFile::kDexAnnotationChar:
448 fprintf(gOutFile, "%" PRIu16, static_cast<u2>(readVarWidth(data, arg, false)));
449 break;
450 case DexFile::kDexAnnotationInt:
451 fprintf(gOutFile, "%" PRId32, static_cast<s4>(readVarWidth(data, arg, true)));
452 break;
453 case DexFile::kDexAnnotationLong:
454 fprintf(gOutFile, "%" PRId64, static_cast<s8>(readVarWidth(data, arg, true)));
455 break;
456 case DexFile::kDexAnnotationFloat: {
457 // Fill on right.
458 union {
459 float f;
460 u4 data;
461 } conv;
462 conv.data = static_cast<u4>(readVarWidth(data, arg, false)) << (3 - arg) * 8;
463 fprintf(gOutFile, "%g", conv.f);
464 break;
465 }
466 case DexFile::kDexAnnotationDouble: {
467 // Fill on right.
468 union {
469 double d;
470 u8 data;
471 } conv;
472 conv.data = readVarWidth(data, arg, false) << (7 - arg) * 8;
473 fprintf(gOutFile, "%g", conv.d);
474 break;
475 }
476 case DexFile::kDexAnnotationString: {
477 const u4 idx = static_cast<u4>(readVarWidth(data, arg, false));
478 if (gOptions.outputFormat == OUTPUT_PLAIN) {
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800479 dumpEscapedString(pDexFile->StringDataByIdx(dex::StringIndex(idx)));
Aart Bikdce50862016-06-10 16:04:03 -0700480 } else {
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800481 dumpXmlAttribute(pDexFile->StringDataByIdx(dex::StringIndex(idx)));
Aart Bikdce50862016-06-10 16:04:03 -0700482 }
483 break;
484 }
485 case DexFile::kDexAnnotationType: {
486 const u4 str_idx = static_cast<u4>(readVarWidth(data, arg, false));
Andreas Gampea5b09a62016-11-17 15:21:22 -0800487 fputs(pDexFile->StringByTypeIdx(dex::TypeIndex(str_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700488 break;
489 }
490 case DexFile::kDexAnnotationField:
491 case DexFile::kDexAnnotationEnum: {
492 const u4 field_idx = static_cast<u4>(readVarWidth(data, arg, false));
493 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
494 fputs(pDexFile->StringDataByIdx(pFieldId.name_idx_), gOutFile);
495 break;
496 }
497 case DexFile::kDexAnnotationMethod: {
498 const u4 method_idx = static_cast<u4>(readVarWidth(data, arg, false));
499 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
500 fputs(pDexFile->StringDataByIdx(pMethodId.name_idx_), gOutFile);
501 break;
502 }
503 case DexFile::kDexAnnotationArray: {
504 fputc('{', gOutFile);
505 // Decode and display all elements.
506 const u4 size = DecodeUnsignedLeb128(data);
507 for (u4 i = 0; i < size; i++) {
508 fputc(' ', gOutFile);
509 dumpEncodedValue(pDexFile, data);
510 }
511 fputs(" }", gOutFile);
512 break;
513 }
514 case DexFile::kDexAnnotationAnnotation: {
515 const u4 type_idx = DecodeUnsignedLeb128(data);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800516 fputs(pDexFile->StringByTypeIdx(dex::TypeIndex(type_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700517 // Decode and display all name=value pairs.
518 const u4 size = DecodeUnsignedLeb128(data);
519 for (u4 i = 0; i < size; i++) {
520 const u4 name_idx = DecodeUnsignedLeb128(data);
521 fputc(' ', gOutFile);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800522 fputs(pDexFile->StringDataByIdx(dex::StringIndex(name_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700523 fputc('=', gOutFile);
524 dumpEncodedValue(pDexFile, data);
525 }
526 break;
527 }
528 case DexFile::kDexAnnotationNull:
529 fputs("null", gOutFile);
530 break;
531 case DexFile::kDexAnnotationBoolean:
532 fputs(strBool(arg), gOutFile);
533 break;
534 default:
535 fputs("????", gOutFile);
536 break;
537 } // switch
538}
539
540/*
541 * Dumps encoded value with prefix.
542 */
543static void dumpEncodedValue(const DexFile* pDexFile, const u1** data) {
544 const u1 enc = *(*data)++;
545 dumpEncodedValue(pDexFile, data, enc & 0x1f, enc >> 5);
546}
547
548/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700549 * Dumps the file header.
Aart Bik69ae54a2015-07-01 14:52:26 -0700550 */
551static void dumpFileHeader(const DexFile* pDexFile) {
552 const DexFile::Header& pHeader = pDexFile->GetHeader();
553 char sanitized[sizeof(pHeader.magic_) * 2 + 1];
554 fprintf(gOutFile, "DEX file header:\n");
555 asciify(sanitized, pHeader.magic_, sizeof(pHeader.magic_));
556 fprintf(gOutFile, "magic : '%s'\n", sanitized);
557 fprintf(gOutFile, "checksum : %08x\n", pHeader.checksum_);
558 fprintf(gOutFile, "signature : %02x%02x...%02x%02x\n",
559 pHeader.signature_[0], pHeader.signature_[1],
560 pHeader.signature_[DexFile::kSha1DigestSize - 2],
561 pHeader.signature_[DexFile::kSha1DigestSize - 1]);
562 fprintf(gOutFile, "file_size : %d\n", pHeader.file_size_);
563 fprintf(gOutFile, "header_size : %d\n", pHeader.header_size_);
564 fprintf(gOutFile, "link_size : %d\n", pHeader.link_size_);
565 fprintf(gOutFile, "link_off : %d (0x%06x)\n",
566 pHeader.link_off_, pHeader.link_off_);
567 fprintf(gOutFile, "string_ids_size : %d\n", pHeader.string_ids_size_);
568 fprintf(gOutFile, "string_ids_off : %d (0x%06x)\n",
569 pHeader.string_ids_off_, pHeader.string_ids_off_);
570 fprintf(gOutFile, "type_ids_size : %d\n", pHeader.type_ids_size_);
571 fprintf(gOutFile, "type_ids_off : %d (0x%06x)\n",
572 pHeader.type_ids_off_, pHeader.type_ids_off_);
Aart Bikdce50862016-06-10 16:04:03 -0700573 fprintf(gOutFile, "proto_ids_size : %d\n", pHeader.proto_ids_size_);
574 fprintf(gOutFile, "proto_ids_off : %d (0x%06x)\n",
Aart Bik69ae54a2015-07-01 14:52:26 -0700575 pHeader.proto_ids_off_, pHeader.proto_ids_off_);
576 fprintf(gOutFile, "field_ids_size : %d\n", pHeader.field_ids_size_);
577 fprintf(gOutFile, "field_ids_off : %d (0x%06x)\n",
578 pHeader.field_ids_off_, pHeader.field_ids_off_);
579 fprintf(gOutFile, "method_ids_size : %d\n", pHeader.method_ids_size_);
580 fprintf(gOutFile, "method_ids_off : %d (0x%06x)\n",
581 pHeader.method_ids_off_, pHeader.method_ids_off_);
582 fprintf(gOutFile, "class_defs_size : %d\n", pHeader.class_defs_size_);
583 fprintf(gOutFile, "class_defs_off : %d (0x%06x)\n",
584 pHeader.class_defs_off_, pHeader.class_defs_off_);
585 fprintf(gOutFile, "data_size : %d\n", pHeader.data_size_);
586 fprintf(gOutFile, "data_off : %d (0x%06x)\n\n",
587 pHeader.data_off_, pHeader.data_off_);
588}
589
590/*
591 * Dumps a class_def_item.
592 */
593static void dumpClassDef(const DexFile* pDexFile, int idx) {
594 // General class information.
595 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
596 fprintf(gOutFile, "Class #%d header:\n", idx);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800597 fprintf(gOutFile, "class_idx : %d\n", pClassDef.class_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700598 fprintf(gOutFile, "access_flags : %d (0x%04x)\n",
599 pClassDef.access_flags_, pClassDef.access_flags_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800600 fprintf(gOutFile, "superclass_idx : %d\n", pClassDef.superclass_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700601 fprintf(gOutFile, "interfaces_off : %d (0x%06x)\n",
602 pClassDef.interfaces_off_, pClassDef.interfaces_off_);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800603 fprintf(gOutFile, "source_file_idx : %d\n", pClassDef.source_file_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700604 fprintf(gOutFile, "annotations_off : %d (0x%06x)\n",
605 pClassDef.annotations_off_, pClassDef.annotations_off_);
606 fprintf(gOutFile, "class_data_off : %d (0x%06x)\n",
607 pClassDef.class_data_off_, pClassDef.class_data_off_);
608
609 // Fields and methods.
610 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
611 if (pEncodedData != nullptr) {
612 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
613 fprintf(gOutFile, "static_fields_size : %d\n", pClassData.NumStaticFields());
614 fprintf(gOutFile, "instance_fields_size: %d\n", pClassData.NumInstanceFields());
615 fprintf(gOutFile, "direct_methods_size : %d\n", pClassData.NumDirectMethods());
616 fprintf(gOutFile, "virtual_methods_size: %d\n", pClassData.NumVirtualMethods());
617 } else {
618 fprintf(gOutFile, "static_fields_size : 0\n");
619 fprintf(gOutFile, "instance_fields_size: 0\n");
620 fprintf(gOutFile, "direct_methods_size : 0\n");
621 fprintf(gOutFile, "virtual_methods_size: 0\n");
622 }
623 fprintf(gOutFile, "\n");
624}
625
Aart Bikdce50862016-06-10 16:04:03 -0700626/**
627 * Dumps an annotation set item.
628 */
629static void dumpAnnotationSetItem(const DexFile* pDexFile, const DexFile::AnnotationSetItem* set_item) {
630 if (set_item == nullptr || set_item->size_ == 0) {
631 fputs(" empty-annotation-set\n", gOutFile);
632 return;
633 }
634 for (u4 i = 0; i < set_item->size_; i++) {
635 const DexFile::AnnotationItem* annotation = pDexFile->GetAnnotationItem(set_item, i);
636 if (annotation == nullptr) {
637 continue;
638 }
639 fputs(" ", gOutFile);
640 switch (annotation->visibility_) {
641 case DexFile::kDexVisibilityBuild: fputs("VISIBILITY_BUILD ", gOutFile); break;
642 case DexFile::kDexVisibilityRuntime: fputs("VISIBILITY_RUNTIME ", gOutFile); break;
643 case DexFile::kDexVisibilitySystem: fputs("VISIBILITY_SYSTEM ", gOutFile); break;
644 default: fputs("VISIBILITY_UNKNOWN ", gOutFile); break;
645 } // switch
646 // Decode raw bytes in annotation.
647 const u1* rData = annotation->annotation_;
648 dumpEncodedValue(pDexFile, &rData, DexFile::kDexAnnotationAnnotation, 0);
649 fputc('\n', gOutFile);
650 }
651}
652
653/*
654 * Dumps class annotations.
655 */
656static void dumpClassAnnotations(const DexFile* pDexFile, int idx) {
657 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
658 const DexFile::AnnotationsDirectoryItem* dir = pDexFile->GetAnnotationsDirectory(pClassDef);
659 if (dir == nullptr) {
660 return; // none
661 }
662
663 fprintf(gOutFile, "Class #%d annotations:\n", idx);
664
665 const DexFile::AnnotationSetItem* class_set_item = pDexFile->GetClassAnnotationSet(dir);
666 const DexFile::FieldAnnotationsItem* fields = pDexFile->GetFieldAnnotations(dir);
667 const DexFile::MethodAnnotationsItem* methods = pDexFile->GetMethodAnnotations(dir);
668 const DexFile::ParameterAnnotationsItem* pars = pDexFile->GetParameterAnnotations(dir);
669
670 // Annotations on the class itself.
671 if (class_set_item != nullptr) {
672 fprintf(gOutFile, "Annotations on class\n");
673 dumpAnnotationSetItem(pDexFile, class_set_item);
674 }
675
676 // Annotations on fields.
677 if (fields != nullptr) {
678 for (u4 i = 0; i < dir->fields_size_; i++) {
679 const u4 field_idx = fields[i].field_idx_;
680 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
681 const char* field_name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
682 fprintf(gOutFile, "Annotations on field #%u '%s'\n", field_idx, field_name);
683 dumpAnnotationSetItem(pDexFile, pDexFile->GetFieldAnnotationSetItem(fields[i]));
684 }
685 }
686
687 // Annotations on methods.
688 if (methods != nullptr) {
689 for (u4 i = 0; i < dir->methods_size_; i++) {
690 const u4 method_idx = methods[i].method_idx_;
691 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
692 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
693 fprintf(gOutFile, "Annotations on method #%u '%s'\n", method_idx, method_name);
694 dumpAnnotationSetItem(pDexFile, pDexFile->GetMethodAnnotationSetItem(methods[i]));
695 }
696 }
697
698 // Annotations on method parameters.
699 if (pars != nullptr) {
700 for (u4 i = 0; i < dir->parameters_size_; i++) {
701 const u4 method_idx = pars[i].method_idx_;
702 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
703 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
704 fprintf(gOutFile, "Annotations on method #%u '%s' parameters\n", method_idx, method_name);
705 const DexFile::AnnotationSetRefList*
706 list = pDexFile->GetParameterAnnotationSetRefList(&pars[i]);
707 if (list != nullptr) {
708 for (u4 j = 0; j < list->size_; j++) {
709 fprintf(gOutFile, "#%u\n", j);
710 dumpAnnotationSetItem(pDexFile, pDexFile->GetSetRefItemItem(&list->list_[j]));
711 }
712 }
713 }
714 }
715
716 fputc('\n', gOutFile);
717}
718
Aart Bik69ae54a2015-07-01 14:52:26 -0700719/*
720 * Dumps an interface that a class declares to implement.
721 */
722static void dumpInterface(const DexFile* pDexFile, const DexFile::TypeItem& pTypeItem, int i) {
723 const char* interfaceName = pDexFile->StringByTypeIdx(pTypeItem.type_idx_);
724 if (gOptions.outputFormat == OUTPUT_PLAIN) {
725 fprintf(gOutFile, " #%d : '%s'\n", i, interfaceName);
726 } else {
Aart Bikc05e2f22016-07-12 15:53:13 -0700727 std::unique_ptr<char[]> dot(descriptorToDot(interfaceName));
728 fprintf(gOutFile, "<implements name=\"%s\">\n</implements>\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -0700729 }
730}
731
732/*
733 * Dumps the catches table associated with the code.
734 */
735static void dumpCatches(const DexFile* pDexFile, const DexFile::CodeItem* pCode) {
736 const u4 triesSize = pCode->tries_size_;
737
738 // No catch table.
739 if (triesSize == 0) {
740 fprintf(gOutFile, " catches : (none)\n");
741 return;
742 }
743
744 // Dump all table entries.
745 fprintf(gOutFile, " catches : %d\n", triesSize);
746 for (u4 i = 0; i < triesSize; i++) {
747 const DexFile::TryItem* pTry = pDexFile->GetTryItems(*pCode, i);
748 const u4 start = pTry->start_addr_;
749 const u4 end = start + pTry->insn_count_;
750 fprintf(gOutFile, " 0x%04x - 0x%04x\n", start, end);
751 for (CatchHandlerIterator it(*pCode, *pTry); it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800752 const dex::TypeIndex tidx = it.GetHandlerTypeIndex();
753 const char* descriptor = (!tidx.IsValid()) ? "<any>" : pDexFile->StringByTypeIdx(tidx);
Aart Bik69ae54a2015-07-01 14:52:26 -0700754 fprintf(gOutFile, " %s -> 0x%04x\n", descriptor, it.GetHandlerAddress());
755 } // for
756 } // for
757}
758
759/*
760 * Callback for dumping each positions table entry.
761 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000762static bool dumpPositionsCb(void* /*context*/, const DexFile::PositionInfo& entry) {
763 fprintf(gOutFile, " 0x%04x line=%d\n", entry.address_, entry.line_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700764 return false;
765}
766
767/*
768 * Callback for dumping locals table entry.
769 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000770static void dumpLocalsCb(void* /*context*/, const DexFile::LocalInfo& entry) {
771 const char* signature = entry.signature_ != nullptr ? entry.signature_ : "";
Aart Bik69ae54a2015-07-01 14:52:26 -0700772 fprintf(gOutFile, " 0x%04x - 0x%04x reg=%d %s %s %s\n",
David Srbeckyb06e28e2015-12-10 13:15:00 +0000773 entry.start_address_, entry.end_address_, entry.reg_,
774 entry.name_, entry.descriptor_, signature);
Aart Bik69ae54a2015-07-01 14:52:26 -0700775}
776
777/*
778 * Helper for dumpInstruction(), which builds the string
Aart Bika0e33fd2016-07-08 18:32:45 -0700779 * representation for the index in the given instruction.
780 * Returns a pointer to a buffer of sufficient size.
Aart Bik69ae54a2015-07-01 14:52:26 -0700781 */
Aart Bika0e33fd2016-07-08 18:32:45 -0700782static std::unique_ptr<char[]> indexString(const DexFile* pDexFile,
783 const Instruction* pDecInsn,
784 size_t bufSize) {
Orion Hodsonb34bb192016-10-18 17:02:58 +0100785 static const u4 kInvalidIndex = std::numeric_limits<u4>::max();
Aart Bika0e33fd2016-07-08 18:32:45 -0700786 std::unique_ptr<char[]> buf(new char[bufSize]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700787 // Determine index and width of the string.
788 u4 index = 0;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100789 u4 secondary_index = kInvalidIndex;
Aart Bik69ae54a2015-07-01 14:52:26 -0700790 u4 width = 4;
791 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
792 // SOME NOT SUPPORTED:
793 // case Instruction::k20bc:
794 case Instruction::k21c:
795 case Instruction::k35c:
796 // case Instruction::k35ms:
797 case Instruction::k3rc:
798 // case Instruction::k3rms:
799 // case Instruction::k35mi:
800 // case Instruction::k3rmi:
801 index = pDecInsn->VRegB();
802 width = 4;
803 break;
804 case Instruction::k31c:
805 index = pDecInsn->VRegB();
806 width = 8;
807 break;
808 case Instruction::k22c:
809 // case Instruction::k22cs:
810 index = pDecInsn->VRegC();
811 width = 4;
812 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100813 case Instruction::k45cc:
814 case Instruction::k4rcc:
815 index = pDecInsn->VRegB();
816 secondary_index = pDecInsn->VRegH();
817 width = 4;
818 break;
Aart Bik69ae54a2015-07-01 14:52:26 -0700819 default:
820 break;
821 } // switch
822
823 // Determine index type.
824 size_t outSize = 0;
825 switch (Instruction::IndexTypeOf(pDecInsn->Opcode())) {
826 case Instruction::kIndexUnknown:
827 // This function should never get called for this type, but do
828 // something sensible here, just to help with debugging.
Aart Bika0e33fd2016-07-08 18:32:45 -0700829 outSize = snprintf(buf.get(), bufSize, "<unknown-index>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700830 break;
831 case Instruction::kIndexNone:
832 // This function should never get called for this type, but do
833 // something sensible here, just to help with debugging.
Aart Bika0e33fd2016-07-08 18:32:45 -0700834 outSize = snprintf(buf.get(), bufSize, "<no-index>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700835 break;
836 case Instruction::kIndexTypeRef:
837 if (index < pDexFile->GetHeader().type_ids_size_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800838 const char* tp = pDexFile->StringByTypeIdx(dex::TypeIndex(index));
Aart Bika0e33fd2016-07-08 18:32:45 -0700839 outSize = snprintf(buf.get(), bufSize, "%s // type@%0*x", tp, width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700840 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700841 outSize = snprintf(buf.get(), bufSize, "<type?> // type@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700842 }
843 break;
844 case Instruction::kIndexStringRef:
845 if (index < pDexFile->GetHeader().string_ids_size_) {
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800846 const char* st = pDexFile->StringDataByIdx(dex::StringIndex(index));
Aart Bika0e33fd2016-07-08 18:32:45 -0700847 outSize = snprintf(buf.get(), bufSize, "\"%s\" // string@%0*x", st, width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700848 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700849 outSize = snprintf(buf.get(), bufSize, "<string?> // string@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700850 }
851 break;
852 case Instruction::kIndexMethodRef:
853 if (index < pDexFile->GetHeader().method_ids_size_) {
854 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
855 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
856 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
857 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
Aart Bika0e33fd2016-07-08 18:32:45 -0700858 outSize = snprintf(buf.get(), bufSize, "%s.%s:%s // method@%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700859 backDescriptor, name, signature.ToString().c_str(), width, index);
860 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700861 outSize = snprintf(buf.get(), bufSize, "<method?> // method@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700862 }
863 break;
864 case Instruction::kIndexFieldRef:
865 if (index < pDexFile->GetHeader().field_ids_size_) {
866 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(index);
867 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
868 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
869 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
Aart Bika0e33fd2016-07-08 18:32:45 -0700870 outSize = snprintf(buf.get(), bufSize, "%s.%s:%s // field@%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700871 backDescriptor, name, typeDescriptor, width, index);
872 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700873 outSize = snprintf(buf.get(), bufSize, "<field?> // field@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700874 }
875 break;
876 case Instruction::kIndexVtableOffset:
Aart Bika0e33fd2016-07-08 18:32:45 -0700877 outSize = snprintf(buf.get(), bufSize, "[%0*x] // vtable #%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700878 width, index, width, index);
879 break;
880 case Instruction::kIndexFieldOffset:
Aart Bika0e33fd2016-07-08 18:32:45 -0700881 outSize = snprintf(buf.get(), bufSize, "[obj+%0*x]", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700882 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100883 case Instruction::kIndexMethodAndProtoRef: {
884 std::string method("<method?>");
885 std::string proto("<proto?>");
886 if (index < pDexFile->GetHeader().method_ids_size_) {
887 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
888 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
889 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
890 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800891 method = android::base::StringPrintf("%s.%s:%s",
892 backDescriptor,
893 name,
894 signature.ToString().c_str());
Orion Hodsonb34bb192016-10-18 17:02:58 +0100895 }
896 if (secondary_index < pDexFile->GetHeader().proto_ids_size_) {
897 const DexFile::ProtoId& protoId = pDexFile->GetProtoId(secondary_index);
898 const Signature signature = pDexFile->GetProtoSignature(protoId);
899 proto = signature.ToString();
900 }
901 outSize = snprintf(buf.get(), bufSize, "%s, %s // method@%0*x, proto@%0*x",
902 method.c_str(), proto.c_str(), width, index, width, secondary_index);
903 }
904 break;
Aart Bik69ae54a2015-07-01 14:52:26 -0700905 // SOME NOT SUPPORTED:
906 // case Instruction::kIndexVaries:
907 // case Instruction::kIndexInlineMethod:
908 default:
Aart Bika0e33fd2016-07-08 18:32:45 -0700909 outSize = snprintf(buf.get(), bufSize, "<?>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700910 break;
911 } // switch
912
913 // Determine success of string construction.
914 if (outSize >= bufSize) {
Aart Bika0e33fd2016-07-08 18:32:45 -0700915 // The buffer wasn't big enough; retry with computed size. Note: snprintf()
916 // doesn't count/ the '\0' as part of its returned size, so we add explicit
917 // space for it here.
918 return indexString(pDexFile, pDecInsn, outSize + 1);
Aart Bik69ae54a2015-07-01 14:52:26 -0700919 }
920 return buf;
921}
922
923/*
924 * Dumps a single instruction.
925 */
926static void dumpInstruction(const DexFile* pDexFile,
927 const DexFile::CodeItem* pCode,
928 u4 codeOffset, u4 insnIdx, u4 insnWidth,
929 const Instruction* pDecInsn) {
930 // Address of instruction (expressed as byte offset).
931 fprintf(gOutFile, "%06x:", codeOffset + 0x10 + insnIdx * 2);
932
933 // Dump (part of) raw bytes.
934 const u2* insns = pCode->insns_;
935 for (u4 i = 0; i < 8; i++) {
936 if (i < insnWidth) {
937 if (i == 7) {
938 fprintf(gOutFile, " ... ");
939 } else {
940 // Print 16-bit value in little-endian order.
941 const u1* bytePtr = (const u1*) &insns[insnIdx + i];
942 fprintf(gOutFile, " %02x%02x", bytePtr[0], bytePtr[1]);
943 }
944 } else {
945 fputs(" ", gOutFile);
946 }
947 } // for
948
949 // Dump pseudo-instruction or opcode.
950 if (pDecInsn->Opcode() == Instruction::NOP) {
951 const u2 instr = get2LE((const u1*) &insns[insnIdx]);
952 if (instr == Instruction::kPackedSwitchSignature) {
953 fprintf(gOutFile, "|%04x: packed-switch-data (%d units)", insnIdx, insnWidth);
954 } else if (instr == Instruction::kSparseSwitchSignature) {
955 fprintf(gOutFile, "|%04x: sparse-switch-data (%d units)", insnIdx, insnWidth);
956 } else if (instr == Instruction::kArrayDataSignature) {
957 fprintf(gOutFile, "|%04x: array-data (%d units)", insnIdx, insnWidth);
958 } else {
959 fprintf(gOutFile, "|%04x: nop // spacer", insnIdx);
960 }
961 } else {
962 fprintf(gOutFile, "|%04x: %s", insnIdx, pDecInsn->Name());
963 }
964
965 // Set up additional argument.
Aart Bika0e33fd2016-07-08 18:32:45 -0700966 std::unique_ptr<char[]> indexBuf;
Aart Bik69ae54a2015-07-01 14:52:26 -0700967 if (Instruction::IndexTypeOf(pDecInsn->Opcode()) != Instruction::kIndexNone) {
Aart Bika0e33fd2016-07-08 18:32:45 -0700968 indexBuf = indexString(pDexFile, pDecInsn, 200);
Aart Bik69ae54a2015-07-01 14:52:26 -0700969 }
970
971 // Dump the instruction.
972 //
973 // NOTE: pDecInsn->DumpString(pDexFile) differs too much from original.
974 //
975 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
976 case Instruction::k10x: // op
977 break;
978 case Instruction::k12x: // op vA, vB
979 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
980 break;
981 case Instruction::k11n: // op vA, #+B
982 fprintf(gOutFile, " v%d, #int %d // #%x",
983 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u1)pDecInsn->VRegB());
984 break;
985 case Instruction::k11x: // op vAA
986 fprintf(gOutFile, " v%d", pDecInsn->VRegA());
987 break;
988 case Instruction::k10t: // op +AA
Aart Bikdce50862016-06-10 16:04:03 -0700989 case Instruction::k20t: { // op +AAAA
990 const s4 targ = (s4) pDecInsn->VRegA();
991 fprintf(gOutFile, " %04x // %c%04x",
992 insnIdx + targ,
993 (targ < 0) ? '-' : '+',
994 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -0700995 break;
Aart Bikdce50862016-06-10 16:04:03 -0700996 }
Aart Bik69ae54a2015-07-01 14:52:26 -0700997 case Instruction::k22x: // op vAA, vBBBB
998 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
999 break;
Aart Bikdce50862016-06-10 16:04:03 -07001000 case Instruction::k21t: { // op vAA, +BBBB
1001 const s4 targ = (s4) pDecInsn->VRegB();
1002 fprintf(gOutFile, " v%d, %04x // %c%04x", pDecInsn->VRegA(),
1003 insnIdx + targ,
1004 (targ < 0) ? '-' : '+',
1005 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001006 break;
Aart Bikdce50862016-06-10 16:04:03 -07001007 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001008 case Instruction::k21s: // op vAA, #+BBBB
1009 fprintf(gOutFile, " v%d, #int %d // #%x",
1010 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u2)pDecInsn->VRegB());
1011 break;
1012 case Instruction::k21h: // op vAA, #+BBBB0000[00000000]
1013 // The printed format varies a bit based on the actual opcode.
1014 if (pDecInsn->Opcode() == Instruction::CONST_HIGH16) {
1015 const s4 value = pDecInsn->VRegB() << 16;
1016 fprintf(gOutFile, " v%d, #int %d // #%x",
1017 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
1018 } else {
1019 const s8 value = ((s8) pDecInsn->VRegB()) << 48;
1020 fprintf(gOutFile, " v%d, #long %" PRId64 " // #%x",
1021 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
1022 }
1023 break;
1024 case Instruction::k21c: // op vAA, thing@BBBB
1025 case Instruction::k31c: // op vAA, thing@BBBBBBBB
Aart Bika0e33fd2016-07-08 18:32:45 -07001026 fprintf(gOutFile, " v%d, %s", pDecInsn->VRegA(), indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001027 break;
1028 case Instruction::k23x: // op vAA, vBB, vCC
1029 fprintf(gOutFile, " v%d, v%d, v%d",
1030 pDecInsn->VRegA(), pDecInsn->VRegB(), pDecInsn->VRegC());
1031 break;
1032 case Instruction::k22b: // op vAA, vBB, #+CC
1033 fprintf(gOutFile, " v%d, v%d, #int %d // #%02x",
1034 pDecInsn->VRegA(), pDecInsn->VRegB(),
1035 (s4) pDecInsn->VRegC(), (u1) pDecInsn->VRegC());
1036 break;
Aart Bikdce50862016-06-10 16:04:03 -07001037 case Instruction::k22t: { // op vA, vB, +CCCC
1038 const s4 targ = (s4) pDecInsn->VRegC();
1039 fprintf(gOutFile, " v%d, v%d, %04x // %c%04x",
1040 pDecInsn->VRegA(), pDecInsn->VRegB(),
1041 insnIdx + targ,
1042 (targ < 0) ? '-' : '+',
1043 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001044 break;
Aart Bikdce50862016-06-10 16:04:03 -07001045 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001046 case Instruction::k22s: // op vA, vB, #+CCCC
1047 fprintf(gOutFile, " v%d, v%d, #int %d // #%04x",
1048 pDecInsn->VRegA(), pDecInsn->VRegB(),
1049 (s4) pDecInsn->VRegC(), (u2) pDecInsn->VRegC());
1050 break;
1051 case Instruction::k22c: // op vA, vB, thing@CCCC
1052 // NOT SUPPORTED:
1053 // case Instruction::k22cs: // [opt] op vA, vB, field offset CCCC
1054 fprintf(gOutFile, " v%d, v%d, %s",
Aart Bika0e33fd2016-07-08 18:32:45 -07001055 pDecInsn->VRegA(), pDecInsn->VRegB(), indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001056 break;
1057 case Instruction::k30t:
1058 fprintf(gOutFile, " #%08x", pDecInsn->VRegA());
1059 break;
Aart Bikdce50862016-06-10 16:04:03 -07001060 case Instruction::k31i: { // op vAA, #+BBBBBBBB
1061 // This is often, but not always, a float.
1062 union {
1063 float f;
1064 u4 i;
1065 } conv;
1066 conv.i = pDecInsn->VRegB();
1067 fprintf(gOutFile, " v%d, #float %g // #%08x",
1068 pDecInsn->VRegA(), conv.f, pDecInsn->VRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001069 break;
Aart Bikdce50862016-06-10 16:04:03 -07001070 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001071 case Instruction::k31t: // op vAA, offset +BBBBBBBB
1072 fprintf(gOutFile, " v%d, %08x // +%08x",
1073 pDecInsn->VRegA(), insnIdx + pDecInsn->VRegB(), pDecInsn->VRegB());
1074 break;
1075 case Instruction::k32x: // op vAAAA, vBBBB
1076 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
1077 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +01001078 case Instruction::k35c: // op {vC, vD, vE, vF, vG}, thing@BBBB
1079 case Instruction::k45cc: { // op {vC, vD, vE, vF, vG}, method@BBBB, proto@HHHH
Aart Bik69ae54a2015-07-01 14:52:26 -07001080 // NOT SUPPORTED:
1081 // case Instruction::k35ms: // [opt] invoke-virtual+super
1082 // case Instruction::k35mi: // [opt] inline invoke
Aart Bikdce50862016-06-10 16:04:03 -07001083 u4 arg[Instruction::kMaxVarArgRegs];
1084 pDecInsn->GetVarArgs(arg);
1085 fputs(" {", gOutFile);
1086 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1087 if (i == 0) {
1088 fprintf(gOutFile, "v%d", arg[i]);
1089 } else {
1090 fprintf(gOutFile, ", v%d", arg[i]);
1091 }
1092 } // for
Aart Bika0e33fd2016-07-08 18:32:45 -07001093 fprintf(gOutFile, "}, %s", indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001094 break;
Aart Bikdce50862016-06-10 16:04:03 -07001095 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001096 case Instruction::k3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB
Orion Hodsonb34bb192016-10-18 17:02:58 +01001097 case Instruction::k4rcc: { // op {vCCCC .. v(CCCC+AA-1)}, method@BBBB, proto@HHHH
Aart Bik69ae54a2015-07-01 14:52:26 -07001098 // NOT SUPPORTED:
1099 // case Instruction::k3rms: // [opt] invoke-virtual+super/range
1100 // case Instruction::k3rmi: // [opt] execute-inline/range
Aart Bik69ae54a2015-07-01 14:52:26 -07001101 // This doesn't match the "dx" output when some of the args are
1102 // 64-bit values -- dx only shows the first register.
1103 fputs(" {", gOutFile);
1104 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1105 if (i == 0) {
1106 fprintf(gOutFile, "v%d", pDecInsn->VRegC() + i);
1107 } else {
1108 fprintf(gOutFile, ", v%d", pDecInsn->VRegC() + i);
1109 }
1110 } // for
Aart Bika0e33fd2016-07-08 18:32:45 -07001111 fprintf(gOutFile, "}, %s", indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001112 }
1113 break;
Aart Bikdce50862016-06-10 16:04:03 -07001114 case Instruction::k51l: { // op vAA, #+BBBBBBBBBBBBBBBB
1115 // This is often, but not always, a double.
1116 union {
1117 double d;
1118 u8 j;
1119 } conv;
1120 conv.j = pDecInsn->WideVRegB();
1121 fprintf(gOutFile, " v%d, #double %g // #%016" PRIx64,
1122 pDecInsn->VRegA(), conv.d, pDecInsn->WideVRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001123 break;
Aart Bikdce50862016-06-10 16:04:03 -07001124 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001125 // NOT SUPPORTED:
1126 // case Instruction::k00x: // unknown op or breakpoint
1127 // break;
1128 default:
1129 fprintf(gOutFile, " ???");
1130 break;
1131 } // switch
1132
1133 fputc('\n', gOutFile);
Aart Bik69ae54a2015-07-01 14:52:26 -07001134}
1135
1136/*
1137 * Dumps a bytecode disassembly.
1138 */
1139static void dumpBytecodes(const DexFile* pDexFile, u4 idx,
1140 const DexFile::CodeItem* pCode, u4 codeOffset) {
1141 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
1142 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
1143 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
1144 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
1145
1146 // Generate header.
Aart Bikc05e2f22016-07-12 15:53:13 -07001147 std::unique_ptr<char[]> dot(descriptorToDot(backDescriptor));
1148 fprintf(gOutFile, "%06x: |[%06x] %s.%s:%s\n",
1149 codeOffset, codeOffset, dot.get(), name, signature.ToString().c_str());
Aart Bik69ae54a2015-07-01 14:52:26 -07001150
1151 // Iterate over all instructions.
1152 const u2* insns = pCode->insns_;
1153 for (u4 insnIdx = 0; insnIdx < pCode->insns_size_in_code_units_;) {
1154 const Instruction* instruction = Instruction::At(&insns[insnIdx]);
1155 const u4 insnWidth = instruction->SizeInCodeUnits();
1156 if (insnWidth == 0) {
1157 fprintf(stderr, "GLITCH: zero-width instruction at idx=0x%04x\n", insnIdx);
1158 break;
1159 }
1160 dumpInstruction(pDexFile, pCode, codeOffset, insnIdx, insnWidth, instruction);
1161 insnIdx += insnWidth;
1162 } // for
1163}
1164
1165/*
1166 * Dumps code of a method.
1167 */
1168static void dumpCode(const DexFile* pDexFile, u4 idx, u4 flags,
1169 const DexFile::CodeItem* pCode, u4 codeOffset) {
1170 fprintf(gOutFile, " registers : %d\n", pCode->registers_size_);
1171 fprintf(gOutFile, " ins : %d\n", pCode->ins_size_);
1172 fprintf(gOutFile, " outs : %d\n", pCode->outs_size_);
1173 fprintf(gOutFile, " insns size : %d 16-bit code units\n",
1174 pCode->insns_size_in_code_units_);
1175
1176 // Bytecode disassembly, if requested.
1177 if (gOptions.disassemble) {
1178 dumpBytecodes(pDexFile, idx, pCode, codeOffset);
1179 }
1180
1181 // Try-catch blocks.
1182 dumpCatches(pDexFile, pCode);
1183
1184 // Positions and locals table in the debug info.
1185 bool is_static = (flags & kAccStatic) != 0;
1186 fprintf(gOutFile, " positions : \n");
David Srbeckyb06e28e2015-12-10 13:15:00 +00001187 pDexFile->DecodeDebugPositionInfo(pCode, dumpPositionsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001188 fprintf(gOutFile, " locals : \n");
David Srbeckyb06e28e2015-12-10 13:15:00 +00001189 pDexFile->DecodeDebugLocalInfo(pCode, is_static, idx, dumpLocalsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001190}
1191
1192/*
1193 * Dumps a method.
1194 */
1195static void dumpMethod(const DexFile* pDexFile, u4 idx, u4 flags,
1196 const DexFile::CodeItem* pCode, u4 codeOffset, int i) {
1197 // Bail for anything private if export only requested.
1198 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1199 return;
1200 }
1201
1202 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
1203 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
1204 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
1205 char* typeDescriptor = strdup(signature.ToString().c_str());
1206 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
1207 char* accessStr = createAccessFlagStr(flags, kAccessForMethod);
1208
1209 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1210 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1211 fprintf(gOutFile, " name : '%s'\n", name);
1212 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1213 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
1214 if (pCode == nullptr) {
1215 fprintf(gOutFile, " code : (none)\n");
1216 } else {
1217 fprintf(gOutFile, " code -\n");
1218 dumpCode(pDexFile, idx, flags, pCode, codeOffset);
1219 }
1220 if (gOptions.disassemble) {
1221 fputc('\n', gOutFile);
1222 }
1223 } else if (gOptions.outputFormat == OUTPUT_XML) {
1224 const bool constructor = (name[0] == '<');
1225
1226 // Method name and prototype.
1227 if (constructor) {
Aart Bikc05e2f22016-07-12 15:53:13 -07001228 std::unique_ptr<char[]> dot(descriptorClassToDot(backDescriptor));
1229 fprintf(gOutFile, "<constructor name=\"%s\"\n", dot.get());
1230 dot = descriptorToDot(backDescriptor);
1231 fprintf(gOutFile, " type=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001232 } else {
1233 fprintf(gOutFile, "<method name=\"%s\"\n", name);
1234 const char* returnType = strrchr(typeDescriptor, ')');
1235 if (returnType == nullptr) {
1236 fprintf(stderr, "bad method type descriptor '%s'\n", typeDescriptor);
1237 goto bail;
1238 }
Aart Bikc05e2f22016-07-12 15:53:13 -07001239 std::unique_ptr<char[]> dot(descriptorToDot(returnType + 1));
1240 fprintf(gOutFile, " return=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001241 fprintf(gOutFile, " abstract=%s\n", quotedBool((flags & kAccAbstract) != 0));
1242 fprintf(gOutFile, " native=%s\n", quotedBool((flags & kAccNative) != 0));
1243 fprintf(gOutFile, " synchronized=%s\n", quotedBool(
1244 (flags & (kAccSynchronized | kAccDeclaredSynchronized)) != 0));
1245 }
1246
1247 // Additional method flags.
1248 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1249 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1250 // The "deprecated=" not knowable w/o parsing annotations.
1251 fprintf(gOutFile, " visibility=%s\n>\n", quotedVisibility(flags));
1252
1253 // Parameters.
1254 if (typeDescriptor[0] != '(') {
1255 fprintf(stderr, "ERROR: bad descriptor '%s'\n", typeDescriptor);
1256 goto bail;
1257 }
1258 char* tmpBuf = reinterpret_cast<char*>(malloc(strlen(typeDescriptor) + 1));
1259 const char* base = typeDescriptor + 1;
1260 int argNum = 0;
1261 while (*base != ')') {
1262 char* cp = tmpBuf;
1263 while (*base == '[') {
1264 *cp++ = *base++;
1265 }
1266 if (*base == 'L') {
1267 // Copy through ';'.
1268 do {
1269 *cp = *base++;
1270 } while (*cp++ != ';');
1271 } else {
1272 // Primitive char, copy it.
Aart Bikc05e2f22016-07-12 15:53:13 -07001273 if (strchr("ZBCSIFJD", *base) == nullptr) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001274 fprintf(stderr, "ERROR: bad method signature '%s'\n", base);
Aart Bika0e33fd2016-07-08 18:32:45 -07001275 break; // while
Aart Bik69ae54a2015-07-01 14:52:26 -07001276 }
1277 *cp++ = *base++;
1278 }
1279 // Null terminate and display.
1280 *cp++ = '\0';
Aart Bikc05e2f22016-07-12 15:53:13 -07001281 std::unique_ptr<char[]> dot(descriptorToDot(tmpBuf));
Aart Bik69ae54a2015-07-01 14:52:26 -07001282 fprintf(gOutFile, "<parameter name=\"arg%d\" type=\"%s\">\n"
Aart Bikc05e2f22016-07-12 15:53:13 -07001283 "</parameter>\n", argNum++, dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001284 } // while
1285 free(tmpBuf);
1286 if (constructor) {
1287 fprintf(gOutFile, "</constructor>\n");
1288 } else {
1289 fprintf(gOutFile, "</method>\n");
1290 }
1291 }
1292
1293 bail:
1294 free(typeDescriptor);
1295 free(accessStr);
1296}
1297
1298/*
1299 * Dumps a static (class) field.
1300 */
Aart Bikdce50862016-06-10 16:04:03 -07001301static void dumpSField(const DexFile* pDexFile, u4 idx, u4 flags, int i, const u1** data) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001302 // Bail for anything private if export only requested.
1303 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1304 return;
1305 }
1306
1307 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(idx);
1308 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
1309 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
1310 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
1311 char* accessStr = createAccessFlagStr(flags, kAccessForField);
1312
1313 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1314 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1315 fprintf(gOutFile, " name : '%s'\n", name);
1316 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1317 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
Aart Bikdce50862016-06-10 16:04:03 -07001318 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001319 fputs(" value : ", gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -07001320 dumpEncodedValue(pDexFile, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001321 fputs("\n", gOutFile);
1322 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001323 } else if (gOptions.outputFormat == OUTPUT_XML) {
1324 fprintf(gOutFile, "<field name=\"%s\"\n", name);
Aart Bikc05e2f22016-07-12 15:53:13 -07001325 std::unique_ptr<char[]> dot(descriptorToDot(typeDescriptor));
1326 fprintf(gOutFile, " type=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001327 fprintf(gOutFile, " transient=%s\n", quotedBool((flags & kAccTransient) != 0));
1328 fprintf(gOutFile, " volatile=%s\n", quotedBool((flags & kAccVolatile) != 0));
1329 // The "value=" is not knowable w/o parsing annotations.
1330 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1331 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1332 // The "deprecated=" is not knowable w/o parsing annotations.
1333 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(flags));
Aart Bikdce50862016-06-10 16:04:03 -07001334 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001335 fputs(" value=\"", gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -07001336 dumpEncodedValue(pDexFile, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001337 fputs("\"\n", gOutFile);
1338 }
1339 fputs(">\n</field>\n", gOutFile);
Aart Bik69ae54a2015-07-01 14:52:26 -07001340 }
1341
1342 free(accessStr);
1343}
1344
1345/*
1346 * Dumps an instance field.
1347 */
1348static void dumpIField(const DexFile* pDexFile, u4 idx, u4 flags, int i) {
Aart Bikdce50862016-06-10 16:04:03 -07001349 dumpSField(pDexFile, idx, flags, i, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001350}
1351
1352/*
Andreas Gampe5073fed2015-08-10 11:40:25 -07001353 * Dumping a CFG. Note that this will do duplicate work. utils.h doesn't expose the code-item
1354 * version, so the DumpMethodCFG code will have to iterate again to find it. But dexdump is a
1355 * tool, so this is not performance-critical.
1356 */
1357
1358static void dumpCfg(const DexFile* dex_file,
Aart Bikdce50862016-06-10 16:04:03 -07001359 u4 dex_method_idx,
Andreas Gampe5073fed2015-08-10 11:40:25 -07001360 const DexFile::CodeItem* code_item) {
1361 if (code_item != nullptr) {
1362 std::ostringstream oss;
1363 DumpMethodCFG(dex_file, dex_method_idx, oss);
David Sehrcaacd112016-10-20 16:27:02 -07001364 fputs(oss.str().c_str(), gOutFile);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001365 }
1366}
1367
1368static void dumpCfg(const DexFile* dex_file, int idx) {
1369 const DexFile::ClassDef& class_def = dex_file->GetClassDef(idx);
Aart Bikdce50862016-06-10 16:04:03 -07001370 const u1* class_data = dex_file->GetClassData(class_def);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001371 if (class_data == nullptr) { // empty class such as a marker interface?
1372 return;
1373 }
1374 ClassDataItemIterator it(*dex_file, class_data);
1375 while (it.HasNextStaticField()) {
1376 it.Next();
1377 }
1378 while (it.HasNextInstanceField()) {
1379 it.Next();
1380 }
1381 while (it.HasNextDirectMethod()) {
1382 dumpCfg(dex_file,
1383 it.GetMemberIndex(),
1384 it.GetMethodCodeItem());
1385 it.Next();
1386 }
1387 while (it.HasNextVirtualMethod()) {
1388 dumpCfg(dex_file,
1389 it.GetMemberIndex(),
1390 it.GetMethodCodeItem());
1391 it.Next();
1392 }
1393}
1394
1395/*
Aart Bik69ae54a2015-07-01 14:52:26 -07001396 * Dumps the class.
1397 *
1398 * Note "idx" is a DexClassDef index, not a DexTypeId index.
1399 *
1400 * If "*pLastPackage" is nullptr or does not match the current class' package,
1401 * the value will be replaced with a newly-allocated string.
1402 */
1403static void dumpClass(const DexFile* pDexFile, int idx, char** pLastPackage) {
1404 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
1405
1406 // Omitting non-public class.
1407 if (gOptions.exportsOnly && (pClassDef.access_flags_ & kAccPublic) == 0) {
1408 return;
1409 }
1410
Aart Bikdce50862016-06-10 16:04:03 -07001411 if (gOptions.showSectionHeaders) {
1412 dumpClassDef(pDexFile, idx);
1413 }
1414
1415 if (gOptions.showAnnotations) {
1416 dumpClassAnnotations(pDexFile, idx);
1417 }
1418
1419 if (gOptions.showCfg) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001420 dumpCfg(pDexFile, idx);
1421 return;
1422 }
1423
Aart Bik69ae54a2015-07-01 14:52:26 -07001424 // For the XML output, show the package name. Ideally we'd gather
1425 // up the classes, sort them, and dump them alphabetically so the
1426 // package name wouldn't jump around, but that's not a great plan
1427 // for something that needs to run on the device.
1428 const char* classDescriptor = pDexFile->StringByTypeIdx(pClassDef.class_idx_);
1429 if (!(classDescriptor[0] == 'L' &&
1430 classDescriptor[strlen(classDescriptor)-1] == ';')) {
1431 // Arrays and primitives should not be defined explicitly. Keep going?
1432 fprintf(stderr, "Malformed class name '%s'\n", classDescriptor);
1433 } else if (gOptions.outputFormat == OUTPUT_XML) {
1434 char* mangle = strdup(classDescriptor + 1);
1435 mangle[strlen(mangle)-1] = '\0';
1436
1437 // Reduce to just the package name.
1438 char* lastSlash = strrchr(mangle, '/');
1439 if (lastSlash != nullptr) {
1440 *lastSlash = '\0';
1441 } else {
1442 *mangle = '\0';
1443 }
1444
1445 for (char* cp = mangle; *cp != '\0'; cp++) {
1446 if (*cp == '/') {
1447 *cp = '.';
1448 }
1449 } // for
1450
1451 if (*pLastPackage == nullptr || strcmp(mangle, *pLastPackage) != 0) {
1452 // Start of a new package.
1453 if (*pLastPackage != nullptr) {
1454 fprintf(gOutFile, "</package>\n");
1455 }
1456 fprintf(gOutFile, "<package name=\"%s\"\n>\n", mangle);
1457 free(*pLastPackage);
1458 *pLastPackage = mangle;
1459 } else {
1460 free(mangle);
1461 }
1462 }
1463
1464 // General class information.
1465 char* accessStr = createAccessFlagStr(pClassDef.access_flags_, kAccessForClass);
1466 const char* superclassDescriptor;
Andreas Gampea5b09a62016-11-17 15:21:22 -08001467 if (!pClassDef.superclass_idx_.IsValid()) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001468 superclassDescriptor = nullptr;
1469 } else {
1470 superclassDescriptor = pDexFile->StringByTypeIdx(pClassDef.superclass_idx_);
1471 }
1472 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1473 fprintf(gOutFile, "Class #%d -\n", idx);
1474 fprintf(gOutFile, " Class descriptor : '%s'\n", classDescriptor);
1475 fprintf(gOutFile, " Access flags : 0x%04x (%s)\n", pClassDef.access_flags_, accessStr);
1476 if (superclassDescriptor != nullptr) {
1477 fprintf(gOutFile, " Superclass : '%s'\n", superclassDescriptor);
1478 }
1479 fprintf(gOutFile, " Interfaces -\n");
1480 } else {
Aart Bikc05e2f22016-07-12 15:53:13 -07001481 std::unique_ptr<char[]> dot(descriptorClassToDot(classDescriptor));
1482 fprintf(gOutFile, "<class name=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001483 if (superclassDescriptor != nullptr) {
Aart Bikc05e2f22016-07-12 15:53:13 -07001484 dot = descriptorToDot(superclassDescriptor);
1485 fprintf(gOutFile, " extends=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001486 }
Alex Light1f12e282015-12-10 16:49:47 -08001487 fprintf(gOutFile, " interface=%s\n",
1488 quotedBool((pClassDef.access_flags_ & kAccInterface) != 0));
Aart Bik69ae54a2015-07-01 14:52:26 -07001489 fprintf(gOutFile, " abstract=%s\n", quotedBool((pClassDef.access_flags_ & kAccAbstract) != 0));
1490 fprintf(gOutFile, " static=%s\n", quotedBool((pClassDef.access_flags_ & kAccStatic) != 0));
1491 fprintf(gOutFile, " final=%s\n", quotedBool((pClassDef.access_flags_ & kAccFinal) != 0));
1492 // The "deprecated=" not knowable w/o parsing annotations.
1493 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(pClassDef.access_flags_));
1494 fprintf(gOutFile, ">\n");
1495 }
1496
1497 // Interfaces.
1498 const DexFile::TypeList* pInterfaces = pDexFile->GetInterfacesList(pClassDef);
1499 if (pInterfaces != nullptr) {
1500 for (u4 i = 0; i < pInterfaces->Size(); i++) {
1501 dumpInterface(pDexFile, pInterfaces->GetTypeItem(i), i);
1502 } // for
1503 }
1504
1505 // Fields and methods.
1506 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
1507 if (pEncodedData == nullptr) {
1508 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1509 fprintf(gOutFile, " Static fields -\n");
1510 fprintf(gOutFile, " Instance fields -\n");
1511 fprintf(gOutFile, " Direct methods -\n");
1512 fprintf(gOutFile, " Virtual methods -\n");
1513 }
1514 } else {
1515 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
Aart Bikdce50862016-06-10 16:04:03 -07001516
1517 // Prepare data for static fields.
1518 const u1* sData = pDexFile->GetEncodedStaticFieldValuesArray(pClassDef);
1519 const u4 sSize = sData != nullptr ? DecodeUnsignedLeb128(&sData) : 0;
1520
1521 // Static fields.
Aart Bik69ae54a2015-07-01 14:52:26 -07001522 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1523 fprintf(gOutFile, " Static fields -\n");
1524 }
Aart Bikdce50862016-06-10 16:04:03 -07001525 for (u4 i = 0; pClassData.HasNextStaticField(); i++, pClassData.Next()) {
1526 dumpSField(pDexFile,
1527 pClassData.GetMemberIndex(),
1528 pClassData.GetRawMemberAccessFlags(),
1529 i,
1530 i < sSize ? &sData : nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001531 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001532
1533 // Instance fields.
Aart Bik69ae54a2015-07-01 14:52:26 -07001534 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1535 fprintf(gOutFile, " Instance fields -\n");
1536 }
Aart Bikdce50862016-06-10 16:04:03 -07001537 for (u4 i = 0; pClassData.HasNextInstanceField(); i++, pClassData.Next()) {
1538 dumpIField(pDexFile,
1539 pClassData.GetMemberIndex(),
1540 pClassData.GetRawMemberAccessFlags(),
1541 i);
Aart Bik69ae54a2015-07-01 14:52:26 -07001542 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001543
1544 // Direct methods.
Aart Bik69ae54a2015-07-01 14:52:26 -07001545 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1546 fprintf(gOutFile, " Direct methods -\n");
1547 }
1548 for (int i = 0; pClassData.HasNextDirectMethod(); i++, pClassData.Next()) {
1549 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1550 pClassData.GetRawMemberAccessFlags(),
1551 pClassData.GetMethodCodeItem(),
1552 pClassData.GetMethodCodeItemOffset(), i);
1553 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001554
1555 // Virtual methods.
Aart Bik69ae54a2015-07-01 14:52:26 -07001556 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1557 fprintf(gOutFile, " Virtual methods -\n");
1558 }
1559 for (int i = 0; pClassData.HasNextVirtualMethod(); i++, pClassData.Next()) {
1560 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1561 pClassData.GetRawMemberAccessFlags(),
1562 pClassData.GetMethodCodeItem(),
1563 pClassData.GetMethodCodeItemOffset(), i);
1564 } // for
1565 }
1566
1567 // End of class.
1568 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1569 const char* fileName;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001570 if (pClassDef.source_file_idx_.IsValid()) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001571 fileName = pDexFile->StringDataByIdx(pClassDef.source_file_idx_);
1572 } else {
1573 fileName = "unknown";
1574 }
1575 fprintf(gOutFile, " source_file_idx : %d (%s)\n\n",
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001576 pClassDef.source_file_idx_.index_, fileName);
Aart Bik69ae54a2015-07-01 14:52:26 -07001577 } else if (gOptions.outputFormat == OUTPUT_XML) {
1578 fprintf(gOutFile, "</class>\n");
1579 }
1580
1581 free(accessStr);
1582}
1583
1584/*
1585 * Dumps the requested sections of the file.
1586 */
Aart Bik7b45a8a2016-10-24 16:07:59 -07001587static void processDexFile(const char* fileName,
1588 const DexFile* pDexFile, size_t i, size_t n) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001589 if (gOptions.verbose) {
Aart Bik7b45a8a2016-10-24 16:07:59 -07001590 fputs("Opened '", gOutFile);
1591 fputs(fileName, gOutFile);
1592 if (n > 1) {
1593 fprintf(gOutFile, ":%s", DexFile::GetMultiDexClassesDexName(i).c_str());
1594 }
1595 fprintf(gOutFile, "', DEX version '%.3s'\n", pDexFile->GetHeader().magic_ + 4);
Aart Bik69ae54a2015-07-01 14:52:26 -07001596 }
1597
1598 // Headers.
1599 if (gOptions.showFileHeaders) {
1600 dumpFileHeader(pDexFile);
1601 }
1602
1603 // Open XML context.
1604 if (gOptions.outputFormat == OUTPUT_XML) {
1605 fprintf(gOutFile, "<api>\n");
1606 }
1607
1608 // Iterate over all classes.
1609 char* package = nullptr;
1610 const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
1611 for (u4 i = 0; i < classDefsSize; i++) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001612 dumpClass(pDexFile, i, &package);
1613 } // for
1614
1615 // Free the last package allocated.
1616 if (package != nullptr) {
1617 fprintf(gOutFile, "</package>\n");
1618 free(package);
1619 }
1620
1621 // Close XML context.
1622 if (gOptions.outputFormat == OUTPUT_XML) {
1623 fprintf(gOutFile, "</api>\n");
1624 }
1625}
1626
1627/*
1628 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
1629 */
1630int processFile(const char* fileName) {
1631 if (gOptions.verbose) {
1632 fprintf(gOutFile, "Processing '%s'...\n", fileName);
1633 }
1634
1635 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
Aart Bikdce50862016-06-10 16:04:03 -07001636 // all of which are Zip archives with "classes.dex" inside.
Aart Bik37d6a3b2016-06-21 18:30:10 -07001637 const bool kVerifyChecksum = !gOptions.ignoreBadChecksum;
Aart Bik69ae54a2015-07-01 14:52:26 -07001638 std::string error_msg;
1639 std::vector<std::unique_ptr<const DexFile>> dex_files;
Aart Bik37d6a3b2016-06-21 18:30:10 -07001640 if (!DexFile::Open(fileName, fileName, kVerifyChecksum, &error_msg, &dex_files)) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001641 // Display returned error message to user. Note that this error behavior
1642 // differs from the error messages shown by the original Dalvik dexdump.
1643 fputs(error_msg.c_str(), stderr);
1644 fputc('\n', stderr);
1645 return -1;
1646 }
1647
Aart Bik4e149602015-07-09 11:45:28 -07001648 // Success. Either report checksum verification or process
1649 // all dex files found in given file.
Aart Bik69ae54a2015-07-01 14:52:26 -07001650 if (gOptions.checksumOnly) {
1651 fprintf(gOutFile, "Checksum verified\n");
1652 } else {
Aart Bik7b45a8a2016-10-24 16:07:59 -07001653 for (size_t i = 0, n = dex_files.size(); i < n; i++) {
1654 processDexFile(fileName, dex_files[i].get(), i, n);
Aart Bik4e149602015-07-09 11:45:28 -07001655 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001656 }
1657 return 0;
1658}
1659
1660} // namespace art