blob: 48b773e90b9ff85b3822c77c090443e394c208ad [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
45#include "dex_file-inl.h"
46#include "dex_instruction-inl.h"
Andreas Gampe5073fed2015-08-10 11:40:25 -070047#include "utils.h"
Aart Bik69ae54a2015-07-01 14:52:26 -070048
49namespace art {
50
51/*
52 * Options parsed in main driver.
53 */
54struct Options gOptions;
55
56/*
Aart Bik4e149602015-07-09 11:45:28 -070057 * Output file. Defaults to stdout.
Aart Bik69ae54a2015-07-01 14:52:26 -070058 */
59FILE* gOutFile = stdout;
60
61/*
62 * Data types that match the definitions in the VM specification.
63 */
64typedef uint8_t u1;
65typedef uint16_t u2;
66typedef uint32_t u4;
67typedef uint64_t u8;
Aart Bikdce50862016-06-10 16:04:03 -070068typedef int8_t s1;
69typedef int16_t s2;
Aart Bik69ae54a2015-07-01 14:52:26 -070070typedef int32_t s4;
71typedef int64_t s8;
72
73/*
74 * Basic information about a field or a method.
75 */
76struct FieldMethodInfo {
77 const char* classDescriptor;
78 const char* name;
79 const char* signature;
80};
81
82/*
83 * Flags for use with createAccessFlagStr().
84 */
85enum AccessFor {
86 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
87};
88const int kNumFlags = 18;
89
90/*
91 * Gets 2 little-endian bytes.
92 */
93static inline u2 get2LE(unsigned char const* pSrc) {
94 return pSrc[0] | (pSrc[1] << 8);
95}
96
97/*
98 * Converts a single-character primitive type into human-readable form.
99 */
100static const char* primitiveTypeLabel(char typeChar) {
101 switch (typeChar) {
102 case 'B': return "byte";
103 case 'C': return "char";
104 case 'D': return "double";
105 case 'F': return "float";
106 case 'I': return "int";
107 case 'J': return "long";
108 case 'S': return "short";
109 case 'V': return "void";
110 case 'Z': return "boolean";
111 default: return "UNKNOWN";
112 } // switch
113}
114
115/*
116 * Converts a type descriptor to human-readable "dotted" form. For
117 * example, "Ljava/lang/String;" becomes "java.lang.String", and
118 * "[I" becomes "int[]". Also converts '$' to '.', which means this
119 * form can't be converted back to a descriptor.
120 */
121static char* descriptorToDot(const char* str) {
122 int targetLen = strlen(str);
123 int offset = 0;
124
125 // Strip leading [s; will be added to end.
126 while (targetLen > 1 && str[offset] == '[') {
127 offset++;
128 targetLen--;
129 } // while
130
131 const int arrayDepth = offset;
132
133 if (targetLen == 1) {
134 // Primitive type.
135 str = primitiveTypeLabel(str[offset]);
136 offset = 0;
137 targetLen = strlen(str);
138 } else {
139 // Account for leading 'L' and trailing ';'.
140 if (targetLen >= 2 && str[offset] == 'L' &&
141 str[offset + targetLen - 1] == ';') {
142 targetLen -= 2;
143 offset++;
144 }
145 }
146
147 // Copy class name over.
148 char* newStr = reinterpret_cast<char*>(
149 malloc(targetLen + arrayDepth * 2 + 1));
150 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
168 * "dotted" form.
169 *
170 * Returns a newly-allocated string.
171 */
172static char* descriptorClassToDot(const char* str) {
173 // Reduce to just the class name, trimming trailing ';'.
174 const char* lastSlash = strrchr(str, '/');
175 if (lastSlash == nullptr) {
176 lastSlash = str + 1; // start past 'L'
177 } else {
178 lastSlash++; // start past '/'
179 }
180
181 char* newStr = strdup(lastSlash);
182 newStr[strlen(lastSlash) - 1] = '\0';
183 for (char* cp = newStr; *cp != '\0'; cp++) {
184 if (*cp == '$') {
185 *cp = '.';
186 }
187 } // for
188 return newStr;
189}
190
191/*
Aart Bikdce50862016-06-10 16:04:03 -0700192 * Returns string representing the boolean value.
193 */
194static const char* strBool(bool val) {
195 return val ? "true" : "false";
196}
197
198/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700199 * Returns a quoted string representing the boolean value.
200 */
201static const char* quotedBool(bool val) {
202 return val ? "\"true\"" : "\"false\"";
203}
204
205/*
206 * Returns a quoted string representing the access flags.
207 */
208static const char* quotedVisibility(u4 accessFlags) {
209 if (accessFlags & kAccPublic) {
210 return "\"public\"";
211 } else if (accessFlags & kAccProtected) {
212 return "\"protected\"";
213 } else if (accessFlags & kAccPrivate) {
214 return "\"private\"";
215 } else {
216 return "\"package\"";
217 }
218}
219
220/*
221 * Counts the number of '1' bits in a word.
222 */
223static int countOnes(u4 val) {
224 val = val - ((val >> 1) & 0x55555555);
225 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
226 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
227}
228
229/*
230 * Creates a new string with human-readable access flags.
231 *
232 * In the base language the access_flags fields are type u2; in Dalvik
233 * they're u4.
234 */
235static char* createAccessFlagStr(u4 flags, AccessFor forWhat) {
236 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
237 {
238 "PUBLIC", /* 0x00001 */
239 "PRIVATE", /* 0x00002 */
240 "PROTECTED", /* 0x00004 */
241 "STATIC", /* 0x00008 */
242 "FINAL", /* 0x00010 */
243 "?", /* 0x00020 */
244 "?", /* 0x00040 */
245 "?", /* 0x00080 */
246 "?", /* 0x00100 */
247 "INTERFACE", /* 0x00200 */
248 "ABSTRACT", /* 0x00400 */
249 "?", /* 0x00800 */
250 "SYNTHETIC", /* 0x01000 */
251 "ANNOTATION", /* 0x02000 */
252 "ENUM", /* 0x04000 */
253 "?", /* 0x08000 */
254 "VERIFIED", /* 0x10000 */
255 "OPTIMIZED", /* 0x20000 */
256 }, {
257 "PUBLIC", /* 0x00001 */
258 "PRIVATE", /* 0x00002 */
259 "PROTECTED", /* 0x00004 */
260 "STATIC", /* 0x00008 */
261 "FINAL", /* 0x00010 */
262 "SYNCHRONIZED", /* 0x00020 */
263 "BRIDGE", /* 0x00040 */
264 "VARARGS", /* 0x00080 */
265 "NATIVE", /* 0x00100 */
266 "?", /* 0x00200 */
267 "ABSTRACT", /* 0x00400 */
268 "STRICT", /* 0x00800 */
269 "SYNTHETIC", /* 0x01000 */
270 "?", /* 0x02000 */
271 "?", /* 0x04000 */
272 "MIRANDA", /* 0x08000 */
273 "CONSTRUCTOR", /* 0x10000 */
274 "DECLARED_SYNCHRONIZED", /* 0x20000 */
275 }, {
276 "PUBLIC", /* 0x00001 */
277 "PRIVATE", /* 0x00002 */
278 "PROTECTED", /* 0x00004 */
279 "STATIC", /* 0x00008 */
280 "FINAL", /* 0x00010 */
281 "?", /* 0x00020 */
282 "VOLATILE", /* 0x00040 */
283 "TRANSIENT", /* 0x00080 */
284 "?", /* 0x00100 */
285 "?", /* 0x00200 */
286 "?", /* 0x00400 */
287 "?", /* 0x00800 */
288 "SYNTHETIC", /* 0x01000 */
289 "?", /* 0x02000 */
290 "ENUM", /* 0x04000 */
291 "?", /* 0x08000 */
292 "?", /* 0x10000 */
293 "?", /* 0x20000 */
294 },
295 };
296
297 // Allocate enough storage to hold the expected number of strings,
298 // plus a space between each. We over-allocate, using the longest
299 // string above as the base metric.
300 const int kLongest = 21; // The strlen of longest string above.
301 const int count = countOnes(flags);
302 char* str;
303 char* cp;
304 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
305
306 for (int i = 0; i < kNumFlags; i++) {
307 if (flags & 0x01) {
308 const char* accessStr = kAccessStrings[forWhat][i];
309 const int len = strlen(accessStr);
310 if (cp != str) {
311 *cp++ = ' ';
312 }
313 memcpy(cp, accessStr, len);
314 cp += len;
315 }
316 flags >>= 1;
317 } // for
318
319 *cp = '\0';
320 return str;
321}
322
323/*
324 * Copies character data from "data" to "out", converting non-ASCII values
325 * to fprintf format chars or an ASCII filler ('.' or '?').
326 *
327 * The output buffer must be able to hold (2*len)+1 bytes. The result is
328 * NULL-terminated.
329 */
330static void asciify(char* out, const unsigned char* data, size_t len) {
331 while (len--) {
332 if (*data < 0x20) {
333 // Could do more here, but we don't need them yet.
334 switch (*data) {
335 case '\0':
336 *out++ = '\\';
337 *out++ = '0';
338 break;
339 case '\n':
340 *out++ = '\\';
341 *out++ = 'n';
342 break;
343 default:
344 *out++ = '.';
345 break;
346 } // switch
347 } else if (*data >= 0x80) {
348 *out++ = '?';
349 } else {
350 *out++ = *data;
351 }
352 data++;
353 } // while
354 *out = '\0';
355}
356
357/*
Aart Bikdce50862016-06-10 16:04:03 -0700358 * Dumps a string value with some escape characters.
359 */
360static void dumpEscapedString(const char* p) {
361 fputs("\"", gOutFile);
362 for (; *p; p++) {
363 switch (*p) {
364 case '\\':
365 fputs("\\\\", gOutFile);
366 break;
367 case '\"':
368 fputs("\\\"", gOutFile);
369 break;
370 case '\t':
371 fputs("\\t", gOutFile);
372 break;
373 case '\n':
374 fputs("\\n", gOutFile);
375 break;
376 case '\r':
377 fputs("\\r", gOutFile);
378 break;
379 default:
380 putc(*p, gOutFile);
381 } // switch
382 } // for
383 fputs("\"", gOutFile);
384}
385
386/*
387 * Dumps a string as an XML attribute value.
388 */
389static void dumpXmlAttribute(const char* p) {
390 for (; *p; p++) {
391 switch (*p) {
392 case '&':
393 fputs("&amp;", gOutFile);
394 break;
395 case '<':
396 fputs("&lt;", gOutFile);
397 break;
398 case '>':
399 fputs("&gt;", gOutFile);
400 break;
401 case '"':
402 fputs("&quot;", gOutFile);
403 break;
404 case '\t':
405 fputs("&#x9;", gOutFile);
406 break;
407 case '\n':
408 fputs("&#xA;", gOutFile);
409 break;
410 case '\r':
411 fputs("&#xD;", gOutFile);
412 break;
413 default:
414 putc(*p, gOutFile);
415 } // switch
416 } // for
417}
418
419/*
420 * Reads variable width value, possibly sign extended at the last defined byte.
421 */
422static u8 readVarWidth(const u1** data, u1 arg, bool sign_extend) {
423 u8 value = 0;
424 for (u4 i = 0; i <= arg; i++) {
425 value |= static_cast<u8>(*(*data)++) << (i * 8);
426 }
427 if (sign_extend) {
428 int shift = (7 - arg) * 8;
429 return (static_cast<s8>(value) << shift) >> shift;
430 }
431 return value;
432}
433
434/*
435 * Dumps encoded value.
436 */
437static void dumpEncodedValue(const DexFile* pDexFile, const u1** data); // forward
438static void dumpEncodedValue(const DexFile* pDexFile, const u1** data, u1 type, u1 arg) {
439 switch (type) {
440 case DexFile::kDexAnnotationByte:
441 fprintf(gOutFile, "%" PRId8, static_cast<s1>(readVarWidth(data, arg, false)));
442 break;
443 case DexFile::kDexAnnotationShort:
444 fprintf(gOutFile, "%" PRId16, static_cast<s2>(readVarWidth(data, arg, true)));
445 break;
446 case DexFile::kDexAnnotationChar:
447 fprintf(gOutFile, "%" PRIu16, static_cast<u2>(readVarWidth(data, arg, false)));
448 break;
449 case DexFile::kDexAnnotationInt:
450 fprintf(gOutFile, "%" PRId32, static_cast<s4>(readVarWidth(data, arg, true)));
451 break;
452 case DexFile::kDexAnnotationLong:
453 fprintf(gOutFile, "%" PRId64, static_cast<s8>(readVarWidth(data, arg, true)));
454 break;
455 case DexFile::kDexAnnotationFloat: {
456 // Fill on right.
457 union {
458 float f;
459 u4 data;
460 } conv;
461 conv.data = static_cast<u4>(readVarWidth(data, arg, false)) << (3 - arg) * 8;
462 fprintf(gOutFile, "%g", conv.f);
463 break;
464 }
465 case DexFile::kDexAnnotationDouble: {
466 // Fill on right.
467 union {
468 double d;
469 u8 data;
470 } conv;
471 conv.data = readVarWidth(data, arg, false) << (7 - arg) * 8;
472 fprintf(gOutFile, "%g", conv.d);
473 break;
474 }
475 case DexFile::kDexAnnotationString: {
476 const u4 idx = static_cast<u4>(readVarWidth(data, arg, false));
477 if (gOptions.outputFormat == OUTPUT_PLAIN) {
478 dumpEscapedString(pDexFile->StringDataByIdx(idx));
479 } else {
480 dumpXmlAttribute(pDexFile->StringDataByIdx(idx));
481 }
482 break;
483 }
484 case DexFile::kDexAnnotationType: {
485 const u4 str_idx = static_cast<u4>(readVarWidth(data, arg, false));
486 fputs(pDexFile->StringByTypeIdx(str_idx), gOutFile);
487 break;
488 }
489 case DexFile::kDexAnnotationField:
490 case DexFile::kDexAnnotationEnum: {
491 const u4 field_idx = static_cast<u4>(readVarWidth(data, arg, false));
492 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
493 fputs(pDexFile->StringDataByIdx(pFieldId.name_idx_), gOutFile);
494 break;
495 }
496 case DexFile::kDexAnnotationMethod: {
497 const u4 method_idx = static_cast<u4>(readVarWidth(data, arg, false));
498 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
499 fputs(pDexFile->StringDataByIdx(pMethodId.name_idx_), gOutFile);
500 break;
501 }
502 case DexFile::kDexAnnotationArray: {
503 fputc('{', gOutFile);
504 // Decode and display all elements.
505 const u4 size = DecodeUnsignedLeb128(data);
506 for (u4 i = 0; i < size; i++) {
507 fputc(' ', gOutFile);
508 dumpEncodedValue(pDexFile, data);
509 }
510 fputs(" }", gOutFile);
511 break;
512 }
513 case DexFile::kDexAnnotationAnnotation: {
514 const u4 type_idx = DecodeUnsignedLeb128(data);
515 fputs(pDexFile->StringByTypeIdx(type_idx), gOutFile);
516 // Decode and display all name=value pairs.
517 const u4 size = DecodeUnsignedLeb128(data);
518 for (u4 i = 0; i < size; i++) {
519 const u4 name_idx = DecodeUnsignedLeb128(data);
520 fputc(' ', gOutFile);
521 fputs(pDexFile->StringDataByIdx(name_idx), gOutFile);
522 fputc('=', gOutFile);
523 dumpEncodedValue(pDexFile, data);
524 }
525 break;
526 }
527 case DexFile::kDexAnnotationNull:
528 fputs("null", gOutFile);
529 break;
530 case DexFile::kDexAnnotationBoolean:
531 fputs(strBool(arg), gOutFile);
532 break;
533 default:
534 fputs("????", gOutFile);
535 break;
536 } // switch
537}
538
539/*
540 * Dumps encoded value with prefix.
541 */
542static void dumpEncodedValue(const DexFile* pDexFile, const u1** data) {
543 const u1 enc = *(*data)++;
544 dumpEncodedValue(pDexFile, data, enc & 0x1f, enc >> 5);
545}
546
547/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700548 * Dumps the file header.
Aart Bik69ae54a2015-07-01 14:52:26 -0700549 */
550static void dumpFileHeader(const DexFile* pDexFile) {
551 const DexFile::Header& pHeader = pDexFile->GetHeader();
552 char sanitized[sizeof(pHeader.magic_) * 2 + 1];
553 fprintf(gOutFile, "DEX file header:\n");
554 asciify(sanitized, pHeader.magic_, sizeof(pHeader.magic_));
555 fprintf(gOutFile, "magic : '%s'\n", sanitized);
556 fprintf(gOutFile, "checksum : %08x\n", pHeader.checksum_);
557 fprintf(gOutFile, "signature : %02x%02x...%02x%02x\n",
558 pHeader.signature_[0], pHeader.signature_[1],
559 pHeader.signature_[DexFile::kSha1DigestSize - 2],
560 pHeader.signature_[DexFile::kSha1DigestSize - 1]);
561 fprintf(gOutFile, "file_size : %d\n", pHeader.file_size_);
562 fprintf(gOutFile, "header_size : %d\n", pHeader.header_size_);
563 fprintf(gOutFile, "link_size : %d\n", pHeader.link_size_);
564 fprintf(gOutFile, "link_off : %d (0x%06x)\n",
565 pHeader.link_off_, pHeader.link_off_);
566 fprintf(gOutFile, "string_ids_size : %d\n", pHeader.string_ids_size_);
567 fprintf(gOutFile, "string_ids_off : %d (0x%06x)\n",
568 pHeader.string_ids_off_, pHeader.string_ids_off_);
569 fprintf(gOutFile, "type_ids_size : %d\n", pHeader.type_ids_size_);
570 fprintf(gOutFile, "type_ids_off : %d (0x%06x)\n",
571 pHeader.type_ids_off_, pHeader.type_ids_off_);
Aart Bikdce50862016-06-10 16:04:03 -0700572 fprintf(gOutFile, "proto_ids_size : %d\n", pHeader.proto_ids_size_);
573 fprintf(gOutFile, "proto_ids_off : %d (0x%06x)\n",
Aart Bik69ae54a2015-07-01 14:52:26 -0700574 pHeader.proto_ids_off_, pHeader.proto_ids_off_);
575 fprintf(gOutFile, "field_ids_size : %d\n", pHeader.field_ids_size_);
576 fprintf(gOutFile, "field_ids_off : %d (0x%06x)\n",
577 pHeader.field_ids_off_, pHeader.field_ids_off_);
578 fprintf(gOutFile, "method_ids_size : %d\n", pHeader.method_ids_size_);
579 fprintf(gOutFile, "method_ids_off : %d (0x%06x)\n",
580 pHeader.method_ids_off_, pHeader.method_ids_off_);
581 fprintf(gOutFile, "class_defs_size : %d\n", pHeader.class_defs_size_);
582 fprintf(gOutFile, "class_defs_off : %d (0x%06x)\n",
583 pHeader.class_defs_off_, pHeader.class_defs_off_);
584 fprintf(gOutFile, "data_size : %d\n", pHeader.data_size_);
585 fprintf(gOutFile, "data_off : %d (0x%06x)\n\n",
586 pHeader.data_off_, pHeader.data_off_);
587}
588
589/*
590 * Dumps a class_def_item.
591 */
592static void dumpClassDef(const DexFile* pDexFile, int idx) {
593 // General class information.
594 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
595 fprintf(gOutFile, "Class #%d header:\n", idx);
596 fprintf(gOutFile, "class_idx : %d\n", pClassDef.class_idx_);
597 fprintf(gOutFile, "access_flags : %d (0x%04x)\n",
598 pClassDef.access_flags_, pClassDef.access_flags_);
599 fprintf(gOutFile, "superclass_idx : %d\n", pClassDef.superclass_idx_);
600 fprintf(gOutFile, "interfaces_off : %d (0x%06x)\n",
601 pClassDef.interfaces_off_, pClassDef.interfaces_off_);
602 fprintf(gOutFile, "source_file_idx : %d\n", pClassDef.source_file_idx_);
603 fprintf(gOutFile, "annotations_off : %d (0x%06x)\n",
604 pClassDef.annotations_off_, pClassDef.annotations_off_);
605 fprintf(gOutFile, "class_data_off : %d (0x%06x)\n",
606 pClassDef.class_data_off_, pClassDef.class_data_off_);
607
608 // Fields and methods.
609 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
610 if (pEncodedData != nullptr) {
611 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
612 fprintf(gOutFile, "static_fields_size : %d\n", pClassData.NumStaticFields());
613 fprintf(gOutFile, "instance_fields_size: %d\n", pClassData.NumInstanceFields());
614 fprintf(gOutFile, "direct_methods_size : %d\n", pClassData.NumDirectMethods());
615 fprintf(gOutFile, "virtual_methods_size: %d\n", pClassData.NumVirtualMethods());
616 } else {
617 fprintf(gOutFile, "static_fields_size : 0\n");
618 fprintf(gOutFile, "instance_fields_size: 0\n");
619 fprintf(gOutFile, "direct_methods_size : 0\n");
620 fprintf(gOutFile, "virtual_methods_size: 0\n");
621 }
622 fprintf(gOutFile, "\n");
623}
624
Aart Bikdce50862016-06-10 16:04:03 -0700625/**
626 * Dumps an annotation set item.
627 */
628static void dumpAnnotationSetItem(const DexFile* pDexFile, const DexFile::AnnotationSetItem* set_item) {
629 if (set_item == nullptr || set_item->size_ == 0) {
630 fputs(" empty-annotation-set\n", gOutFile);
631 return;
632 }
633 for (u4 i = 0; i < set_item->size_; i++) {
634 const DexFile::AnnotationItem* annotation = pDexFile->GetAnnotationItem(set_item, i);
635 if (annotation == nullptr) {
636 continue;
637 }
638 fputs(" ", gOutFile);
639 switch (annotation->visibility_) {
640 case DexFile::kDexVisibilityBuild: fputs("VISIBILITY_BUILD ", gOutFile); break;
641 case DexFile::kDexVisibilityRuntime: fputs("VISIBILITY_RUNTIME ", gOutFile); break;
642 case DexFile::kDexVisibilitySystem: fputs("VISIBILITY_SYSTEM ", gOutFile); break;
643 default: fputs("VISIBILITY_UNKNOWN ", gOutFile); break;
644 } // switch
645 // Decode raw bytes in annotation.
646 const u1* rData = annotation->annotation_;
647 dumpEncodedValue(pDexFile, &rData, DexFile::kDexAnnotationAnnotation, 0);
648 fputc('\n', gOutFile);
649 }
650}
651
652/*
653 * Dumps class annotations.
654 */
655static void dumpClassAnnotations(const DexFile* pDexFile, int idx) {
656 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
657 const DexFile::AnnotationsDirectoryItem* dir = pDexFile->GetAnnotationsDirectory(pClassDef);
658 if (dir == nullptr) {
659 return; // none
660 }
661
662 fprintf(gOutFile, "Class #%d annotations:\n", idx);
663
664 const DexFile::AnnotationSetItem* class_set_item = pDexFile->GetClassAnnotationSet(dir);
665 const DexFile::FieldAnnotationsItem* fields = pDexFile->GetFieldAnnotations(dir);
666 const DexFile::MethodAnnotationsItem* methods = pDexFile->GetMethodAnnotations(dir);
667 const DexFile::ParameterAnnotationsItem* pars = pDexFile->GetParameterAnnotations(dir);
668
669 // Annotations on the class itself.
670 if (class_set_item != nullptr) {
671 fprintf(gOutFile, "Annotations on class\n");
672 dumpAnnotationSetItem(pDexFile, class_set_item);
673 }
674
675 // Annotations on fields.
676 if (fields != nullptr) {
677 for (u4 i = 0; i < dir->fields_size_; i++) {
678 const u4 field_idx = fields[i].field_idx_;
679 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
680 const char* field_name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
681 fprintf(gOutFile, "Annotations on field #%u '%s'\n", field_idx, field_name);
682 dumpAnnotationSetItem(pDexFile, pDexFile->GetFieldAnnotationSetItem(fields[i]));
683 }
684 }
685
686 // Annotations on methods.
687 if (methods != nullptr) {
688 for (u4 i = 0; i < dir->methods_size_; i++) {
689 const u4 method_idx = methods[i].method_idx_;
690 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
691 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
692 fprintf(gOutFile, "Annotations on method #%u '%s'\n", method_idx, method_name);
693 dumpAnnotationSetItem(pDexFile, pDexFile->GetMethodAnnotationSetItem(methods[i]));
694 }
695 }
696
697 // Annotations on method parameters.
698 if (pars != nullptr) {
699 for (u4 i = 0; i < dir->parameters_size_; i++) {
700 const u4 method_idx = pars[i].method_idx_;
701 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
702 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
703 fprintf(gOutFile, "Annotations on method #%u '%s' parameters\n", method_idx, method_name);
704 const DexFile::AnnotationSetRefList*
705 list = pDexFile->GetParameterAnnotationSetRefList(&pars[i]);
706 if (list != nullptr) {
707 for (u4 j = 0; j < list->size_; j++) {
708 fprintf(gOutFile, "#%u\n", j);
709 dumpAnnotationSetItem(pDexFile, pDexFile->GetSetRefItemItem(&list->list_[j]));
710 }
711 }
712 }
713 }
714
715 fputc('\n', gOutFile);
716}
717
Aart Bik69ae54a2015-07-01 14:52:26 -0700718/*
719 * Dumps an interface that a class declares to implement.
720 */
721static void dumpInterface(const DexFile* pDexFile, const DexFile::TypeItem& pTypeItem, int i) {
722 const char* interfaceName = pDexFile->StringByTypeIdx(pTypeItem.type_idx_);
723 if (gOptions.outputFormat == OUTPUT_PLAIN) {
724 fprintf(gOutFile, " #%d : '%s'\n", i, interfaceName);
725 } else {
726 char* dotted = descriptorToDot(interfaceName);
727 fprintf(gOutFile, "<implements name=\"%s\">\n</implements>\n", dotted);
728 free(dotted);
729 }
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()) {
752 const u2 tidx = it.GetHandlerTypeIndex();
753 const char* descriptor =
754 (tidx == DexFile::kDexNoIndex16) ? "<any>" : pDexFile->StringByTypeIdx(tidx);
755 fprintf(gOutFile, " %s -> 0x%04x\n", descriptor, it.GetHandlerAddress());
756 } // for
757 } // for
758}
759
760/*
761 * Callback for dumping each positions table entry.
762 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000763static bool dumpPositionsCb(void* /*context*/, const DexFile::PositionInfo& entry) {
764 fprintf(gOutFile, " 0x%04x line=%d\n", entry.address_, entry.line_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700765 return false;
766}
767
768/*
769 * Callback for dumping locals table entry.
770 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000771static void dumpLocalsCb(void* /*context*/, const DexFile::LocalInfo& entry) {
772 const char* signature = entry.signature_ != nullptr ? entry.signature_ : "";
Aart Bik69ae54a2015-07-01 14:52:26 -0700773 fprintf(gOutFile, " 0x%04x - 0x%04x reg=%d %s %s %s\n",
David Srbeckyb06e28e2015-12-10 13:15:00 +0000774 entry.start_address_, entry.end_address_, entry.reg_,
775 entry.name_, entry.descriptor_, signature);
Aart Bik69ae54a2015-07-01 14:52:26 -0700776}
777
778/*
779 * Helper for dumpInstruction(), which builds the string
780 * representation for the index in the given instruction. This will
781 * first try to use the given buffer, but if the result won't fit,
782 * then this will allocate a new buffer to hold the result. A pointer
783 * to the buffer which holds the full result is always returned, and
784 * this can be compared with the one passed in, to see if the result
785 * needs to be free()d.
786 */
787static char* indexString(const DexFile* pDexFile,
788 const Instruction* pDecInsn, char* buf, size_t bufSize) {
789 // Determine index and width of the string.
790 u4 index = 0;
791 u4 width = 4;
792 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
793 // SOME NOT SUPPORTED:
794 // case Instruction::k20bc:
795 case Instruction::k21c:
796 case Instruction::k35c:
797 // case Instruction::k35ms:
798 case Instruction::k3rc:
799 // case Instruction::k3rms:
800 // case Instruction::k35mi:
801 // case Instruction::k3rmi:
802 index = pDecInsn->VRegB();
803 width = 4;
804 break;
805 case Instruction::k31c:
806 index = pDecInsn->VRegB();
807 width = 8;
808 break;
809 case Instruction::k22c:
810 // case Instruction::k22cs:
811 index = pDecInsn->VRegC();
812 width = 4;
813 break;
814 default:
815 break;
816 } // switch
817
818 // Determine index type.
819 size_t outSize = 0;
820 switch (Instruction::IndexTypeOf(pDecInsn->Opcode())) {
821 case Instruction::kIndexUnknown:
822 // This function should never get called for this type, but do
823 // something sensible here, just to help with debugging.
824 outSize = snprintf(buf, bufSize, "<unknown-index>");
825 break;
826 case Instruction::kIndexNone:
827 // This function should never get called for this type, but do
828 // something sensible here, just to help with debugging.
829 outSize = snprintf(buf, bufSize, "<no-index>");
830 break;
831 case Instruction::kIndexTypeRef:
832 if (index < pDexFile->GetHeader().type_ids_size_) {
833 const char* tp = pDexFile->StringByTypeIdx(index);
834 outSize = snprintf(buf, bufSize, "%s // type@%0*x", tp, width, index);
835 } else {
836 outSize = snprintf(buf, bufSize, "<type?> // type@%0*x", width, index);
837 }
838 break;
839 case Instruction::kIndexStringRef:
840 if (index < pDexFile->GetHeader().string_ids_size_) {
841 const char* st = pDexFile->StringDataByIdx(index);
842 outSize = snprintf(buf, bufSize, "\"%s\" // string@%0*x", st, width, index);
843 } else {
844 outSize = snprintf(buf, bufSize, "<string?> // string@%0*x", width, index);
845 }
846 break;
847 case Instruction::kIndexMethodRef:
848 if (index < pDexFile->GetHeader().method_ids_size_) {
849 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
850 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
851 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
852 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
853 outSize = snprintf(buf, bufSize, "%s.%s:%s // method@%0*x",
854 backDescriptor, name, signature.ToString().c_str(), width, index);
855 } else {
856 outSize = snprintf(buf, bufSize, "<method?> // method@%0*x", width, index);
857 }
858 break;
859 case Instruction::kIndexFieldRef:
860 if (index < pDexFile->GetHeader().field_ids_size_) {
861 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(index);
862 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
863 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
864 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
865 outSize = snprintf(buf, bufSize, "%s.%s:%s // field@%0*x",
866 backDescriptor, name, typeDescriptor, width, index);
867 } else {
868 outSize = snprintf(buf, bufSize, "<field?> // field@%0*x", width, index);
869 }
870 break;
871 case Instruction::kIndexVtableOffset:
872 outSize = snprintf(buf, bufSize, "[%0*x] // vtable #%0*x",
873 width, index, width, index);
874 break;
875 case Instruction::kIndexFieldOffset:
876 outSize = snprintf(buf, bufSize, "[obj+%0*x]", width, index);
877 break;
878 // SOME NOT SUPPORTED:
879 // case Instruction::kIndexVaries:
880 // case Instruction::kIndexInlineMethod:
881 default:
882 outSize = snprintf(buf, bufSize, "<?>");
883 break;
884 } // switch
885
886 // Determine success of string construction.
887 if (outSize >= bufSize) {
888 // The buffer wasn't big enough; allocate and retry. Note:
889 // snprintf() doesn't count the '\0' as part of its returned
890 // size, so we add explicit space for it here.
891 outSize++;
892 buf = reinterpret_cast<char*>(malloc(outSize));
893 if (buf == nullptr) {
894 return nullptr;
895 }
896 return indexString(pDexFile, pDecInsn, buf, outSize);
897 }
898 return buf;
899}
900
901/*
902 * Dumps a single instruction.
903 */
904static void dumpInstruction(const DexFile* pDexFile,
905 const DexFile::CodeItem* pCode,
906 u4 codeOffset, u4 insnIdx, u4 insnWidth,
907 const Instruction* pDecInsn) {
908 // Address of instruction (expressed as byte offset).
909 fprintf(gOutFile, "%06x:", codeOffset + 0x10 + insnIdx * 2);
910
911 // Dump (part of) raw bytes.
912 const u2* insns = pCode->insns_;
913 for (u4 i = 0; i < 8; i++) {
914 if (i < insnWidth) {
915 if (i == 7) {
916 fprintf(gOutFile, " ... ");
917 } else {
918 // Print 16-bit value in little-endian order.
919 const u1* bytePtr = (const u1*) &insns[insnIdx + i];
920 fprintf(gOutFile, " %02x%02x", bytePtr[0], bytePtr[1]);
921 }
922 } else {
923 fputs(" ", gOutFile);
924 }
925 } // for
926
927 // Dump pseudo-instruction or opcode.
928 if (pDecInsn->Opcode() == Instruction::NOP) {
929 const u2 instr = get2LE((const u1*) &insns[insnIdx]);
930 if (instr == Instruction::kPackedSwitchSignature) {
931 fprintf(gOutFile, "|%04x: packed-switch-data (%d units)", insnIdx, insnWidth);
932 } else if (instr == Instruction::kSparseSwitchSignature) {
933 fprintf(gOutFile, "|%04x: sparse-switch-data (%d units)", insnIdx, insnWidth);
934 } else if (instr == Instruction::kArrayDataSignature) {
935 fprintf(gOutFile, "|%04x: array-data (%d units)", insnIdx, insnWidth);
936 } else {
937 fprintf(gOutFile, "|%04x: nop // spacer", insnIdx);
938 }
939 } else {
940 fprintf(gOutFile, "|%04x: %s", insnIdx, pDecInsn->Name());
941 }
942
943 // Set up additional argument.
944 char indexBufChars[200];
945 char *indexBuf = indexBufChars;
946 if (Instruction::IndexTypeOf(pDecInsn->Opcode()) != Instruction::kIndexNone) {
947 indexBuf = indexString(pDexFile, pDecInsn,
948 indexBufChars, sizeof(indexBufChars));
949 }
950
951 // Dump the instruction.
952 //
953 // NOTE: pDecInsn->DumpString(pDexFile) differs too much from original.
954 //
955 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
956 case Instruction::k10x: // op
957 break;
958 case Instruction::k12x: // op vA, vB
959 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
960 break;
961 case Instruction::k11n: // op vA, #+B
962 fprintf(gOutFile, " v%d, #int %d // #%x",
963 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u1)pDecInsn->VRegB());
964 break;
965 case Instruction::k11x: // op vAA
966 fprintf(gOutFile, " v%d", pDecInsn->VRegA());
967 break;
968 case Instruction::k10t: // op +AA
Aart Bikdce50862016-06-10 16:04:03 -0700969 case Instruction::k20t: { // op +AAAA
970 const s4 targ = (s4) pDecInsn->VRegA();
971 fprintf(gOutFile, " %04x // %c%04x",
972 insnIdx + targ,
973 (targ < 0) ? '-' : '+',
974 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -0700975 break;
Aart Bikdce50862016-06-10 16:04:03 -0700976 }
Aart Bik69ae54a2015-07-01 14:52:26 -0700977 case Instruction::k22x: // op vAA, vBBBB
978 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
979 break;
Aart Bikdce50862016-06-10 16:04:03 -0700980 case Instruction::k21t: { // op vAA, +BBBB
981 const s4 targ = (s4) pDecInsn->VRegB();
982 fprintf(gOutFile, " v%d, %04x // %c%04x", pDecInsn->VRegA(),
983 insnIdx + targ,
984 (targ < 0) ? '-' : '+',
985 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -0700986 break;
Aart Bikdce50862016-06-10 16:04:03 -0700987 }
Aart Bik69ae54a2015-07-01 14:52:26 -0700988 case Instruction::k21s: // op vAA, #+BBBB
989 fprintf(gOutFile, " v%d, #int %d // #%x",
990 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u2)pDecInsn->VRegB());
991 break;
992 case Instruction::k21h: // op vAA, #+BBBB0000[00000000]
993 // The printed format varies a bit based on the actual opcode.
994 if (pDecInsn->Opcode() == Instruction::CONST_HIGH16) {
995 const s4 value = pDecInsn->VRegB() << 16;
996 fprintf(gOutFile, " v%d, #int %d // #%x",
997 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
998 } else {
999 const s8 value = ((s8) pDecInsn->VRegB()) << 48;
1000 fprintf(gOutFile, " v%d, #long %" PRId64 " // #%x",
1001 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
1002 }
1003 break;
1004 case Instruction::k21c: // op vAA, thing@BBBB
1005 case Instruction::k31c: // op vAA, thing@BBBBBBBB
1006 fprintf(gOutFile, " v%d, %s", pDecInsn->VRegA(), indexBuf);
1007 break;
1008 case Instruction::k23x: // op vAA, vBB, vCC
1009 fprintf(gOutFile, " v%d, v%d, v%d",
1010 pDecInsn->VRegA(), pDecInsn->VRegB(), pDecInsn->VRegC());
1011 break;
1012 case Instruction::k22b: // op vAA, vBB, #+CC
1013 fprintf(gOutFile, " v%d, v%d, #int %d // #%02x",
1014 pDecInsn->VRegA(), pDecInsn->VRegB(),
1015 (s4) pDecInsn->VRegC(), (u1) pDecInsn->VRegC());
1016 break;
Aart Bikdce50862016-06-10 16:04:03 -07001017 case Instruction::k22t: { // op vA, vB, +CCCC
1018 const s4 targ = (s4) pDecInsn->VRegC();
1019 fprintf(gOutFile, " v%d, v%d, %04x // %c%04x",
1020 pDecInsn->VRegA(), pDecInsn->VRegB(),
1021 insnIdx + targ,
1022 (targ < 0) ? '-' : '+',
1023 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001024 break;
Aart Bikdce50862016-06-10 16:04:03 -07001025 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001026 case Instruction::k22s: // op vA, vB, #+CCCC
1027 fprintf(gOutFile, " v%d, v%d, #int %d // #%04x",
1028 pDecInsn->VRegA(), pDecInsn->VRegB(),
1029 (s4) pDecInsn->VRegC(), (u2) pDecInsn->VRegC());
1030 break;
1031 case Instruction::k22c: // op vA, vB, thing@CCCC
1032 // NOT SUPPORTED:
1033 // case Instruction::k22cs: // [opt] op vA, vB, field offset CCCC
1034 fprintf(gOutFile, " v%d, v%d, %s",
1035 pDecInsn->VRegA(), pDecInsn->VRegB(), indexBuf);
1036 break;
1037 case Instruction::k30t:
1038 fprintf(gOutFile, " #%08x", pDecInsn->VRegA());
1039 break;
Aart Bikdce50862016-06-10 16:04:03 -07001040 case Instruction::k31i: { // op vAA, #+BBBBBBBB
1041 // This is often, but not always, a float.
1042 union {
1043 float f;
1044 u4 i;
1045 } conv;
1046 conv.i = pDecInsn->VRegB();
1047 fprintf(gOutFile, " v%d, #float %g // #%08x",
1048 pDecInsn->VRegA(), conv.f, pDecInsn->VRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001049 break;
Aart Bikdce50862016-06-10 16:04:03 -07001050 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001051 case Instruction::k31t: // op vAA, offset +BBBBBBBB
1052 fprintf(gOutFile, " v%d, %08x // +%08x",
1053 pDecInsn->VRegA(), insnIdx + pDecInsn->VRegB(), pDecInsn->VRegB());
1054 break;
1055 case Instruction::k32x: // op vAAAA, vBBBB
1056 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
1057 break;
Aart Bikdce50862016-06-10 16:04:03 -07001058 case Instruction::k35c: { // op {vC, vD, vE, vF, vG}, thing@BBBB
Aart Bik69ae54a2015-07-01 14:52:26 -07001059 // NOT SUPPORTED:
1060 // case Instruction::k35ms: // [opt] invoke-virtual+super
1061 // case Instruction::k35mi: // [opt] inline invoke
Aart Bikdce50862016-06-10 16:04:03 -07001062 u4 arg[Instruction::kMaxVarArgRegs];
1063 pDecInsn->GetVarArgs(arg);
1064 fputs(" {", gOutFile);
1065 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1066 if (i == 0) {
1067 fprintf(gOutFile, "v%d", arg[i]);
1068 } else {
1069 fprintf(gOutFile, ", v%d", arg[i]);
1070 }
1071 } // for
1072 fprintf(gOutFile, "}, %s", indexBuf);
Aart Bik69ae54a2015-07-01 14:52:26 -07001073 break;
Aart Bikdce50862016-06-10 16:04:03 -07001074 }
1075 case Instruction::k25x: { // op vC, {vD, vE, vF, vG} (B: count)
1076 u4 arg[Instruction::kMaxVarArgRegs25x];
1077 pDecInsn->GetAllArgs25x(arg);
1078 fprintf(gOutFile, " v%d, {", arg[0]);
1079 for (int i = 0, n = pDecInsn->VRegB(); i < n; i++) {
1080 if (i == 0) {
1081 fprintf(gOutFile, "v%d", arg[Instruction::kLambdaVirtualRegisterWidth + i]);
1082 } else {
1083 fprintf(gOutFile, ", v%d", arg[Instruction::kLambdaVirtualRegisterWidth + i]);
1084 }
1085 } // for
1086 fputc('}', gOutFile);
Aart Bika3bb7202015-10-26 17:24:09 -07001087 break;
Aart Bikdce50862016-06-10 16:04:03 -07001088 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001089 case Instruction::k3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB
1090 // NOT SUPPORTED:
1091 // case Instruction::k3rms: // [opt] invoke-virtual+super/range
1092 // case Instruction::k3rmi: // [opt] execute-inline/range
1093 {
1094 // This doesn't match the "dx" output when some of the args are
1095 // 64-bit values -- dx only shows the first register.
1096 fputs(" {", gOutFile);
1097 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1098 if (i == 0) {
1099 fprintf(gOutFile, "v%d", pDecInsn->VRegC() + i);
1100 } else {
1101 fprintf(gOutFile, ", v%d", pDecInsn->VRegC() + i);
1102 }
1103 } // for
1104 fprintf(gOutFile, "}, %s", indexBuf);
1105 }
1106 break;
Aart Bikdce50862016-06-10 16:04:03 -07001107 case Instruction::k51l: { // op vAA, #+BBBBBBBBBBBBBBBB
1108 // This is often, but not always, a double.
1109 union {
1110 double d;
1111 u8 j;
1112 } conv;
1113 conv.j = pDecInsn->WideVRegB();
1114 fprintf(gOutFile, " v%d, #double %g // #%016" PRIx64,
1115 pDecInsn->VRegA(), conv.d, pDecInsn->WideVRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001116 break;
Aart Bikdce50862016-06-10 16:04:03 -07001117 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001118 // NOT SUPPORTED:
1119 // case Instruction::k00x: // unknown op or breakpoint
1120 // break;
1121 default:
1122 fprintf(gOutFile, " ???");
1123 break;
1124 } // switch
1125
1126 fputc('\n', gOutFile);
1127
1128 if (indexBuf != indexBufChars) {
1129 free(indexBuf);
1130 }
1131}
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.
1144 char* tmp = descriptorToDot(backDescriptor);
1145 fprintf(gOutFile, "%06x: "
1146 "|[%06x] %s.%s:%s\n",
1147 codeOffset, codeOffset, tmp, name, signature.ToString().c_str());
1148 free(tmp);
1149
1150 // Iterate over all instructions.
1151 const u2* insns = pCode->insns_;
1152 for (u4 insnIdx = 0; insnIdx < pCode->insns_size_in_code_units_;) {
1153 const Instruction* instruction = Instruction::At(&insns[insnIdx]);
1154 const u4 insnWidth = instruction->SizeInCodeUnits();
1155 if (insnWidth == 0) {
1156 fprintf(stderr, "GLITCH: zero-width instruction at idx=0x%04x\n", insnIdx);
1157 break;
1158 }
1159 dumpInstruction(pDexFile, pCode, codeOffset, insnIdx, insnWidth, instruction);
1160 insnIdx += insnWidth;
1161 } // for
1162}
1163
1164/*
1165 * Dumps code of a method.
1166 */
1167static void dumpCode(const DexFile* pDexFile, u4 idx, u4 flags,
1168 const DexFile::CodeItem* pCode, u4 codeOffset) {
1169 fprintf(gOutFile, " registers : %d\n", pCode->registers_size_);
1170 fprintf(gOutFile, " ins : %d\n", pCode->ins_size_);
1171 fprintf(gOutFile, " outs : %d\n", pCode->outs_size_);
1172 fprintf(gOutFile, " insns size : %d 16-bit code units\n",
1173 pCode->insns_size_in_code_units_);
1174
1175 // Bytecode disassembly, if requested.
1176 if (gOptions.disassemble) {
1177 dumpBytecodes(pDexFile, idx, pCode, codeOffset);
1178 }
1179
1180 // Try-catch blocks.
1181 dumpCatches(pDexFile, pCode);
1182
1183 // Positions and locals table in the debug info.
1184 bool is_static = (flags & kAccStatic) != 0;
1185 fprintf(gOutFile, " positions : \n");
David Srbeckyb06e28e2015-12-10 13:15:00 +00001186 pDexFile->DecodeDebugPositionInfo(pCode, dumpPositionsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001187 fprintf(gOutFile, " locals : \n");
David Srbeckyb06e28e2015-12-10 13:15:00 +00001188 pDexFile->DecodeDebugLocalInfo(pCode, is_static, idx, dumpLocalsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001189}
1190
1191/*
1192 * Dumps a method.
1193 */
1194static void dumpMethod(const DexFile* pDexFile, u4 idx, u4 flags,
1195 const DexFile::CodeItem* pCode, u4 codeOffset, int i) {
1196 // Bail for anything private if export only requested.
1197 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1198 return;
1199 }
1200
1201 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
1202 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
1203 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
1204 char* typeDescriptor = strdup(signature.ToString().c_str());
1205 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
1206 char* accessStr = createAccessFlagStr(flags, kAccessForMethod);
1207
1208 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1209 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1210 fprintf(gOutFile, " name : '%s'\n", name);
1211 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1212 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
1213 if (pCode == nullptr) {
1214 fprintf(gOutFile, " code : (none)\n");
1215 } else {
1216 fprintf(gOutFile, " code -\n");
1217 dumpCode(pDexFile, idx, flags, pCode, codeOffset);
1218 }
1219 if (gOptions.disassemble) {
1220 fputc('\n', gOutFile);
1221 }
1222 } else if (gOptions.outputFormat == OUTPUT_XML) {
1223 const bool constructor = (name[0] == '<');
1224
1225 // Method name and prototype.
1226 if (constructor) {
1227 char* tmp = descriptorClassToDot(backDescriptor);
1228 fprintf(gOutFile, "<constructor name=\"%s\"\n", tmp);
1229 free(tmp);
1230 tmp = descriptorToDot(backDescriptor);
1231 fprintf(gOutFile, " type=\"%s\"\n", tmp);
1232 free(tmp);
1233 } else {
1234 fprintf(gOutFile, "<method name=\"%s\"\n", name);
1235 const char* returnType = strrchr(typeDescriptor, ')');
1236 if (returnType == nullptr) {
1237 fprintf(stderr, "bad method type descriptor '%s'\n", typeDescriptor);
1238 goto bail;
1239 }
1240 char* tmp = descriptorToDot(returnType+1);
1241 fprintf(gOutFile, " return=\"%s\"\n", tmp);
1242 free(tmp);
1243 fprintf(gOutFile, " abstract=%s\n", quotedBool((flags & kAccAbstract) != 0));
1244 fprintf(gOutFile, " native=%s\n", quotedBool((flags & kAccNative) != 0));
1245 fprintf(gOutFile, " synchronized=%s\n", quotedBool(
1246 (flags & (kAccSynchronized | kAccDeclaredSynchronized)) != 0));
1247 }
1248
1249 // Additional method flags.
1250 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1251 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1252 // The "deprecated=" not knowable w/o parsing annotations.
1253 fprintf(gOutFile, " visibility=%s\n>\n", quotedVisibility(flags));
1254
1255 // Parameters.
1256 if (typeDescriptor[0] != '(') {
1257 fprintf(stderr, "ERROR: bad descriptor '%s'\n", typeDescriptor);
1258 goto bail;
1259 }
1260 char* tmpBuf = reinterpret_cast<char*>(malloc(strlen(typeDescriptor) + 1));
1261 const char* base = typeDescriptor + 1;
1262 int argNum = 0;
1263 while (*base != ')') {
1264 char* cp = tmpBuf;
1265 while (*base == '[') {
1266 *cp++ = *base++;
1267 }
1268 if (*base == 'L') {
1269 // Copy through ';'.
1270 do {
1271 *cp = *base++;
1272 } while (*cp++ != ';');
1273 } else {
1274 // Primitive char, copy it.
1275 if (strchr("ZBCSIFJD", *base) == NULL) {
1276 fprintf(stderr, "ERROR: bad method signature '%s'\n", base);
1277 goto bail;
1278 }
1279 *cp++ = *base++;
1280 }
1281 // Null terminate and display.
1282 *cp++ = '\0';
1283 char* tmp = descriptorToDot(tmpBuf);
1284 fprintf(gOutFile, "<parameter name=\"arg%d\" type=\"%s\">\n"
1285 "</parameter>\n", argNum++, tmp);
1286 free(tmp);
1287 } // while
1288 free(tmpBuf);
1289 if (constructor) {
1290 fprintf(gOutFile, "</constructor>\n");
1291 } else {
1292 fprintf(gOutFile, "</method>\n");
1293 }
1294 }
1295
1296 bail:
1297 free(typeDescriptor);
1298 free(accessStr);
1299}
1300
1301/*
1302 * Dumps a static (class) field.
1303 */
Aart Bikdce50862016-06-10 16:04:03 -07001304static void dumpSField(const DexFile* pDexFile, u4 idx, u4 flags, int i, const u1** data) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001305 // Bail for anything private if export only requested.
1306 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1307 return;
1308 }
1309
1310 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(idx);
1311 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
1312 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
1313 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
1314 char* accessStr = createAccessFlagStr(flags, kAccessForField);
1315
1316 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1317 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1318 fprintf(gOutFile, " name : '%s'\n", name);
1319 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1320 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
Aart Bikdce50862016-06-10 16:04:03 -07001321 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001322 fputs(" value : ", gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -07001323 dumpEncodedValue(pDexFile, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001324 fputs("\n", gOutFile);
1325 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001326 } else if (gOptions.outputFormat == OUTPUT_XML) {
1327 fprintf(gOutFile, "<field name=\"%s\"\n", name);
1328 char *tmp = descriptorToDot(typeDescriptor);
1329 fprintf(gOutFile, " type=\"%s\"\n", tmp);
1330 free(tmp);
1331 fprintf(gOutFile, " transient=%s\n", quotedBool((flags & kAccTransient) != 0));
1332 fprintf(gOutFile, " volatile=%s\n", quotedBool((flags & kAccVolatile) != 0));
1333 // The "value=" is not knowable w/o parsing annotations.
1334 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1335 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1336 // The "deprecated=" is not knowable w/o parsing annotations.
1337 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(flags));
Aart Bikdce50862016-06-10 16:04:03 -07001338 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001339 fputs(" value=\"", gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -07001340 dumpEncodedValue(pDexFile, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001341 fputs("\"\n", gOutFile);
1342 }
1343 fputs(">\n</field>\n", gOutFile);
Aart Bik69ae54a2015-07-01 14:52:26 -07001344 }
1345
1346 free(accessStr);
1347}
1348
1349/*
1350 * Dumps an instance field.
1351 */
1352static void dumpIField(const DexFile* pDexFile, u4 idx, u4 flags, int i) {
Aart Bikdce50862016-06-10 16:04:03 -07001353 dumpSField(pDexFile, idx, flags, i, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001354}
1355
1356/*
Andreas Gampe5073fed2015-08-10 11:40:25 -07001357 * Dumping a CFG. Note that this will do duplicate work. utils.h doesn't expose the code-item
1358 * version, so the DumpMethodCFG code will have to iterate again to find it. But dexdump is a
1359 * tool, so this is not performance-critical.
1360 */
1361
1362static void dumpCfg(const DexFile* dex_file,
Aart Bikdce50862016-06-10 16:04:03 -07001363 u4 dex_method_idx,
Andreas Gampe5073fed2015-08-10 11:40:25 -07001364 const DexFile::CodeItem* code_item) {
1365 if (code_item != nullptr) {
1366 std::ostringstream oss;
1367 DumpMethodCFG(dex_file, dex_method_idx, oss);
1368 fprintf(gOutFile, "%s", oss.str().c_str());
1369 }
1370}
1371
1372static void dumpCfg(const DexFile* dex_file, int idx) {
1373 const DexFile::ClassDef& class_def = dex_file->GetClassDef(idx);
Aart Bikdce50862016-06-10 16:04:03 -07001374 const u1* class_data = dex_file->GetClassData(class_def);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001375 if (class_data == nullptr) { // empty class such as a marker interface?
1376 return;
1377 }
1378 ClassDataItemIterator it(*dex_file, class_data);
1379 while (it.HasNextStaticField()) {
1380 it.Next();
1381 }
1382 while (it.HasNextInstanceField()) {
1383 it.Next();
1384 }
1385 while (it.HasNextDirectMethod()) {
1386 dumpCfg(dex_file,
1387 it.GetMemberIndex(),
1388 it.GetMethodCodeItem());
1389 it.Next();
1390 }
1391 while (it.HasNextVirtualMethod()) {
1392 dumpCfg(dex_file,
1393 it.GetMemberIndex(),
1394 it.GetMethodCodeItem());
1395 it.Next();
1396 }
1397}
1398
1399/*
Aart Bik69ae54a2015-07-01 14:52:26 -07001400 * Dumps the class.
1401 *
1402 * Note "idx" is a DexClassDef index, not a DexTypeId index.
1403 *
1404 * If "*pLastPackage" is nullptr or does not match the current class' package,
1405 * the value will be replaced with a newly-allocated string.
1406 */
1407static void dumpClass(const DexFile* pDexFile, int idx, char** pLastPackage) {
1408 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
1409
1410 // Omitting non-public class.
1411 if (gOptions.exportsOnly && (pClassDef.access_flags_ & kAccPublic) == 0) {
1412 return;
1413 }
1414
Aart Bikdce50862016-06-10 16:04:03 -07001415 if (gOptions.showSectionHeaders) {
1416 dumpClassDef(pDexFile, idx);
1417 }
1418
1419 if (gOptions.showAnnotations) {
1420 dumpClassAnnotations(pDexFile, idx);
1421 }
1422
1423 if (gOptions.showCfg) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001424 dumpCfg(pDexFile, idx);
1425 return;
1426 }
1427
Aart Bik69ae54a2015-07-01 14:52:26 -07001428 // For the XML output, show the package name. Ideally we'd gather
1429 // up the classes, sort them, and dump them alphabetically so the
1430 // package name wouldn't jump around, but that's not a great plan
1431 // for something that needs to run on the device.
1432 const char* classDescriptor = pDexFile->StringByTypeIdx(pClassDef.class_idx_);
1433 if (!(classDescriptor[0] == 'L' &&
1434 classDescriptor[strlen(classDescriptor)-1] == ';')) {
1435 // Arrays and primitives should not be defined explicitly. Keep going?
1436 fprintf(stderr, "Malformed class name '%s'\n", classDescriptor);
1437 } else if (gOptions.outputFormat == OUTPUT_XML) {
1438 char* mangle = strdup(classDescriptor + 1);
1439 mangle[strlen(mangle)-1] = '\0';
1440
1441 // Reduce to just the package name.
1442 char* lastSlash = strrchr(mangle, '/');
1443 if (lastSlash != nullptr) {
1444 *lastSlash = '\0';
1445 } else {
1446 *mangle = '\0';
1447 }
1448
1449 for (char* cp = mangle; *cp != '\0'; cp++) {
1450 if (*cp == '/') {
1451 *cp = '.';
1452 }
1453 } // for
1454
1455 if (*pLastPackage == nullptr || strcmp(mangle, *pLastPackage) != 0) {
1456 // Start of a new package.
1457 if (*pLastPackage != nullptr) {
1458 fprintf(gOutFile, "</package>\n");
1459 }
1460 fprintf(gOutFile, "<package name=\"%s\"\n>\n", mangle);
1461 free(*pLastPackage);
1462 *pLastPackage = mangle;
1463 } else {
1464 free(mangle);
1465 }
1466 }
1467
1468 // General class information.
1469 char* accessStr = createAccessFlagStr(pClassDef.access_flags_, kAccessForClass);
1470 const char* superclassDescriptor;
1471 if (pClassDef.superclass_idx_ == DexFile::kDexNoIndex16) {
1472 superclassDescriptor = nullptr;
1473 } else {
1474 superclassDescriptor = pDexFile->StringByTypeIdx(pClassDef.superclass_idx_);
1475 }
1476 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1477 fprintf(gOutFile, "Class #%d -\n", idx);
1478 fprintf(gOutFile, " Class descriptor : '%s'\n", classDescriptor);
1479 fprintf(gOutFile, " Access flags : 0x%04x (%s)\n", pClassDef.access_flags_, accessStr);
1480 if (superclassDescriptor != nullptr) {
1481 fprintf(gOutFile, " Superclass : '%s'\n", superclassDescriptor);
1482 }
1483 fprintf(gOutFile, " Interfaces -\n");
1484 } else {
1485 char* tmp = descriptorClassToDot(classDescriptor);
1486 fprintf(gOutFile, "<class name=\"%s\"\n", tmp);
1487 free(tmp);
1488 if (superclassDescriptor != nullptr) {
1489 tmp = descriptorToDot(superclassDescriptor);
1490 fprintf(gOutFile, " extends=\"%s\"\n", tmp);
1491 free(tmp);
1492 }
Alex Light1f12e282015-12-10 16:49:47 -08001493 fprintf(gOutFile, " interface=%s\n",
1494 quotedBool((pClassDef.access_flags_ & kAccInterface) != 0));
Aart Bik69ae54a2015-07-01 14:52:26 -07001495 fprintf(gOutFile, " abstract=%s\n", quotedBool((pClassDef.access_flags_ & kAccAbstract) != 0));
1496 fprintf(gOutFile, " static=%s\n", quotedBool((pClassDef.access_flags_ & kAccStatic) != 0));
1497 fprintf(gOutFile, " final=%s\n", quotedBool((pClassDef.access_flags_ & kAccFinal) != 0));
1498 // The "deprecated=" not knowable w/o parsing annotations.
1499 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(pClassDef.access_flags_));
1500 fprintf(gOutFile, ">\n");
1501 }
1502
1503 // Interfaces.
1504 const DexFile::TypeList* pInterfaces = pDexFile->GetInterfacesList(pClassDef);
1505 if (pInterfaces != nullptr) {
1506 for (u4 i = 0; i < pInterfaces->Size(); i++) {
1507 dumpInterface(pDexFile, pInterfaces->GetTypeItem(i), i);
1508 } // for
1509 }
1510
1511 // Fields and methods.
1512 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
1513 if (pEncodedData == nullptr) {
1514 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1515 fprintf(gOutFile, " Static fields -\n");
1516 fprintf(gOutFile, " Instance fields -\n");
1517 fprintf(gOutFile, " Direct methods -\n");
1518 fprintf(gOutFile, " Virtual methods -\n");
1519 }
1520 } else {
1521 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
Aart Bikdce50862016-06-10 16:04:03 -07001522
1523 // Prepare data for static fields.
1524 const u1* sData = pDexFile->GetEncodedStaticFieldValuesArray(pClassDef);
1525 const u4 sSize = sData != nullptr ? DecodeUnsignedLeb128(&sData) : 0;
1526
1527 // Static fields.
Aart Bik69ae54a2015-07-01 14:52:26 -07001528 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1529 fprintf(gOutFile, " Static fields -\n");
1530 }
Aart Bikdce50862016-06-10 16:04:03 -07001531 for (u4 i = 0; pClassData.HasNextStaticField(); i++, pClassData.Next()) {
1532 dumpSField(pDexFile,
1533 pClassData.GetMemberIndex(),
1534 pClassData.GetRawMemberAccessFlags(),
1535 i,
1536 i < sSize ? &sData : nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001537 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001538
1539 // Instance fields.
Aart Bik69ae54a2015-07-01 14:52:26 -07001540 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1541 fprintf(gOutFile, " Instance fields -\n");
1542 }
Aart Bikdce50862016-06-10 16:04:03 -07001543 for (u4 i = 0; pClassData.HasNextInstanceField(); i++, pClassData.Next()) {
1544 dumpIField(pDexFile,
1545 pClassData.GetMemberIndex(),
1546 pClassData.GetRawMemberAccessFlags(),
1547 i);
Aart Bik69ae54a2015-07-01 14:52:26 -07001548 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001549
1550 // Direct methods.
Aart Bik69ae54a2015-07-01 14:52:26 -07001551 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1552 fprintf(gOutFile, " Direct methods -\n");
1553 }
1554 for (int i = 0; pClassData.HasNextDirectMethod(); i++, pClassData.Next()) {
1555 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1556 pClassData.GetRawMemberAccessFlags(),
1557 pClassData.GetMethodCodeItem(),
1558 pClassData.GetMethodCodeItemOffset(), i);
1559 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001560
1561 // Virtual methods.
Aart Bik69ae54a2015-07-01 14:52:26 -07001562 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1563 fprintf(gOutFile, " Virtual methods -\n");
1564 }
1565 for (int i = 0; pClassData.HasNextVirtualMethod(); i++, pClassData.Next()) {
1566 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1567 pClassData.GetRawMemberAccessFlags(),
1568 pClassData.GetMethodCodeItem(),
1569 pClassData.GetMethodCodeItemOffset(), i);
1570 } // for
1571 }
1572
1573 // End of class.
1574 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1575 const char* fileName;
1576 if (pClassDef.source_file_idx_ != DexFile::kDexNoIndex) {
1577 fileName = pDexFile->StringDataByIdx(pClassDef.source_file_idx_);
1578 } else {
1579 fileName = "unknown";
1580 }
1581 fprintf(gOutFile, " source_file_idx : %d (%s)\n\n",
1582 pClassDef.source_file_idx_, fileName);
1583 } else if (gOptions.outputFormat == OUTPUT_XML) {
1584 fprintf(gOutFile, "</class>\n");
1585 }
1586
1587 free(accessStr);
1588}
1589
1590/*
1591 * Dumps the requested sections of the file.
1592 */
1593static void processDexFile(const char* fileName, const DexFile* pDexFile) {
1594 if (gOptions.verbose) {
1595 fprintf(gOutFile, "Opened '%s', DEX version '%.3s'\n",
1596 fileName, pDexFile->GetHeader().magic_ + 4);
1597 }
1598
1599 // Headers.
1600 if (gOptions.showFileHeaders) {
1601 dumpFileHeader(pDexFile);
1602 }
1603
1604 // Open XML context.
1605 if (gOptions.outputFormat == OUTPUT_XML) {
1606 fprintf(gOutFile, "<api>\n");
1607 }
1608
1609 // Iterate over all classes.
1610 char* package = nullptr;
1611 const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
1612 for (u4 i = 0; i < classDefsSize; i++) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001613 dumpClass(pDexFile, i, &package);
1614 } // for
1615
1616 // Free the last package allocated.
1617 if (package != nullptr) {
1618 fprintf(gOutFile, "</package>\n");
1619 free(package);
1620 }
1621
1622 // Close XML context.
1623 if (gOptions.outputFormat == OUTPUT_XML) {
1624 fprintf(gOutFile, "</api>\n");
1625 }
1626}
1627
1628/*
1629 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
1630 */
1631int processFile(const char* fileName) {
1632 if (gOptions.verbose) {
1633 fprintf(gOutFile, "Processing '%s'...\n", fileName);
1634 }
1635
1636 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
Aart Bikdce50862016-06-10 16:04:03 -07001637 // all of which are Zip archives with "classes.dex" inside.
Aart Bik37d6a3b2016-06-21 18:30:10 -07001638 const bool kVerifyChecksum = !gOptions.ignoreBadChecksum;
Aart Bik69ae54a2015-07-01 14:52:26 -07001639 std::string error_msg;
1640 std::vector<std::unique_ptr<const DexFile>> dex_files;
Aart Bik37d6a3b2016-06-21 18:30:10 -07001641 if (!DexFile::Open(fileName, fileName, kVerifyChecksum, &error_msg, &dex_files)) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001642 // Display returned error message to user. Note that this error behavior
1643 // differs from the error messages shown by the original Dalvik dexdump.
1644 fputs(error_msg.c_str(), stderr);
1645 fputc('\n', stderr);
1646 return -1;
1647 }
1648
Aart Bik4e149602015-07-09 11:45:28 -07001649 // Success. Either report checksum verification or process
1650 // all dex files found in given file.
Aart Bik69ae54a2015-07-01 14:52:26 -07001651 if (gOptions.checksumOnly) {
1652 fprintf(gOutFile, "Checksum verified\n");
1653 } else {
Aart Bik4e149602015-07-09 11:45:28 -07001654 for (size_t i = 0; i < dex_files.size(); i++) {
1655 processDexFile(fileName, dex_files[i].get());
1656 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001657 }
1658 return 0;
1659}
1660
1661} // namespace art