blob: e9b64028de7096da9630ffd7f6f3ebda67d1a0f3 [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
40#include <memory>
Andreas Gampe5073fed2015-08-10 11:40:25 -070041#include <sstream>
Aart Bik69ae54a2015-07-01 14:52:26 -070042#include <vector>
43
David Sehr999646d2018-02-16 10:22:33 -080044#include "android-base/file.h"
Andreas Gampe221d9812018-01-22 17:48:56 -080045#include "android-base/logging.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080046#include "android-base/stringprintf.h"
47
Mathieu Chartierc2b4db62018-05-18 13:58:12 -070048#include "dex/class_accessor-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000049#include "dex/code_item_accessors-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080050#include "dex/dex_file-inl.h"
51#include "dex/dex_file_exception_helpers.h"
52#include "dex/dex_file_loader.h"
53#include "dex/dex_file_types.h"
54#include "dex/dex_instruction-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070055#include "dexdump_cfg.h"
Aart Bik69ae54a2015-07-01 14:52:26 -070056
57namespace art {
58
59/*
60 * Options parsed in main driver.
61 */
62struct Options gOptions;
63
64/*
Aart Bik4e149602015-07-09 11:45:28 -070065 * Output file. Defaults to stdout.
Aart Bik69ae54a2015-07-01 14:52:26 -070066 */
67FILE* gOutFile = stdout;
68
69/*
70 * Data types that match the definitions in the VM specification.
71 */
72typedef uint8_t u1;
73typedef uint16_t u2;
74typedef uint32_t u4;
75typedef uint64_t u8;
Aart Bikdce50862016-06-10 16:04:03 -070076typedef int8_t s1;
77typedef int16_t s2;
Aart Bik69ae54a2015-07-01 14:52:26 -070078typedef int32_t s4;
79typedef int64_t s8;
80
81/*
82 * Basic information about a field or a method.
83 */
84struct FieldMethodInfo {
85 const char* classDescriptor;
86 const char* name;
87 const char* signature;
88};
89
90/*
91 * Flags for use with createAccessFlagStr().
92 */
93enum AccessFor {
94 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
95};
96const int kNumFlags = 18;
97
98/*
99 * Gets 2 little-endian bytes.
100 */
101static inline u2 get2LE(unsigned char const* pSrc) {
102 return pSrc[0] | (pSrc[1] << 8);
103}
104
105/*
106 * Converts a single-character primitive type into human-readable form.
107 */
108static const char* primitiveTypeLabel(char typeChar) {
109 switch (typeChar) {
110 case 'B': return "byte";
111 case 'C': return "char";
112 case 'D': return "double";
113 case 'F': return "float";
114 case 'I': return "int";
115 case 'J': return "long";
116 case 'S': return "short";
117 case 'V': return "void";
118 case 'Z': return "boolean";
119 default: return "UNKNOWN";
120 } // switch
121}
122
123/*
124 * Converts a type descriptor to human-readable "dotted" form. For
125 * example, "Ljava/lang/String;" becomes "java.lang.String", and
Orion Hodsonfe42d212018-08-24 14:01:14 +0100126 * "[I" becomes "int[]".
Aart Bik69ae54a2015-07-01 14:52:26 -0700127 */
Aart Bikc05e2f22016-07-12 15:53:13 -0700128static std::unique_ptr<char[]> descriptorToDot(const char* str) {
Aart Bik69ae54a2015-07-01 14:52:26 -0700129 int targetLen = strlen(str);
130 int offset = 0;
131
132 // Strip leading [s; will be added to end.
133 while (targetLen > 1 && str[offset] == '[') {
134 offset++;
135 targetLen--;
136 } // while
137
138 const int arrayDepth = offset;
139
140 if (targetLen == 1) {
141 // Primitive type.
142 str = primitiveTypeLabel(str[offset]);
143 offset = 0;
144 targetLen = strlen(str);
145 } else {
146 // Account for leading 'L' and trailing ';'.
147 if (targetLen >= 2 && str[offset] == 'L' &&
148 str[offset + targetLen - 1] == ';') {
149 targetLen -= 2;
150 offset++;
151 }
152 }
153
154 // Copy class name over.
Aart Bikc05e2f22016-07-12 15:53:13 -0700155 std::unique_ptr<char[]> newStr(new char[targetLen + arrayDepth * 2 + 1]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700156 int i = 0;
157 for (; i < targetLen; i++) {
158 const char ch = str[offset + i];
Orion Hodsonfe42d212018-08-24 14:01:14 +0100159 newStr[i] = (ch == '/') ? '.' : ch;
Aart Bik69ae54a2015-07-01 14:52:26 -0700160 } // for
161
162 // Add the appropriate number of brackets for arrays.
163 for (int j = 0; j < arrayDepth; j++) {
164 newStr[i++] = '[';
165 newStr[i++] = ']';
166 } // for
167
168 newStr[i] = '\0';
169 return newStr;
170}
171
172/*
Orion Hodsonfe42d212018-08-24 14:01:14 +0100173 * Retrieves the class name portion of a type descriptor.
Aart Bik69ae54a2015-07-01 14:52:26 -0700174 */
Orion Hodsonfe42d212018-08-24 14:01:14 +0100175static std::unique_ptr<char[]> descriptorClassToName(const char* str) {
Aart Bikc05e2f22016-07-12 15:53:13 -0700176 // Reduce to just the class name prefix.
Aart Bik69ae54a2015-07-01 14:52:26 -0700177 const char* lastSlash = strrchr(str, '/');
178 if (lastSlash == nullptr) {
179 lastSlash = str + 1; // start past 'L'
180 } else {
181 lastSlash++; // start past '/'
182 }
183
Aart Bikc05e2f22016-07-12 15:53:13 -0700184 // Copy class name over, trimming trailing ';'.
185 const int targetLen = strlen(lastSlash);
186 std::unique_ptr<char[]> newStr(new char[targetLen]);
187 for (int i = 0; i < targetLen - 1; i++) {
Orion Hodsonfe42d212018-08-24 14:01:14 +0100188 newStr[i] = lastSlash[i];
Aart Bik69ae54a2015-07-01 14:52:26 -0700189 } // for
Aart Bikc05e2f22016-07-12 15:53:13 -0700190 newStr[targetLen - 1] = '\0';
Aart Bik69ae54a2015-07-01 14:52:26 -0700191 return newStr;
192}
193
194/*
Aart Bikdce50862016-06-10 16:04:03 -0700195 * Returns string representing the boolean value.
196 */
197static const char* strBool(bool val) {
198 return val ? "true" : "false";
199}
200
201/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700202 * Returns a quoted string representing the boolean value.
203 */
204static const char* quotedBool(bool val) {
205 return val ? "\"true\"" : "\"false\"";
206}
207
208/*
209 * Returns a quoted string representing the access flags.
210 */
211static const char* quotedVisibility(u4 accessFlags) {
212 if (accessFlags & kAccPublic) {
213 return "\"public\"";
214 } else if (accessFlags & kAccProtected) {
215 return "\"protected\"";
216 } else if (accessFlags & kAccPrivate) {
217 return "\"private\"";
218 } else {
219 return "\"package\"";
220 }
221}
222
223/*
224 * Counts the number of '1' bits in a word.
225 */
226static int countOnes(u4 val) {
227 val = val - ((val >> 1) & 0x55555555);
228 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
229 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
230}
231
232/*
233 * Creates a new string with human-readable access flags.
234 *
235 * In the base language the access_flags fields are type u2; in Dalvik
236 * they're u4.
237 */
238static char* createAccessFlagStr(u4 flags, AccessFor forWhat) {
239 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
240 {
241 "PUBLIC", /* 0x00001 */
242 "PRIVATE", /* 0x00002 */
243 "PROTECTED", /* 0x00004 */
244 "STATIC", /* 0x00008 */
245 "FINAL", /* 0x00010 */
246 "?", /* 0x00020 */
247 "?", /* 0x00040 */
248 "?", /* 0x00080 */
249 "?", /* 0x00100 */
250 "INTERFACE", /* 0x00200 */
251 "ABSTRACT", /* 0x00400 */
252 "?", /* 0x00800 */
253 "SYNTHETIC", /* 0x01000 */
254 "ANNOTATION", /* 0x02000 */
255 "ENUM", /* 0x04000 */
256 "?", /* 0x08000 */
257 "VERIFIED", /* 0x10000 */
258 "OPTIMIZED", /* 0x20000 */
259 }, {
260 "PUBLIC", /* 0x00001 */
261 "PRIVATE", /* 0x00002 */
262 "PROTECTED", /* 0x00004 */
263 "STATIC", /* 0x00008 */
264 "FINAL", /* 0x00010 */
265 "SYNCHRONIZED", /* 0x00020 */
266 "BRIDGE", /* 0x00040 */
267 "VARARGS", /* 0x00080 */
268 "NATIVE", /* 0x00100 */
269 "?", /* 0x00200 */
270 "ABSTRACT", /* 0x00400 */
271 "STRICT", /* 0x00800 */
272 "SYNTHETIC", /* 0x01000 */
273 "?", /* 0x02000 */
274 "?", /* 0x04000 */
275 "MIRANDA", /* 0x08000 */
276 "CONSTRUCTOR", /* 0x10000 */
277 "DECLARED_SYNCHRONIZED", /* 0x20000 */
278 }, {
279 "PUBLIC", /* 0x00001 */
280 "PRIVATE", /* 0x00002 */
281 "PROTECTED", /* 0x00004 */
282 "STATIC", /* 0x00008 */
283 "FINAL", /* 0x00010 */
284 "?", /* 0x00020 */
285 "VOLATILE", /* 0x00040 */
286 "TRANSIENT", /* 0x00080 */
287 "?", /* 0x00100 */
288 "?", /* 0x00200 */
289 "?", /* 0x00400 */
290 "?", /* 0x00800 */
291 "SYNTHETIC", /* 0x01000 */
292 "?", /* 0x02000 */
293 "ENUM", /* 0x04000 */
294 "?", /* 0x08000 */
295 "?", /* 0x10000 */
296 "?", /* 0x20000 */
297 },
298 };
299
300 // Allocate enough storage to hold the expected number of strings,
301 // plus a space between each. We over-allocate, using the longest
302 // string above as the base metric.
303 const int kLongest = 21; // The strlen of longest string above.
304 const int count = countOnes(flags);
305 char* str;
306 char* cp;
307 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
308
309 for (int i = 0; i < kNumFlags; i++) {
310 if (flags & 0x01) {
311 const char* accessStr = kAccessStrings[forWhat][i];
312 const int len = strlen(accessStr);
313 if (cp != str) {
314 *cp++ = ' ';
315 }
316 memcpy(cp, accessStr, len);
317 cp += len;
318 }
319 flags >>= 1;
320 } // for
321
322 *cp = '\0';
323 return str;
324}
325
326/*
327 * Copies character data from "data" to "out", converting non-ASCII values
328 * to fprintf format chars or an ASCII filler ('.' or '?').
329 *
330 * The output buffer must be able to hold (2*len)+1 bytes. The result is
331 * NULL-terminated.
332 */
333static void asciify(char* out, const unsigned char* data, size_t len) {
334 while (len--) {
335 if (*data < 0x20) {
336 // Could do more here, but we don't need them yet.
337 switch (*data) {
338 case '\0':
339 *out++ = '\\';
340 *out++ = '0';
341 break;
342 case '\n':
343 *out++ = '\\';
344 *out++ = 'n';
345 break;
346 default:
347 *out++ = '.';
348 break;
349 } // switch
350 } else if (*data >= 0x80) {
351 *out++ = '?';
352 } else {
353 *out++ = *data;
354 }
355 data++;
356 } // while
357 *out = '\0';
358}
359
360/*
Aart Bikdce50862016-06-10 16:04:03 -0700361 * Dumps a string value with some escape characters.
362 */
363static void dumpEscapedString(const char* p) {
364 fputs("\"", gOutFile);
365 for (; *p; p++) {
366 switch (*p) {
367 case '\\':
368 fputs("\\\\", gOutFile);
369 break;
370 case '\"':
371 fputs("\\\"", gOutFile);
372 break;
373 case '\t':
374 fputs("\\t", gOutFile);
375 break;
376 case '\n':
377 fputs("\\n", gOutFile);
378 break;
379 case '\r':
380 fputs("\\r", gOutFile);
381 break;
382 default:
383 putc(*p, gOutFile);
384 } // switch
385 } // for
386 fputs("\"", gOutFile);
387}
388
389/*
390 * Dumps a string as an XML attribute value.
391 */
392static void dumpXmlAttribute(const char* p) {
393 for (; *p; p++) {
394 switch (*p) {
395 case '&':
396 fputs("&amp;", gOutFile);
397 break;
398 case '<':
399 fputs("&lt;", gOutFile);
400 break;
401 case '>':
402 fputs("&gt;", gOutFile);
403 break;
404 case '"':
405 fputs("&quot;", gOutFile);
406 break;
407 case '\t':
408 fputs("&#x9;", gOutFile);
409 break;
410 case '\n':
411 fputs("&#xA;", gOutFile);
412 break;
413 case '\r':
414 fputs("&#xD;", gOutFile);
415 break;
416 default:
417 putc(*p, gOutFile);
418 } // switch
419 } // for
420}
421
422/*
423 * Reads variable width value, possibly sign extended at the last defined byte.
424 */
425static u8 readVarWidth(const u1** data, u1 arg, bool sign_extend) {
426 u8 value = 0;
427 for (u4 i = 0; i <= arg; i++) {
428 value |= static_cast<u8>(*(*data)++) << (i * 8);
429 }
430 if (sign_extend) {
431 int shift = (7 - arg) * 8;
432 return (static_cast<s8>(value) << shift) >> shift;
433 }
434 return value;
435}
436
437/*
438 * Dumps encoded value.
439 */
440static void dumpEncodedValue(const DexFile* pDexFile, const u1** data); // forward
441static void dumpEncodedValue(const DexFile* pDexFile, const u1** data, u1 type, u1 arg) {
442 switch (type) {
443 case DexFile::kDexAnnotationByte:
444 fprintf(gOutFile, "%" PRId8, static_cast<s1>(readVarWidth(data, arg, false)));
445 break;
446 case DexFile::kDexAnnotationShort:
447 fprintf(gOutFile, "%" PRId16, static_cast<s2>(readVarWidth(data, arg, true)));
448 break;
449 case DexFile::kDexAnnotationChar:
450 fprintf(gOutFile, "%" PRIu16, static_cast<u2>(readVarWidth(data, arg, false)));
451 break;
452 case DexFile::kDexAnnotationInt:
453 fprintf(gOutFile, "%" PRId32, static_cast<s4>(readVarWidth(data, arg, true)));
454 break;
455 case DexFile::kDexAnnotationLong:
456 fprintf(gOutFile, "%" PRId64, static_cast<s8>(readVarWidth(data, arg, true)));
457 break;
458 case DexFile::kDexAnnotationFloat: {
459 // Fill on right.
460 union {
461 float f;
462 u4 data;
463 } conv;
464 conv.data = static_cast<u4>(readVarWidth(data, arg, false)) << (3 - arg) * 8;
465 fprintf(gOutFile, "%g", conv.f);
466 break;
467 }
468 case DexFile::kDexAnnotationDouble: {
469 // Fill on right.
470 union {
471 double d;
472 u8 data;
473 } conv;
474 conv.data = readVarWidth(data, arg, false) << (7 - arg) * 8;
475 fprintf(gOutFile, "%g", conv.d);
476 break;
477 }
478 case DexFile::kDexAnnotationString: {
479 const u4 idx = static_cast<u4>(readVarWidth(data, arg, false));
480 if (gOptions.outputFormat == OUTPUT_PLAIN) {
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800481 dumpEscapedString(pDexFile->StringDataByIdx(dex::StringIndex(idx)));
Aart Bikdce50862016-06-10 16:04:03 -0700482 } else {
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800483 dumpXmlAttribute(pDexFile->StringDataByIdx(dex::StringIndex(idx)));
Aart Bikdce50862016-06-10 16:04:03 -0700484 }
485 break;
486 }
487 case DexFile::kDexAnnotationType: {
488 const u4 str_idx = static_cast<u4>(readVarWidth(data, arg, false));
Andreas Gampea5b09a62016-11-17 15:21:22 -0800489 fputs(pDexFile->StringByTypeIdx(dex::TypeIndex(str_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700490 break;
491 }
492 case DexFile::kDexAnnotationField:
493 case DexFile::kDexAnnotationEnum: {
494 const u4 field_idx = static_cast<u4>(readVarWidth(data, arg, false));
495 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
496 fputs(pDexFile->StringDataByIdx(pFieldId.name_idx_), gOutFile);
497 break;
498 }
499 case DexFile::kDexAnnotationMethod: {
500 const u4 method_idx = static_cast<u4>(readVarWidth(data, arg, false));
501 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
502 fputs(pDexFile->StringDataByIdx(pMethodId.name_idx_), gOutFile);
503 break;
504 }
505 case DexFile::kDexAnnotationArray: {
506 fputc('{', gOutFile);
507 // Decode and display all elements.
508 const u4 size = DecodeUnsignedLeb128(data);
509 for (u4 i = 0; i < size; i++) {
510 fputc(' ', gOutFile);
511 dumpEncodedValue(pDexFile, data);
512 }
513 fputs(" }", gOutFile);
514 break;
515 }
516 case DexFile::kDexAnnotationAnnotation: {
517 const u4 type_idx = DecodeUnsignedLeb128(data);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800518 fputs(pDexFile->StringByTypeIdx(dex::TypeIndex(type_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700519 // Decode and display all name=value pairs.
520 const u4 size = DecodeUnsignedLeb128(data);
521 for (u4 i = 0; i < size; i++) {
522 const u4 name_idx = DecodeUnsignedLeb128(data);
523 fputc(' ', gOutFile);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800524 fputs(pDexFile->StringDataByIdx(dex::StringIndex(name_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700525 fputc('=', gOutFile);
526 dumpEncodedValue(pDexFile, data);
527 }
528 break;
529 }
530 case DexFile::kDexAnnotationNull:
531 fputs("null", gOutFile);
532 break;
533 case DexFile::kDexAnnotationBoolean:
534 fputs(strBool(arg), gOutFile);
535 break;
536 default:
537 fputs("????", gOutFile);
538 break;
539 } // switch
540}
541
542/*
543 * Dumps encoded value with prefix.
544 */
545static void dumpEncodedValue(const DexFile* pDexFile, const u1** data) {
546 const u1 enc = *(*data)++;
547 dumpEncodedValue(pDexFile, data, enc & 0x1f, enc >> 5);
548}
549
550/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700551 * Dumps the file header.
Aart Bik69ae54a2015-07-01 14:52:26 -0700552 */
553static void dumpFileHeader(const DexFile* pDexFile) {
554 const DexFile::Header& pHeader = pDexFile->GetHeader();
555 char sanitized[sizeof(pHeader.magic_) * 2 + 1];
556 fprintf(gOutFile, "DEX file header:\n");
557 asciify(sanitized, pHeader.magic_, sizeof(pHeader.magic_));
558 fprintf(gOutFile, "magic : '%s'\n", sanitized);
559 fprintf(gOutFile, "checksum : %08x\n", pHeader.checksum_);
560 fprintf(gOutFile, "signature : %02x%02x...%02x%02x\n",
561 pHeader.signature_[0], pHeader.signature_[1],
562 pHeader.signature_[DexFile::kSha1DigestSize - 2],
563 pHeader.signature_[DexFile::kSha1DigestSize - 1]);
564 fprintf(gOutFile, "file_size : %d\n", pHeader.file_size_);
565 fprintf(gOutFile, "header_size : %d\n", pHeader.header_size_);
566 fprintf(gOutFile, "link_size : %d\n", pHeader.link_size_);
567 fprintf(gOutFile, "link_off : %d (0x%06x)\n",
568 pHeader.link_off_, pHeader.link_off_);
569 fprintf(gOutFile, "string_ids_size : %d\n", pHeader.string_ids_size_);
570 fprintf(gOutFile, "string_ids_off : %d (0x%06x)\n",
571 pHeader.string_ids_off_, pHeader.string_ids_off_);
572 fprintf(gOutFile, "type_ids_size : %d\n", pHeader.type_ids_size_);
573 fprintf(gOutFile, "type_ids_off : %d (0x%06x)\n",
574 pHeader.type_ids_off_, pHeader.type_ids_off_);
Aart Bikdce50862016-06-10 16:04:03 -0700575 fprintf(gOutFile, "proto_ids_size : %d\n", pHeader.proto_ids_size_);
576 fprintf(gOutFile, "proto_ids_off : %d (0x%06x)\n",
Aart Bik69ae54a2015-07-01 14:52:26 -0700577 pHeader.proto_ids_off_, pHeader.proto_ids_off_);
578 fprintf(gOutFile, "field_ids_size : %d\n", pHeader.field_ids_size_);
579 fprintf(gOutFile, "field_ids_off : %d (0x%06x)\n",
580 pHeader.field_ids_off_, pHeader.field_ids_off_);
581 fprintf(gOutFile, "method_ids_size : %d\n", pHeader.method_ids_size_);
582 fprintf(gOutFile, "method_ids_off : %d (0x%06x)\n",
583 pHeader.method_ids_off_, pHeader.method_ids_off_);
584 fprintf(gOutFile, "class_defs_size : %d\n", pHeader.class_defs_size_);
585 fprintf(gOutFile, "class_defs_off : %d (0x%06x)\n",
586 pHeader.class_defs_off_, pHeader.class_defs_off_);
587 fprintf(gOutFile, "data_size : %d\n", pHeader.data_size_);
588 fprintf(gOutFile, "data_off : %d (0x%06x)\n\n",
589 pHeader.data_off_, pHeader.data_off_);
590}
591
592/*
593 * Dumps a class_def_item.
594 */
595static void dumpClassDef(const DexFile* pDexFile, int idx) {
596 // General class information.
597 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
598 fprintf(gOutFile, "Class #%d header:\n", idx);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800599 fprintf(gOutFile, "class_idx : %d\n", pClassDef.class_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700600 fprintf(gOutFile, "access_flags : %d (0x%04x)\n",
601 pClassDef.access_flags_, pClassDef.access_flags_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800602 fprintf(gOutFile, "superclass_idx : %d\n", pClassDef.superclass_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700603 fprintf(gOutFile, "interfaces_off : %d (0x%06x)\n",
604 pClassDef.interfaces_off_, pClassDef.interfaces_off_);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800605 fprintf(gOutFile, "source_file_idx : %d\n", pClassDef.source_file_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700606 fprintf(gOutFile, "annotations_off : %d (0x%06x)\n",
607 pClassDef.annotations_off_, pClassDef.annotations_off_);
608 fprintf(gOutFile, "class_data_off : %d (0x%06x)\n",
609 pClassDef.class_data_off_, pClassDef.class_data_off_);
610
611 // Fields and methods.
Mathieu Chartier18e26872018-06-04 17:19:02 -0700612 ClassAccessor accessor(*pDexFile, idx);
Mathieu Chartierc2b4db62018-05-18 13:58:12 -0700613 fprintf(gOutFile, "static_fields_size : %d\n", accessor.NumStaticFields());
614 fprintf(gOutFile, "instance_fields_size: %d\n", accessor.NumInstanceFields());
615 fprintf(gOutFile, "direct_methods_size : %d\n", accessor.NumDirectMethods());
616 fprintf(gOutFile, "virtual_methods_size: %d\n", accessor.NumVirtualMethods());
Aart Bik69ae54a2015-07-01 14:52:26 -0700617 fprintf(gOutFile, "\n");
618}
619
Aart Bikdce50862016-06-10 16:04:03 -0700620/**
621 * Dumps an annotation set item.
622 */
623static void dumpAnnotationSetItem(const DexFile* pDexFile, const DexFile::AnnotationSetItem* set_item) {
624 if (set_item == nullptr || set_item->size_ == 0) {
625 fputs(" empty-annotation-set\n", gOutFile);
626 return;
627 }
628 for (u4 i = 0; i < set_item->size_; i++) {
629 const DexFile::AnnotationItem* annotation = pDexFile->GetAnnotationItem(set_item, i);
630 if (annotation == nullptr) {
631 continue;
632 }
633 fputs(" ", gOutFile);
634 switch (annotation->visibility_) {
635 case DexFile::kDexVisibilityBuild: fputs("VISIBILITY_BUILD ", gOutFile); break;
636 case DexFile::kDexVisibilityRuntime: fputs("VISIBILITY_RUNTIME ", gOutFile); break;
637 case DexFile::kDexVisibilitySystem: fputs("VISIBILITY_SYSTEM ", gOutFile); break;
638 default: fputs("VISIBILITY_UNKNOWN ", gOutFile); break;
639 } // switch
640 // Decode raw bytes in annotation.
641 const u1* rData = annotation->annotation_;
642 dumpEncodedValue(pDexFile, &rData, DexFile::kDexAnnotationAnnotation, 0);
643 fputc('\n', gOutFile);
644 }
645}
646
647/*
648 * Dumps class annotations.
649 */
650static void dumpClassAnnotations(const DexFile* pDexFile, int idx) {
651 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
652 const DexFile::AnnotationsDirectoryItem* dir = pDexFile->GetAnnotationsDirectory(pClassDef);
653 if (dir == nullptr) {
654 return; // none
655 }
656
657 fprintf(gOutFile, "Class #%d annotations:\n", idx);
658
659 const DexFile::AnnotationSetItem* class_set_item = pDexFile->GetClassAnnotationSet(dir);
660 const DexFile::FieldAnnotationsItem* fields = pDexFile->GetFieldAnnotations(dir);
661 const DexFile::MethodAnnotationsItem* methods = pDexFile->GetMethodAnnotations(dir);
662 const DexFile::ParameterAnnotationsItem* pars = pDexFile->GetParameterAnnotations(dir);
663
664 // Annotations on the class itself.
665 if (class_set_item != nullptr) {
666 fprintf(gOutFile, "Annotations on class\n");
667 dumpAnnotationSetItem(pDexFile, class_set_item);
668 }
669
670 // Annotations on fields.
671 if (fields != nullptr) {
672 for (u4 i = 0; i < dir->fields_size_; i++) {
673 const u4 field_idx = fields[i].field_idx_;
674 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
675 const char* field_name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
676 fprintf(gOutFile, "Annotations on field #%u '%s'\n", field_idx, field_name);
677 dumpAnnotationSetItem(pDexFile, pDexFile->GetFieldAnnotationSetItem(fields[i]));
678 }
679 }
680
681 // Annotations on methods.
682 if (methods != nullptr) {
683 for (u4 i = 0; i < dir->methods_size_; i++) {
684 const u4 method_idx = methods[i].method_idx_;
685 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
686 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
687 fprintf(gOutFile, "Annotations on method #%u '%s'\n", method_idx, method_name);
688 dumpAnnotationSetItem(pDexFile, pDexFile->GetMethodAnnotationSetItem(methods[i]));
689 }
690 }
691
692 // Annotations on method parameters.
693 if (pars != nullptr) {
694 for (u4 i = 0; i < dir->parameters_size_; i++) {
695 const u4 method_idx = pars[i].method_idx_;
696 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
697 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
698 fprintf(gOutFile, "Annotations on method #%u '%s' parameters\n", method_idx, method_name);
699 const DexFile::AnnotationSetRefList*
700 list = pDexFile->GetParameterAnnotationSetRefList(&pars[i]);
701 if (list != nullptr) {
702 for (u4 j = 0; j < list->size_; j++) {
703 fprintf(gOutFile, "#%u\n", j);
704 dumpAnnotationSetItem(pDexFile, pDexFile->GetSetRefItemItem(&list->list_[j]));
705 }
706 }
707 }
708 }
709
710 fputc('\n', gOutFile);
711}
712
Aart Bik69ae54a2015-07-01 14:52:26 -0700713/*
714 * Dumps an interface that a class declares to implement.
715 */
716static void dumpInterface(const DexFile* pDexFile, const DexFile::TypeItem& pTypeItem, int i) {
717 const char* interfaceName = pDexFile->StringByTypeIdx(pTypeItem.type_idx_);
718 if (gOptions.outputFormat == OUTPUT_PLAIN) {
719 fprintf(gOutFile, " #%d : '%s'\n", i, interfaceName);
720 } else {
Aart Bikc05e2f22016-07-12 15:53:13 -0700721 std::unique_ptr<char[]> dot(descriptorToDot(interfaceName));
722 fprintf(gOutFile, "<implements name=\"%s\">\n</implements>\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -0700723 }
724}
725
726/*
727 * Dumps the catches table associated with the code.
728 */
729static void dumpCatches(const DexFile* pDexFile, const DexFile::CodeItem* pCode) {
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800730 CodeItemDataAccessor accessor(*pDexFile, pCode);
Mathieu Chartierdc578c72017-12-27 11:51:45 -0800731 const u4 triesSize = accessor.TriesSize();
Aart Bik69ae54a2015-07-01 14:52:26 -0700732
733 // No catch table.
734 if (triesSize == 0) {
735 fprintf(gOutFile, " catches : (none)\n");
736 return;
737 }
738
739 // Dump all table entries.
740 fprintf(gOutFile, " catches : %d\n", triesSize);
Mathieu Chartierdc578c72017-12-27 11:51:45 -0800741 for (const DexFile::TryItem& try_item : accessor.TryItems()) {
742 const u4 start = try_item.start_addr_;
743 const u4 end = start + try_item.insn_count_;
Aart Bik69ae54a2015-07-01 14:52:26 -0700744 fprintf(gOutFile, " 0x%04x - 0x%04x\n", start, end);
Mathieu Chartierdc578c72017-12-27 11:51:45 -0800745 for (CatchHandlerIterator it(accessor, try_item); it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800746 const dex::TypeIndex tidx = it.GetHandlerTypeIndex();
747 const char* descriptor = (!tidx.IsValid()) ? "<any>" : pDexFile->StringByTypeIdx(tidx);
Aart Bik69ae54a2015-07-01 14:52:26 -0700748 fprintf(gOutFile, " %s -> 0x%04x\n", descriptor, it.GetHandlerAddress());
749 } // for
750 } // for
751}
752
753/*
754 * Callback for dumping each positions table entry.
755 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000756static bool dumpPositionsCb(void* /*context*/, const DexFile::PositionInfo& entry) {
757 fprintf(gOutFile, " 0x%04x line=%d\n", entry.address_, entry.line_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700758 return false;
759}
760
761/*
762 * Callback for dumping locals table entry.
763 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000764static void dumpLocalsCb(void* /*context*/, const DexFile::LocalInfo& entry) {
765 const char* signature = entry.signature_ != nullptr ? entry.signature_ : "";
Aart Bik69ae54a2015-07-01 14:52:26 -0700766 fprintf(gOutFile, " 0x%04x - 0x%04x reg=%d %s %s %s\n",
David Srbeckyb06e28e2015-12-10 13:15:00 +0000767 entry.start_address_, entry.end_address_, entry.reg_,
768 entry.name_, entry.descriptor_, signature);
Aart Bik69ae54a2015-07-01 14:52:26 -0700769}
770
771/*
772 * Helper for dumpInstruction(), which builds the string
Aart Bika0e33fd2016-07-08 18:32:45 -0700773 * representation for the index in the given instruction.
774 * Returns a pointer to a buffer of sufficient size.
Aart Bik69ae54a2015-07-01 14:52:26 -0700775 */
Aart Bika0e33fd2016-07-08 18:32:45 -0700776static std::unique_ptr<char[]> indexString(const DexFile* pDexFile,
777 const Instruction* pDecInsn,
778 size_t bufSize) {
779 std::unique_ptr<char[]> buf(new char[bufSize]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700780 // Determine index and width of the string.
781 u4 index = 0;
Orion Hodson06d10a72018-05-14 08:53:38 +0100782 u2 secondary_index = 0;
Aart Bik69ae54a2015-07-01 14:52:26 -0700783 u4 width = 4;
784 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
785 // SOME NOT SUPPORTED:
786 // case Instruction::k20bc:
787 case Instruction::k21c:
788 case Instruction::k35c:
789 // case Instruction::k35ms:
790 case Instruction::k3rc:
791 // case Instruction::k3rms:
792 // case Instruction::k35mi:
793 // case Instruction::k3rmi:
794 index = pDecInsn->VRegB();
795 width = 4;
796 break;
797 case Instruction::k31c:
798 index = pDecInsn->VRegB();
799 width = 8;
800 break;
801 case Instruction::k22c:
802 // case Instruction::k22cs:
803 index = pDecInsn->VRegC();
804 width = 4;
805 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100806 case Instruction::k45cc:
807 case Instruction::k4rcc:
808 index = pDecInsn->VRegB();
809 secondary_index = pDecInsn->VRegH();
810 width = 4;
811 break;
Aart Bik69ae54a2015-07-01 14:52:26 -0700812 default:
813 break;
814 } // switch
815
816 // Determine index type.
817 size_t outSize = 0;
818 switch (Instruction::IndexTypeOf(pDecInsn->Opcode())) {
819 case Instruction::kIndexUnknown:
820 // This function should never get called for this type, but do
821 // something sensible here, just to help with debugging.
Aart Bika0e33fd2016-07-08 18:32:45 -0700822 outSize = snprintf(buf.get(), bufSize, "<unknown-index>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700823 break;
824 case Instruction::kIndexNone:
825 // This function should never get called for this type, but do
826 // something sensible here, just to help with debugging.
Aart Bika0e33fd2016-07-08 18:32:45 -0700827 outSize = snprintf(buf.get(), bufSize, "<no-index>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700828 break;
829 case Instruction::kIndexTypeRef:
830 if (index < pDexFile->GetHeader().type_ids_size_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800831 const char* tp = pDexFile->StringByTypeIdx(dex::TypeIndex(index));
Aart Bika0e33fd2016-07-08 18:32:45 -0700832 outSize = snprintf(buf.get(), bufSize, "%s // type@%0*x", tp, width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700833 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700834 outSize = snprintf(buf.get(), bufSize, "<type?> // type@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700835 }
836 break;
837 case Instruction::kIndexStringRef:
838 if (index < pDexFile->GetHeader().string_ids_size_) {
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800839 const char* st = pDexFile->StringDataByIdx(dex::StringIndex(index));
Aart Bika0e33fd2016-07-08 18:32:45 -0700840 outSize = snprintf(buf.get(), bufSize, "\"%s\" // string@%0*x", st, width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700841 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700842 outSize = snprintf(buf.get(), bufSize, "<string?> // string@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700843 }
844 break;
845 case Instruction::kIndexMethodRef:
846 if (index < pDexFile->GetHeader().method_ids_size_) {
847 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
848 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
849 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
850 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
Aart Bika0e33fd2016-07-08 18:32:45 -0700851 outSize = snprintf(buf.get(), bufSize, "%s.%s:%s // method@%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700852 backDescriptor, name, signature.ToString().c_str(), width, index);
853 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700854 outSize = snprintf(buf.get(), bufSize, "<method?> // method@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700855 }
856 break;
857 case Instruction::kIndexFieldRef:
858 if (index < pDexFile->GetHeader().field_ids_size_) {
859 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(index);
860 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
861 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
862 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
Aart Bika0e33fd2016-07-08 18:32:45 -0700863 outSize = snprintf(buf.get(), bufSize, "%s.%s:%s // field@%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700864 backDescriptor, name, typeDescriptor, width, index);
865 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700866 outSize = snprintf(buf.get(), bufSize, "<field?> // field@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700867 }
868 break;
869 case Instruction::kIndexVtableOffset:
Aart Bika0e33fd2016-07-08 18:32:45 -0700870 outSize = snprintf(buf.get(), bufSize, "[%0*x] // vtable #%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700871 width, index, width, index);
872 break;
873 case Instruction::kIndexFieldOffset:
Aart Bika0e33fd2016-07-08 18:32:45 -0700874 outSize = snprintf(buf.get(), bufSize, "[obj+%0*x]", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700875 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100876 case Instruction::kIndexMethodAndProtoRef: {
Orion Hodsonc069a302017-01-18 09:23:12 +0000877 std::string method("<method?>");
878 std::string proto("<proto?>");
879 if (index < pDexFile->GetHeader().method_ids_size_) {
880 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
881 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
882 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
883 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
884 method = android::base::StringPrintf("%s.%s:%s",
885 backDescriptor,
886 name,
887 signature.ToString().c_str());
Orion Hodsonb34bb192016-10-18 17:02:58 +0100888 }
Orion Hodsonc069a302017-01-18 09:23:12 +0000889 if (secondary_index < pDexFile->GetHeader().proto_ids_size_) {
Orion Hodson06d10a72018-05-14 08:53:38 +0100890 const DexFile::ProtoId& protoId = pDexFile->GetProtoId(dex::ProtoIndex(secondary_index));
Orion Hodsonc069a302017-01-18 09:23:12 +0000891 const Signature signature = pDexFile->GetProtoSignature(protoId);
892 proto = signature.ToString();
893 }
894 outSize = snprintf(buf.get(), bufSize, "%s, %s // method@%0*x, proto@%0*x",
895 method.c_str(), proto.c_str(), width, index, width, secondary_index);
896 break;
897 }
898 case Instruction::kIndexCallSiteRef:
899 // Call site information is too large to detail in disassembly so just output the index.
900 outSize = snprintf(buf.get(), bufSize, "call_site@%0*x", width, index);
Orion Hodsonb34bb192016-10-18 17:02:58 +0100901 break;
Orion Hodson2e599942017-09-22 16:17:41 +0100902 case Instruction::kIndexMethodHandleRef:
903 // Method handle information is too large to detail in disassembly so just output the index.
904 outSize = snprintf(buf.get(), bufSize, "method_handle@%0*x", width, index);
905 break;
906 case Instruction::kIndexProtoRef:
907 if (index < pDexFile->GetHeader().proto_ids_size_) {
Orion Hodson06d10a72018-05-14 08:53:38 +0100908 const DexFile::ProtoId& protoId = pDexFile->GetProtoId(dex::ProtoIndex(index));
Orion Hodson2e599942017-09-22 16:17:41 +0100909 const Signature signature = pDexFile->GetProtoSignature(protoId);
910 const std::string& proto = signature.ToString();
911 outSize = snprintf(buf.get(), bufSize, "%s // proto@%0*x", proto.c_str(), width, index);
912 } else {
913 outSize = snprintf(buf.get(), bufSize, "<?> // proto@%0*x", width, index);
914 }
Aart Bik69ae54a2015-07-01 14:52:26 -0700915 break;
916 } // switch
917
Orion Hodson2e599942017-09-22 16:17:41 +0100918 if (outSize == 0) {
919 // The index type has not been handled in the switch above.
920 outSize = snprintf(buf.get(), bufSize, "<?>");
921 }
922
Aart Bik69ae54a2015-07-01 14:52:26 -0700923 // Determine success of string construction.
924 if (outSize >= bufSize) {
Aart Bika0e33fd2016-07-08 18:32:45 -0700925 // The buffer wasn't big enough; retry with computed size. Note: snprintf()
926 // doesn't count/ the '\0' as part of its returned size, so we add explicit
927 // space for it here.
928 return indexString(pDexFile, pDecInsn, outSize + 1);
Aart Bik69ae54a2015-07-01 14:52:26 -0700929 }
930 return buf;
931}
932
933/*
934 * Dumps a single instruction.
935 */
936static void dumpInstruction(const DexFile* pDexFile,
937 const DexFile::CodeItem* pCode,
938 u4 codeOffset, u4 insnIdx, u4 insnWidth,
939 const Instruction* pDecInsn) {
940 // Address of instruction (expressed as byte offset).
941 fprintf(gOutFile, "%06x:", codeOffset + 0x10 + insnIdx * 2);
942
943 // Dump (part of) raw bytes.
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800944 CodeItemInstructionAccessor accessor(*pDexFile, pCode);
Aart Bik69ae54a2015-07-01 14:52:26 -0700945 for (u4 i = 0; i < 8; i++) {
946 if (i < insnWidth) {
947 if (i == 7) {
948 fprintf(gOutFile, " ... ");
949 } else {
950 // Print 16-bit value in little-endian order.
Mathieu Chartier641a3af2017-12-15 11:42:58 -0800951 const u1* bytePtr = (const u1*) &accessor.Insns()[insnIdx + i];
Aart Bik69ae54a2015-07-01 14:52:26 -0700952 fprintf(gOutFile, " %02x%02x", bytePtr[0], bytePtr[1]);
953 }
954 } else {
955 fputs(" ", gOutFile);
956 }
957 } // for
958
959 // Dump pseudo-instruction or opcode.
960 if (pDecInsn->Opcode() == Instruction::NOP) {
Mathieu Chartier641a3af2017-12-15 11:42:58 -0800961 const u2 instr = get2LE((const u1*) &accessor.Insns()[insnIdx]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700962 if (instr == Instruction::kPackedSwitchSignature) {
963 fprintf(gOutFile, "|%04x: packed-switch-data (%d units)", insnIdx, insnWidth);
964 } else if (instr == Instruction::kSparseSwitchSignature) {
965 fprintf(gOutFile, "|%04x: sparse-switch-data (%d units)", insnIdx, insnWidth);
966 } else if (instr == Instruction::kArrayDataSignature) {
967 fprintf(gOutFile, "|%04x: array-data (%d units)", insnIdx, insnWidth);
968 } else {
969 fprintf(gOutFile, "|%04x: nop // spacer", insnIdx);
970 }
971 } else {
972 fprintf(gOutFile, "|%04x: %s", insnIdx, pDecInsn->Name());
973 }
974
975 // Set up additional argument.
Aart Bika0e33fd2016-07-08 18:32:45 -0700976 std::unique_ptr<char[]> indexBuf;
Aart Bik69ae54a2015-07-01 14:52:26 -0700977 if (Instruction::IndexTypeOf(pDecInsn->Opcode()) != Instruction::kIndexNone) {
Aart Bika0e33fd2016-07-08 18:32:45 -0700978 indexBuf = indexString(pDexFile, pDecInsn, 200);
Aart Bik69ae54a2015-07-01 14:52:26 -0700979 }
980
981 // Dump the instruction.
982 //
983 // NOTE: pDecInsn->DumpString(pDexFile) differs too much from original.
984 //
985 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
986 case Instruction::k10x: // op
987 break;
988 case Instruction::k12x: // op vA, vB
989 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
990 break;
991 case Instruction::k11n: // op vA, #+B
992 fprintf(gOutFile, " v%d, #int %d // #%x",
993 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u1)pDecInsn->VRegB());
994 break;
995 case Instruction::k11x: // op vAA
996 fprintf(gOutFile, " v%d", pDecInsn->VRegA());
997 break;
998 case Instruction::k10t: // op +AA
Aart Bikdce50862016-06-10 16:04:03 -0700999 case Instruction::k20t: { // op +AAAA
1000 const s4 targ = (s4) pDecInsn->VRegA();
1001 fprintf(gOutFile, " %04x // %c%04x",
1002 insnIdx + targ,
1003 (targ < 0) ? '-' : '+',
1004 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001005 break;
Aart Bikdce50862016-06-10 16:04:03 -07001006 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001007 case Instruction::k22x: // op vAA, vBBBB
1008 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
1009 break;
Aart Bikdce50862016-06-10 16:04:03 -07001010 case Instruction::k21t: { // op vAA, +BBBB
1011 const s4 targ = (s4) pDecInsn->VRegB();
1012 fprintf(gOutFile, " v%d, %04x // %c%04x", pDecInsn->VRegA(),
1013 insnIdx + targ,
1014 (targ < 0) ? '-' : '+',
1015 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001016 break;
Aart Bikdce50862016-06-10 16:04:03 -07001017 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001018 case Instruction::k21s: // op vAA, #+BBBB
1019 fprintf(gOutFile, " v%d, #int %d // #%x",
1020 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u2)pDecInsn->VRegB());
1021 break;
1022 case Instruction::k21h: // op vAA, #+BBBB0000[00000000]
1023 // The printed format varies a bit based on the actual opcode.
1024 if (pDecInsn->Opcode() == Instruction::CONST_HIGH16) {
1025 const s4 value = pDecInsn->VRegB() << 16;
1026 fprintf(gOutFile, " v%d, #int %d // #%x",
1027 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
1028 } else {
1029 const s8 value = ((s8) pDecInsn->VRegB()) << 48;
1030 fprintf(gOutFile, " v%d, #long %" PRId64 " // #%x",
1031 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
1032 }
1033 break;
1034 case Instruction::k21c: // op vAA, thing@BBBB
1035 case Instruction::k31c: // op vAA, thing@BBBBBBBB
Aart Bika0e33fd2016-07-08 18:32:45 -07001036 fprintf(gOutFile, " v%d, %s", pDecInsn->VRegA(), indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001037 break;
1038 case Instruction::k23x: // op vAA, vBB, vCC
1039 fprintf(gOutFile, " v%d, v%d, v%d",
1040 pDecInsn->VRegA(), pDecInsn->VRegB(), pDecInsn->VRegC());
1041 break;
1042 case Instruction::k22b: // op vAA, vBB, #+CC
1043 fprintf(gOutFile, " v%d, v%d, #int %d // #%02x",
1044 pDecInsn->VRegA(), pDecInsn->VRegB(),
1045 (s4) pDecInsn->VRegC(), (u1) pDecInsn->VRegC());
1046 break;
Aart Bikdce50862016-06-10 16:04:03 -07001047 case Instruction::k22t: { // op vA, vB, +CCCC
1048 const s4 targ = (s4) pDecInsn->VRegC();
1049 fprintf(gOutFile, " v%d, v%d, %04x // %c%04x",
1050 pDecInsn->VRegA(), pDecInsn->VRegB(),
1051 insnIdx + targ,
1052 (targ < 0) ? '-' : '+',
1053 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001054 break;
Aart Bikdce50862016-06-10 16:04:03 -07001055 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001056 case Instruction::k22s: // op vA, vB, #+CCCC
1057 fprintf(gOutFile, " v%d, v%d, #int %d // #%04x",
1058 pDecInsn->VRegA(), pDecInsn->VRegB(),
1059 (s4) pDecInsn->VRegC(), (u2) pDecInsn->VRegC());
1060 break;
1061 case Instruction::k22c: // op vA, vB, thing@CCCC
1062 // NOT SUPPORTED:
1063 // case Instruction::k22cs: // [opt] op vA, vB, field offset CCCC
1064 fprintf(gOutFile, " v%d, v%d, %s",
Aart Bika0e33fd2016-07-08 18:32:45 -07001065 pDecInsn->VRegA(), pDecInsn->VRegB(), indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001066 break;
1067 case Instruction::k30t:
1068 fprintf(gOutFile, " #%08x", pDecInsn->VRegA());
1069 break;
Aart Bikdce50862016-06-10 16:04:03 -07001070 case Instruction::k31i: { // op vAA, #+BBBBBBBB
1071 // This is often, but not always, a float.
1072 union {
1073 float f;
1074 u4 i;
1075 } conv;
1076 conv.i = pDecInsn->VRegB();
1077 fprintf(gOutFile, " v%d, #float %g // #%08x",
1078 pDecInsn->VRegA(), conv.f, pDecInsn->VRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001079 break;
Aart Bikdce50862016-06-10 16:04:03 -07001080 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001081 case Instruction::k31t: // op vAA, offset +BBBBBBBB
1082 fprintf(gOutFile, " v%d, %08x // +%08x",
1083 pDecInsn->VRegA(), insnIdx + pDecInsn->VRegB(), pDecInsn->VRegB());
1084 break;
1085 case Instruction::k32x: // op vAAAA, vBBBB
1086 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
1087 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +01001088 case Instruction::k35c: // op {vC, vD, vE, vF, vG}, thing@BBBB
1089 case Instruction::k45cc: { // op {vC, vD, vE, vF, vG}, method@BBBB, proto@HHHH
Aart Bik69ae54a2015-07-01 14:52:26 -07001090 // NOT SUPPORTED:
1091 // case Instruction::k35ms: // [opt] invoke-virtual+super
1092 // case Instruction::k35mi: // [opt] inline invoke
Aart Bikdce50862016-06-10 16:04:03 -07001093 u4 arg[Instruction::kMaxVarArgRegs];
1094 pDecInsn->GetVarArgs(arg);
1095 fputs(" {", gOutFile);
1096 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1097 if (i == 0) {
1098 fprintf(gOutFile, "v%d", arg[i]);
1099 } else {
1100 fprintf(gOutFile, ", v%d", arg[i]);
1101 }
1102 } // for
Aart Bika0e33fd2016-07-08 18:32:45 -07001103 fprintf(gOutFile, "}, %s", indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001104 break;
Aart Bikdce50862016-06-10 16:04:03 -07001105 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001106 case Instruction::k3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB
Orion Hodsonb34bb192016-10-18 17:02:58 +01001107 case Instruction::k4rcc: { // op {vCCCC .. v(CCCC+AA-1)}, method@BBBB, proto@HHHH
Aart Bik69ae54a2015-07-01 14:52:26 -07001108 // NOT SUPPORTED:
1109 // case Instruction::k3rms: // [opt] invoke-virtual+super/range
1110 // case Instruction::k3rmi: // [opt] execute-inline/range
Aart Bik69ae54a2015-07-01 14:52:26 -07001111 // This doesn't match the "dx" output when some of the args are
1112 // 64-bit values -- dx only shows the first register.
1113 fputs(" {", gOutFile);
1114 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1115 if (i == 0) {
1116 fprintf(gOutFile, "v%d", pDecInsn->VRegC() + i);
1117 } else {
1118 fprintf(gOutFile, ", v%d", pDecInsn->VRegC() + i);
1119 }
1120 } // for
Aart Bika0e33fd2016-07-08 18:32:45 -07001121 fprintf(gOutFile, "}, %s", indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001122 }
1123 break;
Aart Bikdce50862016-06-10 16:04:03 -07001124 case Instruction::k51l: { // op vAA, #+BBBBBBBBBBBBBBBB
1125 // This is often, but not always, a double.
1126 union {
1127 double d;
1128 u8 j;
1129 } conv;
1130 conv.j = pDecInsn->WideVRegB();
1131 fprintf(gOutFile, " v%d, #double %g // #%016" PRIx64,
1132 pDecInsn->VRegA(), conv.d, pDecInsn->WideVRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001133 break;
Aart Bikdce50862016-06-10 16:04:03 -07001134 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001135 // NOT SUPPORTED:
1136 // case Instruction::k00x: // unknown op or breakpoint
1137 // break;
1138 default:
1139 fprintf(gOutFile, " ???");
1140 break;
1141 } // switch
1142
1143 fputc('\n', gOutFile);
Aart Bik69ae54a2015-07-01 14:52:26 -07001144}
1145
1146/*
1147 * Dumps a bytecode disassembly.
1148 */
1149static void dumpBytecodes(const DexFile* pDexFile, u4 idx,
1150 const DexFile::CodeItem* pCode, u4 codeOffset) {
1151 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
1152 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
1153 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
1154 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
1155
1156 // Generate header.
Aart Bikc05e2f22016-07-12 15:53:13 -07001157 std::unique_ptr<char[]> dot(descriptorToDot(backDescriptor));
1158 fprintf(gOutFile, "%06x: |[%06x] %s.%s:%s\n",
1159 codeOffset, codeOffset, dot.get(), name, signature.ToString().c_str());
Aart Bik69ae54a2015-07-01 14:52:26 -07001160
1161 // Iterate over all instructions.
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001162 CodeItemDataAccessor accessor(*pDexFile, pCode);
Aart Bik7a9aaf12018-02-05 17:00:40 -08001163 const u4 maxPc = accessor.InsnsSizeInCodeUnits();
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001164 for (const DexInstructionPcPair& pair : accessor) {
Aart Bik7a9aaf12018-02-05 17:00:40 -08001165 const u4 dexPc = pair.DexPc();
1166 if (dexPc >= maxPc) {
1167 LOG(WARNING) << "GLITCH: run-away instruction at idx=0x" << std::hex << dexPc;
1168 break;
1169 }
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001170 const Instruction* instruction = &pair.Inst();
Aart Bik69ae54a2015-07-01 14:52:26 -07001171 const u4 insnWidth = instruction->SizeInCodeUnits();
1172 if (insnWidth == 0) {
Aart Bik7a9aaf12018-02-05 17:00:40 -08001173 LOG(WARNING) << "GLITCH: zero-width instruction at idx=0x" << std::hex << dexPc;
Aart Bik69ae54a2015-07-01 14:52:26 -07001174 break;
1175 }
Aart Bik7a9aaf12018-02-05 17:00:40 -08001176 dumpInstruction(pDexFile, pCode, codeOffset, dexPc, insnWidth, instruction);
Aart Bik69ae54a2015-07-01 14:52:26 -07001177 } // for
1178}
1179
1180/*
1181 * Dumps code of a method.
1182 */
1183static void dumpCode(const DexFile* pDexFile, u4 idx, u4 flags,
1184 const DexFile::CodeItem* pCode, u4 codeOffset) {
Mathieu Chartier8892c6b2018-01-09 15:10:17 -08001185 CodeItemDebugInfoAccessor accessor(*pDexFile, pCode, idx);
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001186
1187 fprintf(gOutFile, " registers : %d\n", accessor.RegistersSize());
1188 fprintf(gOutFile, " ins : %d\n", accessor.InsSize());
1189 fprintf(gOutFile, " outs : %d\n", accessor.OutsSize());
Aart Bik69ae54a2015-07-01 14:52:26 -07001190 fprintf(gOutFile, " insns size : %d 16-bit code units\n",
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001191 accessor.InsnsSizeInCodeUnits());
Aart Bik69ae54a2015-07-01 14:52:26 -07001192
1193 // Bytecode disassembly, if requested.
1194 if (gOptions.disassemble) {
1195 dumpBytecodes(pDexFile, idx, pCode, codeOffset);
1196 }
1197
1198 // Try-catch blocks.
1199 dumpCatches(pDexFile, pCode);
1200
1201 // Positions and locals table in the debug info.
1202 bool is_static = (flags & kAccStatic) != 0;
1203 fprintf(gOutFile, " positions : \n");
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001204 pDexFile->DecodeDebugPositionInfo(accessor.DebugInfoOffset(), dumpPositionsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001205 fprintf(gOutFile, " locals : \n");
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001206 accessor.DecodeDebugLocalInfo(is_static, idx, dumpLocalsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001207}
1208
1209/*
1210 * Dumps a method.
1211 */
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001212static void dumpMethod(const ClassAccessor::Method& method, int i) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001213 // Bail for anything private if export only requested.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001214 const uint32_t flags = method.GetRawAccessFlags();
Aart Bik69ae54a2015-07-01 14:52:26 -07001215 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1216 return;
1217 }
1218
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001219 const DexFile& dex_file = method.GetDexFile();
1220 const DexFile::MethodId& pMethodId = dex_file.GetMethodId(method.GetIndex());
1221 const char* name = dex_file.StringDataByIdx(pMethodId.name_idx_);
1222 const Signature signature = dex_file.GetMethodSignature(pMethodId);
Aart Bik69ae54a2015-07-01 14:52:26 -07001223 char* typeDescriptor = strdup(signature.ToString().c_str());
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001224 const char* backDescriptor = dex_file.StringByTypeIdx(pMethodId.class_idx_);
Aart Bik69ae54a2015-07-01 14:52:26 -07001225 char* accessStr = createAccessFlagStr(flags, kAccessForMethod);
1226
1227 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1228 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1229 fprintf(gOutFile, " name : '%s'\n", name);
1230 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1231 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001232 if (method.GetCodeItem() == nullptr) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001233 fprintf(gOutFile, " code : (none)\n");
1234 } else {
1235 fprintf(gOutFile, " code -\n");
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001236 dumpCode(&dex_file,
1237 method.GetIndex(),
1238 flags,
1239 method.GetCodeItem(),
1240 method.GetCodeItemOffset());
Aart Bik69ae54a2015-07-01 14:52:26 -07001241 }
1242 if (gOptions.disassemble) {
1243 fputc('\n', gOutFile);
1244 }
1245 } else if (gOptions.outputFormat == OUTPUT_XML) {
1246 const bool constructor = (name[0] == '<');
1247
1248 // Method name and prototype.
1249 if (constructor) {
Orion Hodsonfe42d212018-08-24 14:01:14 +01001250 std::unique_ptr<char[]> dot(descriptorClassToName(backDescriptor));
Aart Bikc05e2f22016-07-12 15:53:13 -07001251 fprintf(gOutFile, "<constructor name=\"%s\"\n", dot.get());
1252 dot = descriptorToDot(backDescriptor);
1253 fprintf(gOutFile, " type=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001254 } else {
1255 fprintf(gOutFile, "<method name=\"%s\"\n", name);
1256 const char* returnType = strrchr(typeDescriptor, ')');
1257 if (returnType == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08001258 LOG(ERROR) << "bad method type descriptor '" << typeDescriptor << "'";
Aart Bik69ae54a2015-07-01 14:52:26 -07001259 goto bail;
1260 }
Aart Bikc05e2f22016-07-12 15:53:13 -07001261 std::unique_ptr<char[]> dot(descriptorToDot(returnType + 1));
1262 fprintf(gOutFile, " return=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001263 fprintf(gOutFile, " abstract=%s\n", quotedBool((flags & kAccAbstract) != 0));
1264 fprintf(gOutFile, " native=%s\n", quotedBool((flags & kAccNative) != 0));
1265 fprintf(gOutFile, " synchronized=%s\n", quotedBool(
1266 (flags & (kAccSynchronized | kAccDeclaredSynchronized)) != 0));
1267 }
1268
1269 // Additional method flags.
1270 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1271 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1272 // The "deprecated=" not knowable w/o parsing annotations.
1273 fprintf(gOutFile, " visibility=%s\n>\n", quotedVisibility(flags));
1274
1275 // Parameters.
1276 if (typeDescriptor[0] != '(') {
Andreas Gampe221d9812018-01-22 17:48:56 -08001277 LOG(ERROR) << "ERROR: bad descriptor '" << typeDescriptor << "'";
Aart Bik69ae54a2015-07-01 14:52:26 -07001278 goto bail;
1279 }
1280 char* tmpBuf = reinterpret_cast<char*>(malloc(strlen(typeDescriptor) + 1));
1281 const char* base = typeDescriptor + 1;
1282 int argNum = 0;
1283 while (*base != ')') {
1284 char* cp = tmpBuf;
1285 while (*base == '[') {
1286 *cp++ = *base++;
1287 }
1288 if (*base == 'L') {
1289 // Copy through ';'.
1290 do {
1291 *cp = *base++;
1292 } while (*cp++ != ';');
1293 } else {
1294 // Primitive char, copy it.
Aart Bikc05e2f22016-07-12 15:53:13 -07001295 if (strchr("ZBCSIFJD", *base) == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08001296 LOG(ERROR) << "ERROR: bad method signature '" << base << "'";
Aart Bika0e33fd2016-07-08 18:32:45 -07001297 break; // while
Aart Bik69ae54a2015-07-01 14:52:26 -07001298 }
1299 *cp++ = *base++;
1300 }
1301 // Null terminate and display.
1302 *cp++ = '\0';
Aart Bikc05e2f22016-07-12 15:53:13 -07001303 std::unique_ptr<char[]> dot(descriptorToDot(tmpBuf));
Aart Bik69ae54a2015-07-01 14:52:26 -07001304 fprintf(gOutFile, "<parameter name=\"arg%d\" type=\"%s\">\n"
Aart Bikc05e2f22016-07-12 15:53:13 -07001305 "</parameter>\n", argNum++, dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001306 } // while
1307 free(tmpBuf);
1308 if (constructor) {
1309 fprintf(gOutFile, "</constructor>\n");
1310 } else {
1311 fprintf(gOutFile, "</method>\n");
1312 }
1313 }
1314
1315 bail:
1316 free(typeDescriptor);
1317 free(accessStr);
1318}
1319
1320/*
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001321 * Dumps a static or instance (class) field.
Aart Bik69ae54a2015-07-01 14:52:26 -07001322 */
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001323static void dumpField(const ClassAccessor::Field& field, int i, const u1** data = nullptr) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001324 // Bail for anything private if export only requested.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001325 const uint32_t flags = field.GetRawAccessFlags();
Aart Bik69ae54a2015-07-01 14:52:26 -07001326 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1327 return;
1328 }
1329
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001330 const DexFile& dex_file = field.GetDexFile();
1331 const DexFile::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
1332 const char* name = dex_file.StringDataByIdx(field_id.name_idx_);
1333 const char* typeDescriptor = dex_file.StringByTypeIdx(field_id.type_idx_);
1334 const char* backDescriptor = dex_file.StringByTypeIdx(field_id.class_idx_);
Aart Bik69ae54a2015-07-01 14:52:26 -07001335 char* accessStr = createAccessFlagStr(flags, kAccessForField);
1336
1337 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1338 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1339 fprintf(gOutFile, " name : '%s'\n", name);
1340 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1341 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
Aart Bikdce50862016-06-10 16:04:03 -07001342 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001343 fputs(" value : ", gOutFile);
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001344 dumpEncodedValue(&dex_file, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001345 fputs("\n", gOutFile);
1346 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001347 } else if (gOptions.outputFormat == OUTPUT_XML) {
1348 fprintf(gOutFile, "<field name=\"%s\"\n", name);
Aart Bikc05e2f22016-07-12 15:53:13 -07001349 std::unique_ptr<char[]> dot(descriptorToDot(typeDescriptor));
1350 fprintf(gOutFile, " type=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001351 fprintf(gOutFile, " transient=%s\n", quotedBool((flags & kAccTransient) != 0));
1352 fprintf(gOutFile, " volatile=%s\n", quotedBool((flags & kAccVolatile) != 0));
1353 // The "value=" is not knowable w/o parsing annotations.
1354 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1355 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1356 // The "deprecated=" is not knowable w/o parsing annotations.
1357 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(flags));
Aart Bikdce50862016-06-10 16:04:03 -07001358 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001359 fputs(" value=\"", gOutFile);
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001360 dumpEncodedValue(&dex_file, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001361 fputs("\"\n", gOutFile);
1362 }
1363 fputs(">\n</field>\n", gOutFile);
Aart Bik69ae54a2015-07-01 14:52:26 -07001364 }
1365
1366 free(accessStr);
1367}
1368
1369/*
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001370 * Dumping a CFG.
Aart Bik69ae54a2015-07-01 14:52:26 -07001371 */
Andreas Gampe5073fed2015-08-10 11:40:25 -07001372static void dumpCfg(const DexFile* dex_file, int idx) {
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001373 ClassAccessor accessor(*dex_file, dex_file->GetClassDef(idx));
1374 for (const ClassAccessor::Method& method : accessor.GetMethods()) {
1375 if (method.GetCodeItem() != nullptr) {
1376 std::ostringstream oss;
1377 DumpMethodCFG(method, oss);
1378 fputs(oss.str().c_str(), gOutFile);
1379 }
Andreas Gampe5073fed2015-08-10 11:40:25 -07001380 }
Andreas Gampe5073fed2015-08-10 11:40:25 -07001381}
1382
1383/*
Aart Bik69ae54a2015-07-01 14:52:26 -07001384 * Dumps the class.
1385 *
1386 * Note "idx" is a DexClassDef index, not a DexTypeId index.
1387 *
1388 * If "*pLastPackage" is nullptr or does not match the current class' package,
1389 * the value will be replaced with a newly-allocated string.
1390 */
1391static void dumpClass(const DexFile* pDexFile, int idx, char** pLastPackage) {
1392 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
1393
1394 // Omitting non-public class.
1395 if (gOptions.exportsOnly && (pClassDef.access_flags_ & kAccPublic) == 0) {
1396 return;
1397 }
1398
Aart Bikdce50862016-06-10 16:04:03 -07001399 if (gOptions.showSectionHeaders) {
1400 dumpClassDef(pDexFile, idx);
1401 }
1402
1403 if (gOptions.showAnnotations) {
1404 dumpClassAnnotations(pDexFile, idx);
1405 }
1406
1407 if (gOptions.showCfg) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001408 dumpCfg(pDexFile, idx);
1409 return;
1410 }
1411
Aart Bik69ae54a2015-07-01 14:52:26 -07001412 // For the XML output, show the package name. Ideally we'd gather
1413 // up the classes, sort them, and dump them alphabetically so the
1414 // package name wouldn't jump around, but that's not a great plan
1415 // for something that needs to run on the device.
1416 const char* classDescriptor = pDexFile->StringByTypeIdx(pClassDef.class_idx_);
1417 if (!(classDescriptor[0] == 'L' &&
1418 classDescriptor[strlen(classDescriptor)-1] == ';')) {
1419 // Arrays and primitives should not be defined explicitly. Keep going?
Andreas Gampe221d9812018-01-22 17:48:56 -08001420 LOG(WARNING) << "Malformed class name '" << classDescriptor << "'";
Aart Bik69ae54a2015-07-01 14:52:26 -07001421 } else if (gOptions.outputFormat == OUTPUT_XML) {
1422 char* mangle = strdup(classDescriptor + 1);
1423 mangle[strlen(mangle)-1] = '\0';
1424
1425 // Reduce to just the package name.
1426 char* lastSlash = strrchr(mangle, '/');
1427 if (lastSlash != nullptr) {
1428 *lastSlash = '\0';
1429 } else {
1430 *mangle = '\0';
1431 }
1432
1433 for (char* cp = mangle; *cp != '\0'; cp++) {
1434 if (*cp == '/') {
1435 *cp = '.';
1436 }
1437 } // for
1438
1439 if (*pLastPackage == nullptr || strcmp(mangle, *pLastPackage) != 0) {
1440 // Start of a new package.
1441 if (*pLastPackage != nullptr) {
1442 fprintf(gOutFile, "</package>\n");
1443 }
1444 fprintf(gOutFile, "<package name=\"%s\"\n>\n", mangle);
1445 free(*pLastPackage);
1446 *pLastPackage = mangle;
1447 } else {
1448 free(mangle);
1449 }
1450 }
1451
1452 // General class information.
1453 char* accessStr = createAccessFlagStr(pClassDef.access_flags_, kAccessForClass);
1454 const char* superclassDescriptor;
Andreas Gampea5b09a62016-11-17 15:21:22 -08001455 if (!pClassDef.superclass_idx_.IsValid()) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001456 superclassDescriptor = nullptr;
1457 } else {
1458 superclassDescriptor = pDexFile->StringByTypeIdx(pClassDef.superclass_idx_);
1459 }
1460 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1461 fprintf(gOutFile, "Class #%d -\n", idx);
1462 fprintf(gOutFile, " Class descriptor : '%s'\n", classDescriptor);
1463 fprintf(gOutFile, " Access flags : 0x%04x (%s)\n", pClassDef.access_flags_, accessStr);
1464 if (superclassDescriptor != nullptr) {
1465 fprintf(gOutFile, " Superclass : '%s'\n", superclassDescriptor);
1466 }
1467 fprintf(gOutFile, " Interfaces -\n");
1468 } else {
Orion Hodsonfe42d212018-08-24 14:01:14 +01001469 std::unique_ptr<char[]> dot(descriptorClassToName(classDescriptor));
Aart Bikc05e2f22016-07-12 15:53:13 -07001470 fprintf(gOutFile, "<class name=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001471 if (superclassDescriptor != nullptr) {
Aart Bikc05e2f22016-07-12 15:53:13 -07001472 dot = descriptorToDot(superclassDescriptor);
1473 fprintf(gOutFile, " extends=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001474 }
Alex Light1f12e282015-12-10 16:49:47 -08001475 fprintf(gOutFile, " interface=%s\n",
1476 quotedBool((pClassDef.access_flags_ & kAccInterface) != 0));
Aart Bik69ae54a2015-07-01 14:52:26 -07001477 fprintf(gOutFile, " abstract=%s\n", quotedBool((pClassDef.access_flags_ & kAccAbstract) != 0));
1478 fprintf(gOutFile, " static=%s\n", quotedBool((pClassDef.access_flags_ & kAccStatic) != 0));
1479 fprintf(gOutFile, " final=%s\n", quotedBool((pClassDef.access_flags_ & kAccFinal) != 0));
1480 // The "deprecated=" not knowable w/o parsing annotations.
1481 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(pClassDef.access_flags_));
1482 fprintf(gOutFile, ">\n");
1483 }
1484
1485 // Interfaces.
1486 const DexFile::TypeList* pInterfaces = pDexFile->GetInterfacesList(pClassDef);
1487 if (pInterfaces != nullptr) {
1488 for (u4 i = 0; i < pInterfaces->Size(); i++) {
1489 dumpInterface(pDexFile, pInterfaces->GetTypeItem(i), i);
1490 } // for
1491 }
1492
1493 // Fields and methods.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001494 ClassAccessor accessor(*pDexFile, pClassDef);
Aart Bikdce50862016-06-10 16:04:03 -07001495
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001496 // Prepare data for static fields.
1497 const u1* sData = pDexFile->GetEncodedStaticFieldValuesArray(pClassDef);
1498 const u4 sSize = sData != nullptr ? DecodeUnsignedLeb128(&sData) : 0;
Aart Bikdce50862016-06-10 16:04:03 -07001499
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001500 // Static fields.
1501 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1502 fprintf(gOutFile, " Static fields -\n");
1503 }
1504 uint32_t i = 0u;
1505 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
1506 dumpField(field, i, i < sSize ? &sData : nullptr);
1507 ++i;
1508 }
Aart Bikdce50862016-06-10 16:04:03 -07001509
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001510 // Instance fields.
1511 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1512 fprintf(gOutFile, " Instance fields -\n");
1513 }
1514 i = 0u;
1515 for (const ClassAccessor::Field& field : accessor.GetInstanceFields()) {
1516 dumpField(field, i);
1517 ++i;
1518 }
Aart Bikdce50862016-06-10 16:04:03 -07001519
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001520 // Direct methods.
1521 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1522 fprintf(gOutFile, " Direct methods -\n");
1523 }
1524 i = 0u;
1525 for (const ClassAccessor::Method& method : accessor.GetDirectMethods()) {
1526 dumpMethod(method, i);
1527 ++i;
1528 }
Aart Bikdce50862016-06-10 16:04:03 -07001529
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001530 // Virtual methods.
1531 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1532 fprintf(gOutFile, " Virtual methods -\n");
1533 }
1534 i = 0u;
1535 for (const ClassAccessor::Method& method : accessor.GetVirtualMethods()) {
1536 dumpMethod(method, i);
1537 ++i;
Aart Bik69ae54a2015-07-01 14:52:26 -07001538 }
1539
1540 // End of class.
1541 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1542 const char* fileName;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001543 if (pClassDef.source_file_idx_.IsValid()) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001544 fileName = pDexFile->StringDataByIdx(pClassDef.source_file_idx_);
1545 } else {
1546 fileName = "unknown";
1547 }
1548 fprintf(gOutFile, " source_file_idx : %d (%s)\n\n",
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001549 pClassDef.source_file_idx_.index_, fileName);
Aart Bik69ae54a2015-07-01 14:52:26 -07001550 } else if (gOptions.outputFormat == OUTPUT_XML) {
1551 fprintf(gOutFile, "</class>\n");
1552 }
1553
1554 free(accessStr);
1555}
1556
Orion Hodsonc069a302017-01-18 09:23:12 +00001557static void dumpMethodHandle(const DexFile* pDexFile, u4 idx) {
1558 const DexFile::MethodHandleItem& mh = pDexFile->GetMethodHandle(idx);
Orion Hodson631827d2017-04-10 14:53:47 +01001559 const char* type = nullptr;
1560 bool is_instance = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001561 bool is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001562 switch (static_cast<DexFile::MethodHandleType>(mh.method_handle_type_)) {
1563 case DexFile::MethodHandleType::kStaticPut:
1564 type = "put-static";
Orion Hodson631827d2017-04-10 14:53:47 +01001565 is_instance = false;
1566 is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001567 break;
1568 case DexFile::MethodHandleType::kStaticGet:
1569 type = "get-static";
Orion Hodson631827d2017-04-10 14:53:47 +01001570 is_instance = false;
1571 is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001572 break;
1573 case DexFile::MethodHandleType::kInstancePut:
1574 type = "put-instance";
Orion Hodson631827d2017-04-10 14:53:47 +01001575 is_instance = true;
1576 is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001577 break;
1578 case DexFile::MethodHandleType::kInstanceGet:
1579 type = "get-instance";
Orion Hodson631827d2017-04-10 14:53:47 +01001580 is_instance = true;
1581 is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001582 break;
1583 case DexFile::MethodHandleType::kInvokeStatic:
1584 type = "invoke-static";
Orion Hodson631827d2017-04-10 14:53:47 +01001585 is_instance = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001586 is_invoke = true;
1587 break;
1588 case DexFile::MethodHandleType::kInvokeInstance:
1589 type = "invoke-instance";
Orion Hodson631827d2017-04-10 14:53:47 +01001590 is_instance = true;
Orion Hodsonc069a302017-01-18 09:23:12 +00001591 is_invoke = true;
1592 break;
1593 case DexFile::MethodHandleType::kInvokeConstructor:
1594 type = "invoke-constructor";
Orion Hodson631827d2017-04-10 14:53:47 +01001595 is_instance = true;
1596 is_invoke = true;
1597 break;
1598 case DexFile::MethodHandleType::kInvokeDirect:
1599 type = "invoke-direct";
1600 is_instance = true;
1601 is_invoke = true;
1602 break;
1603 case DexFile::MethodHandleType::kInvokeInterface:
1604 type = "invoke-interface";
1605 is_instance = true;
Orion Hodsonc069a302017-01-18 09:23:12 +00001606 is_invoke = true;
1607 break;
1608 }
1609
1610 const char* declaring_class;
1611 const char* member;
1612 std::string member_type;
Orion Hodson631827d2017-04-10 14:53:47 +01001613 if (type != nullptr) {
1614 if (is_invoke) {
1615 const DexFile::MethodId& method_id = pDexFile->GetMethodId(mh.field_or_method_idx_);
1616 declaring_class = pDexFile->GetMethodDeclaringClassDescriptor(method_id);
1617 member = pDexFile->GetMethodName(method_id);
1618 member_type = pDexFile->GetMethodSignature(method_id).ToString();
1619 } else {
1620 const DexFile::FieldId& field_id = pDexFile->GetFieldId(mh.field_or_method_idx_);
1621 declaring_class = pDexFile->GetFieldDeclaringClassDescriptor(field_id);
1622 member = pDexFile->GetFieldName(field_id);
1623 member_type = pDexFile->GetFieldTypeDescriptor(field_id);
1624 }
1625 if (is_instance) {
1626 member_type = android::base::StringPrintf("(%s%s", declaring_class, member_type.c_str() + 1);
1627 }
Orion Hodsonc069a302017-01-18 09:23:12 +00001628 } else {
Orion Hodson631827d2017-04-10 14:53:47 +01001629 type = "?";
1630 declaring_class = "?";
1631 member = "?";
1632 member_type = "?";
Orion Hodsonc069a302017-01-18 09:23:12 +00001633 }
1634
1635 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1636 fprintf(gOutFile, "Method handle #%u:\n", idx);
1637 fprintf(gOutFile, " type : %s\n", type);
1638 fprintf(gOutFile, " target : %s %s\n", declaring_class, member);
1639 fprintf(gOutFile, " target_type : %s\n", member_type.c_str());
1640 } else {
1641 fprintf(gOutFile, "<method_handle index=\"%u\"\n", idx);
1642 fprintf(gOutFile, " type=\"%s\"\n", type);
1643 fprintf(gOutFile, " target_class=\"%s\"\n", declaring_class);
1644 fprintf(gOutFile, " target_member=\"%s\"\n", member);
1645 fprintf(gOutFile, " target_member_type=");
1646 dumpEscapedString(member_type.c_str());
1647 fprintf(gOutFile, "\n>\n</method_handle>\n");
1648 }
1649}
1650
1651static void dumpCallSite(const DexFile* pDexFile, u4 idx) {
1652 const DexFile::CallSiteIdItem& call_site_id = pDexFile->GetCallSiteId(idx);
1653 CallSiteArrayValueIterator it(*pDexFile, call_site_id);
1654 if (it.Size() < 3) {
Andreas Gampe221d9812018-01-22 17:48:56 -08001655 LOG(ERROR) << "ERROR: Call site " << idx << " has too few values.";
Orion Hodsonc069a302017-01-18 09:23:12 +00001656 return;
1657 }
1658
1659 uint32_t method_handle_idx = static_cast<uint32_t>(it.GetJavaValue().i);
1660 it.Next();
1661 dex::StringIndex method_name_idx = static_cast<dex::StringIndex>(it.GetJavaValue().i);
1662 const char* method_name = pDexFile->StringDataByIdx(method_name_idx);
1663 it.Next();
Orion Hodson06d10a72018-05-14 08:53:38 +01001664 dex::ProtoIndex method_type_idx = static_cast<dex::ProtoIndex>(it.GetJavaValue().i);
Orion Hodsonc069a302017-01-18 09:23:12 +00001665 const DexFile::ProtoId& method_type_id = pDexFile->GetProtoId(method_type_idx);
1666 std::string method_type = pDexFile->GetProtoSignature(method_type_id).ToString();
1667 it.Next();
1668
1669 if (gOptions.outputFormat == OUTPUT_PLAIN) {
Orion Hodson775224d2017-07-05 11:04:01 +01001670 fprintf(gOutFile, "Call site #%u: // offset %u\n", idx, call_site_id.data_off_);
Orion Hodsonc069a302017-01-18 09:23:12 +00001671 fprintf(gOutFile, " link_argument[0] : %u (MethodHandle)\n", method_handle_idx);
1672 fprintf(gOutFile, " link_argument[1] : %s (String)\n", method_name);
1673 fprintf(gOutFile, " link_argument[2] : %s (MethodType)\n", method_type.c_str());
1674 } else {
Orion Hodson775224d2017-07-05 11:04:01 +01001675 fprintf(gOutFile, "<call_site index=\"%u\" offset=\"%u\">\n", idx, call_site_id.data_off_);
Orion Hodsonc069a302017-01-18 09:23:12 +00001676 fprintf(gOutFile,
1677 "<link_argument index=\"0\" type=\"MethodHandle\" value=\"%u\"/>\n",
1678 method_handle_idx);
1679 fprintf(gOutFile,
1680 "<link_argument index=\"1\" type=\"String\" values=\"%s\"/>\n",
1681 method_name);
1682 fprintf(gOutFile,
1683 "<link_argument index=\"2\" type=\"MethodType\" value=\"%s\"/>\n",
1684 method_type.c_str());
1685 }
1686
1687 size_t argument = 3;
1688 while (it.HasNext()) {
1689 const char* type;
1690 std::string value;
1691 switch (it.GetValueType()) {
1692 case EncodedArrayValueIterator::ValueType::kByte:
1693 type = "byte";
1694 value = android::base::StringPrintf("%u", it.GetJavaValue().b);
1695 break;
1696 case EncodedArrayValueIterator::ValueType::kShort:
1697 type = "short";
1698 value = android::base::StringPrintf("%d", it.GetJavaValue().s);
1699 break;
1700 case EncodedArrayValueIterator::ValueType::kChar:
1701 type = "char";
1702 value = android::base::StringPrintf("%u", it.GetJavaValue().c);
1703 break;
1704 case EncodedArrayValueIterator::ValueType::kInt:
1705 type = "int";
1706 value = android::base::StringPrintf("%d", it.GetJavaValue().i);
1707 break;
1708 case EncodedArrayValueIterator::ValueType::kLong:
1709 type = "long";
1710 value = android::base::StringPrintf("%" PRId64, it.GetJavaValue().j);
1711 break;
1712 case EncodedArrayValueIterator::ValueType::kFloat:
1713 type = "float";
1714 value = android::base::StringPrintf("%g", it.GetJavaValue().f);
1715 break;
1716 case EncodedArrayValueIterator::ValueType::kDouble:
1717 type = "double";
1718 value = android::base::StringPrintf("%g", it.GetJavaValue().d);
1719 break;
1720 case EncodedArrayValueIterator::ValueType::kMethodType: {
1721 type = "MethodType";
Orion Hodson06d10a72018-05-14 08:53:38 +01001722 dex::ProtoIndex proto_idx = static_cast<dex::ProtoIndex>(it.GetJavaValue().i);
Orion Hodsonc069a302017-01-18 09:23:12 +00001723 const DexFile::ProtoId& proto_id = pDexFile->GetProtoId(proto_idx);
1724 value = pDexFile->GetProtoSignature(proto_id).ToString();
1725 break;
1726 }
1727 case EncodedArrayValueIterator::ValueType::kMethodHandle:
1728 type = "MethodHandle";
1729 value = android::base::StringPrintf("%d", it.GetJavaValue().i);
1730 break;
1731 case EncodedArrayValueIterator::ValueType::kString: {
1732 type = "String";
1733 dex::StringIndex string_idx = static_cast<dex::StringIndex>(it.GetJavaValue().i);
1734 value = pDexFile->StringDataByIdx(string_idx);
1735 break;
1736 }
1737 case EncodedArrayValueIterator::ValueType::kType: {
1738 type = "Class";
1739 dex::TypeIndex type_idx = static_cast<dex::TypeIndex>(it.GetJavaValue().i);
Orion Hodson0f6cc7f2018-05-25 15:33:44 +01001740 const DexFile::TypeId& type_id = pDexFile->GetTypeId(type_idx);
1741 value = pDexFile->GetTypeDescriptor(type_id);
Orion Hodsonc069a302017-01-18 09:23:12 +00001742 break;
1743 }
1744 case EncodedArrayValueIterator::ValueType::kField:
1745 case EncodedArrayValueIterator::ValueType::kMethod:
1746 case EncodedArrayValueIterator::ValueType::kEnum:
1747 case EncodedArrayValueIterator::ValueType::kArray:
1748 case EncodedArrayValueIterator::ValueType::kAnnotation:
1749 // Unreachable based on current EncodedArrayValueIterator::Next().
Andreas Gampef45d61c2017-06-07 10:29:33 -07001750 UNIMPLEMENTED(FATAL) << " type " << it.GetValueType();
Orion Hodsonc069a302017-01-18 09:23:12 +00001751 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00001752 case EncodedArrayValueIterator::ValueType::kNull:
1753 type = "Null";
1754 value = "null";
1755 break;
1756 case EncodedArrayValueIterator::ValueType::kBoolean:
1757 type = "boolean";
1758 value = it.GetJavaValue().z ? "true" : "false";
1759 break;
1760 }
1761
1762 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1763 fprintf(gOutFile, " link_argument[%zu] : %s (%s)\n", argument, value.c_str(), type);
1764 } else {
1765 fprintf(gOutFile, "<link_argument index=\"%zu\" type=\"%s\" value=", argument, type);
1766 dumpEscapedString(value.c_str());
1767 fprintf(gOutFile, "/>\n");
1768 }
1769
1770 it.Next();
1771 argument++;
1772 }
1773
1774 if (gOptions.outputFormat == OUTPUT_XML) {
1775 fprintf(gOutFile, "</call_site>\n");
1776 }
1777}
1778
Aart Bik69ae54a2015-07-01 14:52:26 -07001779/*
1780 * Dumps the requested sections of the file.
1781 */
Aart Bik7b45a8a2016-10-24 16:07:59 -07001782static void processDexFile(const char* fileName,
1783 const DexFile* pDexFile, size_t i, size_t n) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001784 if (gOptions.verbose) {
Aart Bik7b45a8a2016-10-24 16:07:59 -07001785 fputs("Opened '", gOutFile);
1786 fputs(fileName, gOutFile);
1787 if (n > 1) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001788 fprintf(gOutFile, ":%s", DexFileLoader::GetMultiDexClassesDexName(i).c_str());
Aart Bik7b45a8a2016-10-24 16:07:59 -07001789 }
1790 fprintf(gOutFile, "', DEX version '%.3s'\n", pDexFile->GetHeader().magic_ + 4);
Aart Bik69ae54a2015-07-01 14:52:26 -07001791 }
1792
1793 // Headers.
1794 if (gOptions.showFileHeaders) {
1795 dumpFileHeader(pDexFile);
1796 }
1797
1798 // Open XML context.
1799 if (gOptions.outputFormat == OUTPUT_XML) {
1800 fprintf(gOutFile, "<api>\n");
1801 }
1802
1803 // Iterate over all classes.
1804 char* package = nullptr;
1805 const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
1806 for (u4 i = 0; i < classDefsSize; i++) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001807 dumpClass(pDexFile, i, &package);
1808 } // for
1809
Orion Hodsonc069a302017-01-18 09:23:12 +00001810 // Iterate over all method handles.
1811 for (u4 i = 0; i < pDexFile->NumMethodHandles(); ++i) {
1812 dumpMethodHandle(pDexFile, i);
1813 } // for
1814
1815 // Iterate over all call site ids.
1816 for (u4 i = 0; i < pDexFile->NumCallSiteIds(); ++i) {
1817 dumpCallSite(pDexFile, i);
1818 } // for
1819
Aart Bik69ae54a2015-07-01 14:52:26 -07001820 // Free the last package allocated.
1821 if (package != nullptr) {
1822 fprintf(gOutFile, "</package>\n");
1823 free(package);
1824 }
1825
1826 // Close XML context.
1827 if (gOptions.outputFormat == OUTPUT_XML) {
1828 fprintf(gOutFile, "</api>\n");
1829 }
1830}
1831
1832/*
1833 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
1834 */
1835int processFile(const char* fileName) {
1836 if (gOptions.verbose) {
1837 fprintf(gOutFile, "Processing '%s'...\n", fileName);
1838 }
1839
Nicolas Geoffrayc1d8caa2018-02-27 10:15:14 +00001840 const bool kVerifyChecksum = !gOptions.ignoreBadChecksum;
1841 const bool kVerify = !gOptions.disableVerifier;
1842 std::string content;
Aart Bik69ae54a2015-07-01 14:52:26 -07001843 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
Aart Bikdce50862016-06-10 16:04:03 -07001844 // all of which are Zip archives with "classes.dex" inside.
David Sehr999646d2018-02-16 10:22:33 -08001845 // TODO: add an api to android::base to read a std::vector<uint8_t>.
1846 if (!android::base::ReadFileToString(fileName, &content)) {
1847 LOG(ERROR) << "ReadFileToString failed";
David Sehr5a1f6292018-01-19 11:08:51 -08001848 return -1;
1849 }
1850 const DexFileLoader dex_file_loader;
Dario Frenie166fac2018-07-16 11:08:03 +01001851 DexFileLoaderErrorCode error_code;
David Sehr999646d2018-02-16 10:22:33 -08001852 std::string error_msg;
Aart Bik69ae54a2015-07-01 14:52:26 -07001853 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr999646d2018-02-16 10:22:33 -08001854 if (!dex_file_loader.OpenAll(reinterpret_cast<const uint8_t*>(content.data()),
1855 content.size(),
1856 fileName,
Nicolas Geoffrayc1d8caa2018-02-27 10:15:14 +00001857 kVerify,
David Sehr999646d2018-02-16 10:22:33 -08001858 kVerifyChecksum,
Dario Frenie166fac2018-07-16 11:08:03 +01001859 &error_code,
David Sehr999646d2018-02-16 10:22:33 -08001860 &error_msg,
1861 &dex_files)) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001862 // Display returned error message to user. Note that this error behavior
1863 // differs from the error messages shown by the original Dalvik dexdump.
Andreas Gampe221d9812018-01-22 17:48:56 -08001864 LOG(ERROR) << error_msg;
Aart Bik69ae54a2015-07-01 14:52:26 -07001865 return -1;
1866 }
1867
Aart Bik4e149602015-07-09 11:45:28 -07001868 // Success. Either report checksum verification or process
1869 // all dex files found in given file.
Aart Bik69ae54a2015-07-01 14:52:26 -07001870 if (gOptions.checksumOnly) {
1871 fprintf(gOutFile, "Checksum verified\n");
1872 } else {
Aart Bik7b45a8a2016-10-24 16:07:59 -07001873 for (size_t i = 0, n = dex_files.size(); i < n; i++) {
1874 processDexFile(fileName, dex_files[i].get(), i, n);
Aart Bik4e149602015-07-09 11:45:28 -07001875 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001876 }
1877 return 0;
1878}
1879
1880} // namespace art