blob: e72d49e05f1865208bc5db26fbcbe204c416484d [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
David Sehr0225f8e2018-01-31 08:52:24 +000048#include "dex/code_item_accessors-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080049#include "dex/dex_file-inl.h"
50#include "dex/dex_file_exception_helpers.h"
51#include "dex/dex_file_loader.h"
52#include "dex/dex_file_types.h"
53#include "dex/dex_instruction-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070054#include "dexdump_cfg.h"
Aart Bik69ae54a2015-07-01 14:52:26 -070055
56namespace art {
57
58/*
59 * Options parsed in main driver.
60 */
61struct Options gOptions;
62
63/*
Aart Bik4e149602015-07-09 11:45:28 -070064 * Output file. Defaults to stdout.
Aart Bik69ae54a2015-07-01 14:52:26 -070065 */
66FILE* gOutFile = stdout;
67
68/*
69 * Data types that match the definitions in the VM specification.
70 */
71typedef uint8_t u1;
72typedef uint16_t u2;
73typedef uint32_t u4;
74typedef uint64_t u8;
Aart Bikdce50862016-06-10 16:04:03 -070075typedef int8_t s1;
76typedef int16_t s2;
Aart Bik69ae54a2015-07-01 14:52:26 -070077typedef int32_t s4;
78typedef int64_t s8;
79
80/*
81 * Basic information about a field or a method.
82 */
83struct FieldMethodInfo {
84 const char* classDescriptor;
85 const char* name;
86 const char* signature;
87};
88
89/*
90 * Flags for use with createAccessFlagStr().
91 */
92enum AccessFor {
93 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
94};
95const int kNumFlags = 18;
96
97/*
98 * Gets 2 little-endian bytes.
99 */
100static inline u2 get2LE(unsigned char const* pSrc) {
101 return pSrc[0] | (pSrc[1] << 8);
102}
103
104/*
105 * Converts a single-character primitive type into human-readable form.
106 */
107static const char* primitiveTypeLabel(char typeChar) {
108 switch (typeChar) {
109 case 'B': return "byte";
110 case 'C': return "char";
111 case 'D': return "double";
112 case 'F': return "float";
113 case 'I': return "int";
114 case 'J': return "long";
115 case 'S': return "short";
116 case 'V': return "void";
117 case 'Z': return "boolean";
118 default: return "UNKNOWN";
119 } // switch
120}
121
122/*
123 * Converts a type descriptor to human-readable "dotted" form. For
124 * example, "Ljava/lang/String;" becomes "java.lang.String", and
125 * "[I" becomes "int[]". Also converts '$' to '.', which means this
126 * form can't be converted back to a descriptor.
127 */
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];
159 newStr[i] = (ch == '/' || ch == '$') ? '.' : ch;
160 } // 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/*
173 * Converts the class name portion of a type descriptor to human-readable
Aart Bikc05e2f22016-07-12 15:53:13 -0700174 * "dotted" form. For example, "Ljava/lang/String;" becomes "String".
Aart Bik69ae54a2015-07-01 14:52:26 -0700175 */
Aart Bikc05e2f22016-07-12 15:53:13 -0700176static std::unique_ptr<char[]> descriptorClassToDot(const char* str) {
177 // Reduce to just the class name prefix.
Aart Bik69ae54a2015-07-01 14:52:26 -0700178 const char* lastSlash = strrchr(str, '/');
179 if (lastSlash == nullptr) {
180 lastSlash = str + 1; // start past 'L'
181 } else {
182 lastSlash++; // start past '/'
183 }
184
Aart Bikc05e2f22016-07-12 15:53:13 -0700185 // Copy class name over, trimming trailing ';'.
186 const int targetLen = strlen(lastSlash);
187 std::unique_ptr<char[]> newStr(new char[targetLen]);
188 for (int i = 0; i < targetLen - 1; i++) {
189 const char ch = lastSlash[i];
190 newStr[i] = ch == '$' ? '.' : ch;
Aart Bik69ae54a2015-07-01 14:52:26 -0700191 } // for
Aart Bikc05e2f22016-07-12 15:53:13 -0700192 newStr[targetLen - 1] = '\0';
Aart Bik69ae54a2015-07-01 14:52:26 -0700193 return newStr;
194}
195
196/*
Aart Bikdce50862016-06-10 16:04:03 -0700197 * Returns string representing the boolean value.
198 */
199static const char* strBool(bool val) {
200 return val ? "true" : "false";
201}
202
203/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700204 * Returns a quoted string representing the boolean value.
205 */
206static const char* quotedBool(bool val) {
207 return val ? "\"true\"" : "\"false\"";
208}
209
210/*
211 * Returns a quoted string representing the access flags.
212 */
213static const char* quotedVisibility(u4 accessFlags) {
214 if (accessFlags & kAccPublic) {
215 return "\"public\"";
216 } else if (accessFlags & kAccProtected) {
217 return "\"protected\"";
218 } else if (accessFlags & kAccPrivate) {
219 return "\"private\"";
220 } else {
221 return "\"package\"";
222 }
223}
224
225/*
226 * Counts the number of '1' bits in a word.
227 */
228static int countOnes(u4 val) {
229 val = val - ((val >> 1) & 0x55555555);
230 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
231 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
232}
233
234/*
235 * Creates a new string with human-readable access flags.
236 *
237 * In the base language the access_flags fields are type u2; in Dalvik
238 * they're u4.
239 */
240static char* createAccessFlagStr(u4 flags, AccessFor forWhat) {
241 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
242 {
243 "PUBLIC", /* 0x00001 */
244 "PRIVATE", /* 0x00002 */
245 "PROTECTED", /* 0x00004 */
246 "STATIC", /* 0x00008 */
247 "FINAL", /* 0x00010 */
248 "?", /* 0x00020 */
249 "?", /* 0x00040 */
250 "?", /* 0x00080 */
251 "?", /* 0x00100 */
252 "INTERFACE", /* 0x00200 */
253 "ABSTRACT", /* 0x00400 */
254 "?", /* 0x00800 */
255 "SYNTHETIC", /* 0x01000 */
256 "ANNOTATION", /* 0x02000 */
257 "ENUM", /* 0x04000 */
258 "?", /* 0x08000 */
259 "VERIFIED", /* 0x10000 */
260 "OPTIMIZED", /* 0x20000 */
261 }, {
262 "PUBLIC", /* 0x00001 */
263 "PRIVATE", /* 0x00002 */
264 "PROTECTED", /* 0x00004 */
265 "STATIC", /* 0x00008 */
266 "FINAL", /* 0x00010 */
267 "SYNCHRONIZED", /* 0x00020 */
268 "BRIDGE", /* 0x00040 */
269 "VARARGS", /* 0x00080 */
270 "NATIVE", /* 0x00100 */
271 "?", /* 0x00200 */
272 "ABSTRACT", /* 0x00400 */
273 "STRICT", /* 0x00800 */
274 "SYNTHETIC", /* 0x01000 */
275 "?", /* 0x02000 */
276 "?", /* 0x04000 */
277 "MIRANDA", /* 0x08000 */
278 "CONSTRUCTOR", /* 0x10000 */
279 "DECLARED_SYNCHRONIZED", /* 0x20000 */
280 }, {
281 "PUBLIC", /* 0x00001 */
282 "PRIVATE", /* 0x00002 */
283 "PROTECTED", /* 0x00004 */
284 "STATIC", /* 0x00008 */
285 "FINAL", /* 0x00010 */
286 "?", /* 0x00020 */
287 "VOLATILE", /* 0x00040 */
288 "TRANSIENT", /* 0x00080 */
289 "?", /* 0x00100 */
290 "?", /* 0x00200 */
291 "?", /* 0x00400 */
292 "?", /* 0x00800 */
293 "SYNTHETIC", /* 0x01000 */
294 "?", /* 0x02000 */
295 "ENUM", /* 0x04000 */
296 "?", /* 0x08000 */
297 "?", /* 0x10000 */
298 "?", /* 0x20000 */
299 },
300 };
301
302 // Allocate enough storage to hold the expected number of strings,
303 // plus a space between each. We over-allocate, using the longest
304 // string above as the base metric.
305 const int kLongest = 21; // The strlen of longest string above.
306 const int count = countOnes(flags);
307 char* str;
308 char* cp;
309 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
310
311 for (int i = 0; i < kNumFlags; i++) {
312 if (flags & 0x01) {
313 const char* accessStr = kAccessStrings[forWhat][i];
314 const int len = strlen(accessStr);
315 if (cp != str) {
316 *cp++ = ' ';
317 }
318 memcpy(cp, accessStr, len);
319 cp += len;
320 }
321 flags >>= 1;
322 } // for
323
324 *cp = '\0';
325 return str;
326}
327
328/*
329 * Copies character data from "data" to "out", converting non-ASCII values
330 * to fprintf format chars or an ASCII filler ('.' or '?').
331 *
332 * The output buffer must be able to hold (2*len)+1 bytes. The result is
333 * NULL-terminated.
334 */
335static void asciify(char* out, const unsigned char* data, size_t len) {
336 while (len--) {
337 if (*data < 0x20) {
338 // Could do more here, but we don't need them yet.
339 switch (*data) {
340 case '\0':
341 *out++ = '\\';
342 *out++ = '0';
343 break;
344 case '\n':
345 *out++ = '\\';
346 *out++ = 'n';
347 break;
348 default:
349 *out++ = '.';
350 break;
351 } // switch
352 } else if (*data >= 0x80) {
353 *out++ = '?';
354 } else {
355 *out++ = *data;
356 }
357 data++;
358 } // while
359 *out = '\0';
360}
361
362/*
Aart Bikdce50862016-06-10 16:04:03 -0700363 * Dumps a string value with some escape characters.
364 */
365static void dumpEscapedString(const char* p) {
366 fputs("\"", gOutFile);
367 for (; *p; p++) {
368 switch (*p) {
369 case '\\':
370 fputs("\\\\", gOutFile);
371 break;
372 case '\"':
373 fputs("\\\"", gOutFile);
374 break;
375 case '\t':
376 fputs("\\t", gOutFile);
377 break;
378 case '\n':
379 fputs("\\n", gOutFile);
380 break;
381 case '\r':
382 fputs("\\r", gOutFile);
383 break;
384 default:
385 putc(*p, gOutFile);
386 } // switch
387 } // for
388 fputs("\"", gOutFile);
389}
390
391/*
392 * Dumps a string as an XML attribute value.
393 */
394static void dumpXmlAttribute(const char* p) {
395 for (; *p; p++) {
396 switch (*p) {
397 case '&':
398 fputs("&amp;", gOutFile);
399 break;
400 case '<':
401 fputs("&lt;", gOutFile);
402 break;
403 case '>':
404 fputs("&gt;", gOutFile);
405 break;
406 case '"':
407 fputs("&quot;", gOutFile);
408 break;
409 case '\t':
410 fputs("&#x9;", gOutFile);
411 break;
412 case '\n':
413 fputs("&#xA;", gOutFile);
414 break;
415 case '\r':
416 fputs("&#xD;", gOutFile);
417 break;
418 default:
419 putc(*p, gOutFile);
420 } // switch
421 } // for
422}
423
424/*
425 * Reads variable width value, possibly sign extended at the last defined byte.
426 */
427static u8 readVarWidth(const u1** data, u1 arg, bool sign_extend) {
428 u8 value = 0;
429 for (u4 i = 0; i <= arg; i++) {
430 value |= static_cast<u8>(*(*data)++) << (i * 8);
431 }
432 if (sign_extend) {
433 int shift = (7 - arg) * 8;
434 return (static_cast<s8>(value) << shift) >> shift;
435 }
436 return value;
437}
438
439/*
440 * Dumps encoded value.
441 */
442static void dumpEncodedValue(const DexFile* pDexFile, const u1** data); // forward
443static void dumpEncodedValue(const DexFile* pDexFile, const u1** data, u1 type, u1 arg) {
444 switch (type) {
445 case DexFile::kDexAnnotationByte:
446 fprintf(gOutFile, "%" PRId8, static_cast<s1>(readVarWidth(data, arg, false)));
447 break;
448 case DexFile::kDexAnnotationShort:
449 fprintf(gOutFile, "%" PRId16, static_cast<s2>(readVarWidth(data, arg, true)));
450 break;
451 case DexFile::kDexAnnotationChar:
452 fprintf(gOutFile, "%" PRIu16, static_cast<u2>(readVarWidth(data, arg, false)));
453 break;
454 case DexFile::kDexAnnotationInt:
455 fprintf(gOutFile, "%" PRId32, static_cast<s4>(readVarWidth(data, arg, true)));
456 break;
457 case DexFile::kDexAnnotationLong:
458 fprintf(gOutFile, "%" PRId64, static_cast<s8>(readVarWidth(data, arg, true)));
459 break;
460 case DexFile::kDexAnnotationFloat: {
461 // Fill on right.
462 union {
463 float f;
464 u4 data;
465 } conv;
466 conv.data = static_cast<u4>(readVarWidth(data, arg, false)) << (3 - arg) * 8;
467 fprintf(gOutFile, "%g", conv.f);
468 break;
469 }
470 case DexFile::kDexAnnotationDouble: {
471 // Fill on right.
472 union {
473 double d;
474 u8 data;
475 } conv;
476 conv.data = readVarWidth(data, arg, false) << (7 - arg) * 8;
477 fprintf(gOutFile, "%g", conv.d);
478 break;
479 }
480 case DexFile::kDexAnnotationString: {
481 const u4 idx = static_cast<u4>(readVarWidth(data, arg, false));
482 if (gOptions.outputFormat == OUTPUT_PLAIN) {
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800483 dumpEscapedString(pDexFile->StringDataByIdx(dex::StringIndex(idx)));
Aart Bikdce50862016-06-10 16:04:03 -0700484 } else {
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800485 dumpXmlAttribute(pDexFile->StringDataByIdx(dex::StringIndex(idx)));
Aart Bikdce50862016-06-10 16:04:03 -0700486 }
487 break;
488 }
489 case DexFile::kDexAnnotationType: {
490 const u4 str_idx = static_cast<u4>(readVarWidth(data, arg, false));
Andreas Gampea5b09a62016-11-17 15:21:22 -0800491 fputs(pDexFile->StringByTypeIdx(dex::TypeIndex(str_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700492 break;
493 }
494 case DexFile::kDexAnnotationField:
495 case DexFile::kDexAnnotationEnum: {
496 const u4 field_idx = static_cast<u4>(readVarWidth(data, arg, false));
497 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
498 fputs(pDexFile->StringDataByIdx(pFieldId.name_idx_), gOutFile);
499 break;
500 }
501 case DexFile::kDexAnnotationMethod: {
502 const u4 method_idx = static_cast<u4>(readVarWidth(data, arg, false));
503 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
504 fputs(pDexFile->StringDataByIdx(pMethodId.name_idx_), gOutFile);
505 break;
506 }
507 case DexFile::kDexAnnotationArray: {
508 fputc('{', gOutFile);
509 // Decode and display all elements.
510 const u4 size = DecodeUnsignedLeb128(data);
511 for (u4 i = 0; i < size; i++) {
512 fputc(' ', gOutFile);
513 dumpEncodedValue(pDexFile, data);
514 }
515 fputs(" }", gOutFile);
516 break;
517 }
518 case DexFile::kDexAnnotationAnnotation: {
519 const u4 type_idx = DecodeUnsignedLeb128(data);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800520 fputs(pDexFile->StringByTypeIdx(dex::TypeIndex(type_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700521 // Decode and display all name=value pairs.
522 const u4 size = DecodeUnsignedLeb128(data);
523 for (u4 i = 0; i < size; i++) {
524 const u4 name_idx = DecodeUnsignedLeb128(data);
525 fputc(' ', gOutFile);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800526 fputs(pDexFile->StringDataByIdx(dex::StringIndex(name_idx)), gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -0700527 fputc('=', gOutFile);
528 dumpEncodedValue(pDexFile, data);
529 }
530 break;
531 }
532 case DexFile::kDexAnnotationNull:
533 fputs("null", gOutFile);
534 break;
535 case DexFile::kDexAnnotationBoolean:
536 fputs(strBool(arg), gOutFile);
537 break;
538 default:
539 fputs("????", gOutFile);
540 break;
541 } // switch
542}
543
544/*
545 * Dumps encoded value with prefix.
546 */
547static void dumpEncodedValue(const DexFile* pDexFile, const u1** data) {
548 const u1 enc = *(*data)++;
549 dumpEncodedValue(pDexFile, data, enc & 0x1f, enc >> 5);
550}
551
552/*
Aart Bik69ae54a2015-07-01 14:52:26 -0700553 * Dumps the file header.
Aart Bik69ae54a2015-07-01 14:52:26 -0700554 */
555static void dumpFileHeader(const DexFile* pDexFile) {
556 const DexFile::Header& pHeader = pDexFile->GetHeader();
557 char sanitized[sizeof(pHeader.magic_) * 2 + 1];
558 fprintf(gOutFile, "DEX file header:\n");
559 asciify(sanitized, pHeader.magic_, sizeof(pHeader.magic_));
560 fprintf(gOutFile, "magic : '%s'\n", sanitized);
561 fprintf(gOutFile, "checksum : %08x\n", pHeader.checksum_);
562 fprintf(gOutFile, "signature : %02x%02x...%02x%02x\n",
563 pHeader.signature_[0], pHeader.signature_[1],
564 pHeader.signature_[DexFile::kSha1DigestSize - 2],
565 pHeader.signature_[DexFile::kSha1DigestSize - 1]);
566 fprintf(gOutFile, "file_size : %d\n", pHeader.file_size_);
567 fprintf(gOutFile, "header_size : %d\n", pHeader.header_size_);
568 fprintf(gOutFile, "link_size : %d\n", pHeader.link_size_);
569 fprintf(gOutFile, "link_off : %d (0x%06x)\n",
570 pHeader.link_off_, pHeader.link_off_);
571 fprintf(gOutFile, "string_ids_size : %d\n", pHeader.string_ids_size_);
572 fprintf(gOutFile, "string_ids_off : %d (0x%06x)\n",
573 pHeader.string_ids_off_, pHeader.string_ids_off_);
574 fprintf(gOutFile, "type_ids_size : %d\n", pHeader.type_ids_size_);
575 fprintf(gOutFile, "type_ids_off : %d (0x%06x)\n",
576 pHeader.type_ids_off_, pHeader.type_ids_off_);
Aart Bikdce50862016-06-10 16:04:03 -0700577 fprintf(gOutFile, "proto_ids_size : %d\n", pHeader.proto_ids_size_);
578 fprintf(gOutFile, "proto_ids_off : %d (0x%06x)\n",
Aart Bik69ae54a2015-07-01 14:52:26 -0700579 pHeader.proto_ids_off_, pHeader.proto_ids_off_);
580 fprintf(gOutFile, "field_ids_size : %d\n", pHeader.field_ids_size_);
581 fprintf(gOutFile, "field_ids_off : %d (0x%06x)\n",
582 pHeader.field_ids_off_, pHeader.field_ids_off_);
583 fprintf(gOutFile, "method_ids_size : %d\n", pHeader.method_ids_size_);
584 fprintf(gOutFile, "method_ids_off : %d (0x%06x)\n",
585 pHeader.method_ids_off_, pHeader.method_ids_off_);
586 fprintf(gOutFile, "class_defs_size : %d\n", pHeader.class_defs_size_);
587 fprintf(gOutFile, "class_defs_off : %d (0x%06x)\n",
588 pHeader.class_defs_off_, pHeader.class_defs_off_);
589 fprintf(gOutFile, "data_size : %d\n", pHeader.data_size_);
590 fprintf(gOutFile, "data_off : %d (0x%06x)\n\n",
591 pHeader.data_off_, pHeader.data_off_);
592}
593
594/*
595 * Dumps a class_def_item.
596 */
597static void dumpClassDef(const DexFile* pDexFile, int idx) {
598 // General class information.
599 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
600 fprintf(gOutFile, "Class #%d header:\n", idx);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800601 fprintf(gOutFile, "class_idx : %d\n", pClassDef.class_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700602 fprintf(gOutFile, "access_flags : %d (0x%04x)\n",
603 pClassDef.access_flags_, pClassDef.access_flags_);
Andreas Gampea5b09a62016-11-17 15:21:22 -0800604 fprintf(gOutFile, "superclass_idx : %d\n", pClassDef.superclass_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700605 fprintf(gOutFile, "interfaces_off : %d (0x%06x)\n",
606 pClassDef.interfaces_off_, pClassDef.interfaces_off_);
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800607 fprintf(gOutFile, "source_file_idx : %d\n", pClassDef.source_file_idx_.index_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700608 fprintf(gOutFile, "annotations_off : %d (0x%06x)\n",
609 pClassDef.annotations_off_, pClassDef.annotations_off_);
610 fprintf(gOutFile, "class_data_off : %d (0x%06x)\n",
611 pClassDef.class_data_off_, pClassDef.class_data_off_);
612
613 // Fields and methods.
614 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
615 if (pEncodedData != nullptr) {
616 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
617 fprintf(gOutFile, "static_fields_size : %d\n", pClassData.NumStaticFields());
618 fprintf(gOutFile, "instance_fields_size: %d\n", pClassData.NumInstanceFields());
619 fprintf(gOutFile, "direct_methods_size : %d\n", pClassData.NumDirectMethods());
620 fprintf(gOutFile, "virtual_methods_size: %d\n", pClassData.NumVirtualMethods());
621 } else {
622 fprintf(gOutFile, "static_fields_size : 0\n");
623 fprintf(gOutFile, "instance_fields_size: 0\n");
624 fprintf(gOutFile, "direct_methods_size : 0\n");
625 fprintf(gOutFile, "virtual_methods_size: 0\n");
626 }
627 fprintf(gOutFile, "\n");
628}
629
Aart Bikdce50862016-06-10 16:04:03 -0700630/**
631 * Dumps an annotation set item.
632 */
633static void dumpAnnotationSetItem(const DexFile* pDexFile, const DexFile::AnnotationSetItem* set_item) {
634 if (set_item == nullptr || set_item->size_ == 0) {
635 fputs(" empty-annotation-set\n", gOutFile);
636 return;
637 }
638 for (u4 i = 0; i < set_item->size_; i++) {
639 const DexFile::AnnotationItem* annotation = pDexFile->GetAnnotationItem(set_item, i);
640 if (annotation == nullptr) {
641 continue;
642 }
643 fputs(" ", gOutFile);
644 switch (annotation->visibility_) {
645 case DexFile::kDexVisibilityBuild: fputs("VISIBILITY_BUILD ", gOutFile); break;
646 case DexFile::kDexVisibilityRuntime: fputs("VISIBILITY_RUNTIME ", gOutFile); break;
647 case DexFile::kDexVisibilitySystem: fputs("VISIBILITY_SYSTEM ", gOutFile); break;
648 default: fputs("VISIBILITY_UNKNOWN ", gOutFile); break;
649 } // switch
650 // Decode raw bytes in annotation.
651 const u1* rData = annotation->annotation_;
652 dumpEncodedValue(pDexFile, &rData, DexFile::kDexAnnotationAnnotation, 0);
653 fputc('\n', gOutFile);
654 }
655}
656
657/*
658 * Dumps class annotations.
659 */
660static void dumpClassAnnotations(const DexFile* pDexFile, int idx) {
661 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
662 const DexFile::AnnotationsDirectoryItem* dir = pDexFile->GetAnnotationsDirectory(pClassDef);
663 if (dir == nullptr) {
664 return; // none
665 }
666
667 fprintf(gOutFile, "Class #%d annotations:\n", idx);
668
669 const DexFile::AnnotationSetItem* class_set_item = pDexFile->GetClassAnnotationSet(dir);
670 const DexFile::FieldAnnotationsItem* fields = pDexFile->GetFieldAnnotations(dir);
671 const DexFile::MethodAnnotationsItem* methods = pDexFile->GetMethodAnnotations(dir);
672 const DexFile::ParameterAnnotationsItem* pars = pDexFile->GetParameterAnnotations(dir);
673
674 // Annotations on the class itself.
675 if (class_set_item != nullptr) {
676 fprintf(gOutFile, "Annotations on class\n");
677 dumpAnnotationSetItem(pDexFile, class_set_item);
678 }
679
680 // Annotations on fields.
681 if (fields != nullptr) {
682 for (u4 i = 0; i < dir->fields_size_; i++) {
683 const u4 field_idx = fields[i].field_idx_;
684 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(field_idx);
685 const char* field_name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
686 fprintf(gOutFile, "Annotations on field #%u '%s'\n", field_idx, field_name);
687 dumpAnnotationSetItem(pDexFile, pDexFile->GetFieldAnnotationSetItem(fields[i]));
688 }
689 }
690
691 // Annotations on methods.
692 if (methods != nullptr) {
693 for (u4 i = 0; i < dir->methods_size_; i++) {
694 const u4 method_idx = methods[i].method_idx_;
695 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
696 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
697 fprintf(gOutFile, "Annotations on method #%u '%s'\n", method_idx, method_name);
698 dumpAnnotationSetItem(pDexFile, pDexFile->GetMethodAnnotationSetItem(methods[i]));
699 }
700 }
701
702 // Annotations on method parameters.
703 if (pars != nullptr) {
704 for (u4 i = 0; i < dir->parameters_size_; i++) {
705 const u4 method_idx = pars[i].method_idx_;
706 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(method_idx);
707 const char* method_name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
708 fprintf(gOutFile, "Annotations on method #%u '%s' parameters\n", method_idx, method_name);
709 const DexFile::AnnotationSetRefList*
710 list = pDexFile->GetParameterAnnotationSetRefList(&pars[i]);
711 if (list != nullptr) {
712 for (u4 j = 0; j < list->size_; j++) {
713 fprintf(gOutFile, "#%u\n", j);
714 dumpAnnotationSetItem(pDexFile, pDexFile->GetSetRefItemItem(&list->list_[j]));
715 }
716 }
717 }
718 }
719
720 fputc('\n', gOutFile);
721}
722
Aart Bik69ae54a2015-07-01 14:52:26 -0700723/*
724 * Dumps an interface that a class declares to implement.
725 */
726static void dumpInterface(const DexFile* pDexFile, const DexFile::TypeItem& pTypeItem, int i) {
727 const char* interfaceName = pDexFile->StringByTypeIdx(pTypeItem.type_idx_);
728 if (gOptions.outputFormat == OUTPUT_PLAIN) {
729 fprintf(gOutFile, " #%d : '%s'\n", i, interfaceName);
730 } else {
Aart Bikc05e2f22016-07-12 15:53:13 -0700731 std::unique_ptr<char[]> dot(descriptorToDot(interfaceName));
732 fprintf(gOutFile, "<implements name=\"%s\">\n</implements>\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -0700733 }
734}
735
736/*
737 * Dumps the catches table associated with the code.
738 */
739static void dumpCatches(const DexFile* pDexFile, const DexFile::CodeItem* pCode) {
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800740 CodeItemDataAccessor accessor(*pDexFile, pCode);
Mathieu Chartierdc578c72017-12-27 11:51:45 -0800741 const u4 triesSize = accessor.TriesSize();
Aart Bik69ae54a2015-07-01 14:52:26 -0700742
743 // No catch table.
744 if (triesSize == 0) {
745 fprintf(gOutFile, " catches : (none)\n");
746 return;
747 }
748
749 // Dump all table entries.
750 fprintf(gOutFile, " catches : %d\n", triesSize);
Mathieu Chartierdc578c72017-12-27 11:51:45 -0800751 for (const DexFile::TryItem& try_item : accessor.TryItems()) {
752 const u4 start = try_item.start_addr_;
753 const u4 end = start + try_item.insn_count_;
Aart Bik69ae54a2015-07-01 14:52:26 -0700754 fprintf(gOutFile, " 0x%04x - 0x%04x\n", start, end);
Mathieu Chartierdc578c72017-12-27 11:51:45 -0800755 for (CatchHandlerIterator it(accessor, try_item); it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800756 const dex::TypeIndex tidx = it.GetHandlerTypeIndex();
757 const char* descriptor = (!tidx.IsValid()) ? "<any>" : pDexFile->StringByTypeIdx(tidx);
Aart Bik69ae54a2015-07-01 14:52:26 -0700758 fprintf(gOutFile, " %s -> 0x%04x\n", descriptor, it.GetHandlerAddress());
759 } // for
760 } // for
761}
762
763/*
764 * Callback for dumping each positions table entry.
765 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000766static bool dumpPositionsCb(void* /*context*/, const DexFile::PositionInfo& entry) {
767 fprintf(gOutFile, " 0x%04x line=%d\n", entry.address_, entry.line_);
Aart Bik69ae54a2015-07-01 14:52:26 -0700768 return false;
769}
770
771/*
772 * Callback for dumping locals table entry.
773 */
David Srbeckyb06e28e2015-12-10 13:15:00 +0000774static void dumpLocalsCb(void* /*context*/, const DexFile::LocalInfo& entry) {
775 const char* signature = entry.signature_ != nullptr ? entry.signature_ : "";
Aart Bik69ae54a2015-07-01 14:52:26 -0700776 fprintf(gOutFile, " 0x%04x - 0x%04x reg=%d %s %s %s\n",
David Srbeckyb06e28e2015-12-10 13:15:00 +0000777 entry.start_address_, entry.end_address_, entry.reg_,
778 entry.name_, entry.descriptor_, signature);
Aart Bik69ae54a2015-07-01 14:52:26 -0700779}
780
781/*
782 * Helper for dumpInstruction(), which builds the string
Aart Bika0e33fd2016-07-08 18:32:45 -0700783 * representation for the index in the given instruction.
784 * Returns a pointer to a buffer of sufficient size.
Aart Bik69ae54a2015-07-01 14:52:26 -0700785 */
Aart Bika0e33fd2016-07-08 18:32:45 -0700786static std::unique_ptr<char[]> indexString(const DexFile* pDexFile,
787 const Instruction* pDecInsn,
788 size_t bufSize) {
789 std::unique_ptr<char[]> buf(new char[bufSize]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700790 // Determine index and width of the string.
791 u4 index = 0;
Orion Hodson16b2adf2018-05-14 08:53:38 +0100792 u2 secondary_index = 0;
Aart Bik69ae54a2015-07-01 14:52:26 -0700793 u4 width = 4;
794 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
795 // SOME NOT SUPPORTED:
796 // case Instruction::k20bc:
797 case Instruction::k21c:
798 case Instruction::k35c:
799 // case Instruction::k35ms:
800 case Instruction::k3rc:
801 // case Instruction::k3rms:
802 // case Instruction::k35mi:
803 // case Instruction::k3rmi:
804 index = pDecInsn->VRegB();
805 width = 4;
806 break;
807 case Instruction::k31c:
808 index = pDecInsn->VRegB();
809 width = 8;
810 break;
811 case Instruction::k22c:
812 // case Instruction::k22cs:
813 index = pDecInsn->VRegC();
814 width = 4;
815 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100816 case Instruction::k45cc:
817 case Instruction::k4rcc:
818 index = pDecInsn->VRegB();
819 secondary_index = pDecInsn->VRegH();
820 width = 4;
821 break;
Aart Bik69ae54a2015-07-01 14:52:26 -0700822 default:
823 break;
824 } // switch
825
826 // Determine index type.
827 size_t outSize = 0;
828 switch (Instruction::IndexTypeOf(pDecInsn->Opcode())) {
829 case Instruction::kIndexUnknown:
830 // This function should never get called for this type, but do
831 // something sensible here, just to help with debugging.
Aart Bika0e33fd2016-07-08 18:32:45 -0700832 outSize = snprintf(buf.get(), bufSize, "<unknown-index>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700833 break;
834 case Instruction::kIndexNone:
835 // This function should never get called for this type, but do
836 // something sensible here, just to help with debugging.
Aart Bika0e33fd2016-07-08 18:32:45 -0700837 outSize = snprintf(buf.get(), bufSize, "<no-index>");
Aart Bik69ae54a2015-07-01 14:52:26 -0700838 break;
839 case Instruction::kIndexTypeRef:
840 if (index < pDexFile->GetHeader().type_ids_size_) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800841 const char* tp = pDexFile->StringByTypeIdx(dex::TypeIndex(index));
Aart Bika0e33fd2016-07-08 18:32:45 -0700842 outSize = snprintf(buf.get(), bufSize, "%s // type@%0*x", tp, width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700843 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700844 outSize = snprintf(buf.get(), bufSize, "<type?> // type@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700845 }
846 break;
847 case Instruction::kIndexStringRef:
848 if (index < pDexFile->GetHeader().string_ids_size_) {
Andreas Gampe8a0128a2016-11-28 07:38:35 -0800849 const char* st = pDexFile->StringDataByIdx(dex::StringIndex(index));
Aart Bika0e33fd2016-07-08 18:32:45 -0700850 outSize = snprintf(buf.get(), bufSize, "\"%s\" // string@%0*x", st, width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700851 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700852 outSize = snprintf(buf.get(), bufSize, "<string?> // string@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700853 }
854 break;
855 case Instruction::kIndexMethodRef:
856 if (index < pDexFile->GetHeader().method_ids_size_) {
857 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
858 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
859 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
860 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
Aart Bika0e33fd2016-07-08 18:32:45 -0700861 outSize = snprintf(buf.get(), bufSize, "%s.%s:%s // method@%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700862 backDescriptor, name, signature.ToString().c_str(), width, index);
863 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700864 outSize = snprintf(buf.get(), bufSize, "<method?> // method@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700865 }
866 break;
867 case Instruction::kIndexFieldRef:
868 if (index < pDexFile->GetHeader().field_ids_size_) {
869 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(index);
870 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
871 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
872 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
Aart Bika0e33fd2016-07-08 18:32:45 -0700873 outSize = snprintf(buf.get(), bufSize, "%s.%s:%s // field@%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700874 backDescriptor, name, typeDescriptor, width, index);
875 } else {
Aart Bika0e33fd2016-07-08 18:32:45 -0700876 outSize = snprintf(buf.get(), bufSize, "<field?> // field@%0*x", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700877 }
878 break;
879 case Instruction::kIndexVtableOffset:
Aart Bika0e33fd2016-07-08 18:32:45 -0700880 outSize = snprintf(buf.get(), bufSize, "[%0*x] // vtable #%0*x",
Aart Bik69ae54a2015-07-01 14:52:26 -0700881 width, index, width, index);
882 break;
883 case Instruction::kIndexFieldOffset:
Aart Bika0e33fd2016-07-08 18:32:45 -0700884 outSize = snprintf(buf.get(), bufSize, "[obj+%0*x]", width, index);
Aart Bik69ae54a2015-07-01 14:52:26 -0700885 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +0100886 case Instruction::kIndexMethodAndProtoRef: {
Orion Hodsonc069a302017-01-18 09:23:12 +0000887 std::string method("<method?>");
888 std::string proto("<proto?>");
889 if (index < pDexFile->GetHeader().method_ids_size_) {
890 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
891 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
892 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
893 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
894 method = android::base::StringPrintf("%s.%s:%s",
895 backDescriptor,
896 name,
897 signature.ToString().c_str());
Orion Hodsonb34bb192016-10-18 17:02:58 +0100898 }
Orion Hodsonc069a302017-01-18 09:23:12 +0000899 if (secondary_index < pDexFile->GetHeader().proto_ids_size_) {
Orion Hodson16b2adf2018-05-14 08:53:38 +0100900 const DexFile::ProtoId& protoId = pDexFile->GetProtoId(dex::ProtoIndex(secondary_index));
Orion Hodsonc069a302017-01-18 09:23:12 +0000901 const Signature signature = pDexFile->GetProtoSignature(protoId);
902 proto = signature.ToString();
903 }
904 outSize = snprintf(buf.get(), bufSize, "%s, %s // method@%0*x, proto@%0*x",
905 method.c_str(), proto.c_str(), width, index, width, secondary_index);
906 break;
907 }
908 case Instruction::kIndexCallSiteRef:
909 // Call site information is too large to detail in disassembly so just output the index.
910 outSize = snprintf(buf.get(), bufSize, "call_site@%0*x", width, index);
Orion Hodsonb34bb192016-10-18 17:02:58 +0100911 break;
Orion Hodson2e599942017-09-22 16:17:41 +0100912 case Instruction::kIndexMethodHandleRef:
913 // Method handle information is too large to detail in disassembly so just output the index.
914 outSize = snprintf(buf.get(), bufSize, "method_handle@%0*x", width, index);
915 break;
916 case Instruction::kIndexProtoRef:
917 if (index < pDexFile->GetHeader().proto_ids_size_) {
Orion Hodson16b2adf2018-05-14 08:53:38 +0100918 const DexFile::ProtoId& protoId = pDexFile->GetProtoId(dex::ProtoIndex(index));
Orion Hodson2e599942017-09-22 16:17:41 +0100919 const Signature signature = pDexFile->GetProtoSignature(protoId);
920 const std::string& proto = signature.ToString();
921 outSize = snprintf(buf.get(), bufSize, "%s // proto@%0*x", proto.c_str(), width, index);
922 } else {
923 outSize = snprintf(buf.get(), bufSize, "<?> // proto@%0*x", width, index);
924 }
Aart Bik69ae54a2015-07-01 14:52:26 -0700925 break;
926 } // switch
927
Orion Hodson2e599942017-09-22 16:17:41 +0100928 if (outSize == 0) {
929 // The index type has not been handled in the switch above.
930 outSize = snprintf(buf.get(), bufSize, "<?>");
931 }
932
Aart Bik69ae54a2015-07-01 14:52:26 -0700933 // Determine success of string construction.
934 if (outSize >= bufSize) {
Aart Bika0e33fd2016-07-08 18:32:45 -0700935 // The buffer wasn't big enough; retry with computed size. Note: snprintf()
936 // doesn't count/ the '\0' as part of its returned size, so we add explicit
937 // space for it here.
938 return indexString(pDexFile, pDecInsn, outSize + 1);
Aart Bik69ae54a2015-07-01 14:52:26 -0700939 }
940 return buf;
941}
942
943/*
944 * Dumps a single instruction.
945 */
946static void dumpInstruction(const DexFile* pDexFile,
947 const DexFile::CodeItem* pCode,
948 u4 codeOffset, u4 insnIdx, u4 insnWidth,
949 const Instruction* pDecInsn) {
950 // Address of instruction (expressed as byte offset).
951 fprintf(gOutFile, "%06x:", codeOffset + 0x10 + insnIdx * 2);
952
953 // Dump (part of) raw bytes.
Mathieu Chartier698ebbc2018-01-05 11:00:42 -0800954 CodeItemInstructionAccessor accessor(*pDexFile, pCode);
Aart Bik69ae54a2015-07-01 14:52:26 -0700955 for (u4 i = 0; i < 8; i++) {
956 if (i < insnWidth) {
957 if (i == 7) {
958 fprintf(gOutFile, " ... ");
959 } else {
960 // Print 16-bit value in little-endian order.
Mathieu Chartier641a3af2017-12-15 11:42:58 -0800961 const u1* bytePtr = (const u1*) &accessor.Insns()[insnIdx + i];
Aart Bik69ae54a2015-07-01 14:52:26 -0700962 fprintf(gOutFile, " %02x%02x", bytePtr[0], bytePtr[1]);
963 }
964 } else {
965 fputs(" ", gOutFile);
966 }
967 } // for
968
969 // Dump pseudo-instruction or opcode.
970 if (pDecInsn->Opcode() == Instruction::NOP) {
Mathieu Chartier641a3af2017-12-15 11:42:58 -0800971 const u2 instr = get2LE((const u1*) &accessor.Insns()[insnIdx]);
Aart Bik69ae54a2015-07-01 14:52:26 -0700972 if (instr == Instruction::kPackedSwitchSignature) {
973 fprintf(gOutFile, "|%04x: packed-switch-data (%d units)", insnIdx, insnWidth);
974 } else if (instr == Instruction::kSparseSwitchSignature) {
975 fprintf(gOutFile, "|%04x: sparse-switch-data (%d units)", insnIdx, insnWidth);
976 } else if (instr == Instruction::kArrayDataSignature) {
977 fprintf(gOutFile, "|%04x: array-data (%d units)", insnIdx, insnWidth);
978 } else {
979 fprintf(gOutFile, "|%04x: nop // spacer", insnIdx);
980 }
981 } else {
982 fprintf(gOutFile, "|%04x: %s", insnIdx, pDecInsn->Name());
983 }
984
985 // Set up additional argument.
Aart Bika0e33fd2016-07-08 18:32:45 -0700986 std::unique_ptr<char[]> indexBuf;
Aart Bik69ae54a2015-07-01 14:52:26 -0700987 if (Instruction::IndexTypeOf(pDecInsn->Opcode()) != Instruction::kIndexNone) {
Aart Bika0e33fd2016-07-08 18:32:45 -0700988 indexBuf = indexString(pDexFile, pDecInsn, 200);
Aart Bik69ae54a2015-07-01 14:52:26 -0700989 }
990
991 // Dump the instruction.
992 //
993 // NOTE: pDecInsn->DumpString(pDexFile) differs too much from original.
994 //
995 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
996 case Instruction::k10x: // op
997 break;
998 case Instruction::k12x: // op vA, vB
999 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
1000 break;
1001 case Instruction::k11n: // op vA, #+B
1002 fprintf(gOutFile, " v%d, #int %d // #%x",
1003 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u1)pDecInsn->VRegB());
1004 break;
1005 case Instruction::k11x: // op vAA
1006 fprintf(gOutFile, " v%d", pDecInsn->VRegA());
1007 break;
1008 case Instruction::k10t: // op +AA
Aart Bikdce50862016-06-10 16:04:03 -07001009 case Instruction::k20t: { // op +AAAA
1010 const s4 targ = (s4) pDecInsn->VRegA();
1011 fprintf(gOutFile, " %04x // %c%04x",
1012 insnIdx + targ,
1013 (targ < 0) ? '-' : '+',
1014 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001015 break;
Aart Bikdce50862016-06-10 16:04:03 -07001016 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001017 case Instruction::k22x: // op vAA, vBBBB
1018 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
1019 break;
Aart Bikdce50862016-06-10 16:04:03 -07001020 case Instruction::k21t: { // op vAA, +BBBB
1021 const s4 targ = (s4) pDecInsn->VRegB();
1022 fprintf(gOutFile, " v%d, %04x // %c%04x", pDecInsn->VRegA(),
1023 insnIdx + targ,
1024 (targ < 0) ? '-' : '+',
1025 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001026 break;
Aart Bikdce50862016-06-10 16:04:03 -07001027 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001028 case Instruction::k21s: // op vAA, #+BBBB
1029 fprintf(gOutFile, " v%d, #int %d // #%x",
1030 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u2)pDecInsn->VRegB());
1031 break;
1032 case Instruction::k21h: // op vAA, #+BBBB0000[00000000]
1033 // The printed format varies a bit based on the actual opcode.
1034 if (pDecInsn->Opcode() == Instruction::CONST_HIGH16) {
1035 const s4 value = pDecInsn->VRegB() << 16;
1036 fprintf(gOutFile, " v%d, #int %d // #%x",
1037 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
1038 } else {
1039 const s8 value = ((s8) pDecInsn->VRegB()) << 48;
1040 fprintf(gOutFile, " v%d, #long %" PRId64 " // #%x",
1041 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
1042 }
1043 break;
1044 case Instruction::k21c: // op vAA, thing@BBBB
1045 case Instruction::k31c: // op vAA, thing@BBBBBBBB
Aart Bika0e33fd2016-07-08 18:32:45 -07001046 fprintf(gOutFile, " v%d, %s", pDecInsn->VRegA(), indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001047 break;
1048 case Instruction::k23x: // op vAA, vBB, vCC
1049 fprintf(gOutFile, " v%d, v%d, v%d",
1050 pDecInsn->VRegA(), pDecInsn->VRegB(), pDecInsn->VRegC());
1051 break;
1052 case Instruction::k22b: // op vAA, vBB, #+CC
1053 fprintf(gOutFile, " v%d, v%d, #int %d // #%02x",
1054 pDecInsn->VRegA(), pDecInsn->VRegB(),
1055 (s4) pDecInsn->VRegC(), (u1) pDecInsn->VRegC());
1056 break;
Aart Bikdce50862016-06-10 16:04:03 -07001057 case Instruction::k22t: { // op vA, vB, +CCCC
1058 const s4 targ = (s4) pDecInsn->VRegC();
1059 fprintf(gOutFile, " v%d, v%d, %04x // %c%04x",
1060 pDecInsn->VRegA(), pDecInsn->VRegB(),
1061 insnIdx + targ,
1062 (targ < 0) ? '-' : '+',
1063 (targ < 0) ? -targ : targ);
Aart Bik69ae54a2015-07-01 14:52:26 -07001064 break;
Aart Bikdce50862016-06-10 16:04:03 -07001065 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001066 case Instruction::k22s: // op vA, vB, #+CCCC
1067 fprintf(gOutFile, " v%d, v%d, #int %d // #%04x",
1068 pDecInsn->VRegA(), pDecInsn->VRegB(),
1069 (s4) pDecInsn->VRegC(), (u2) pDecInsn->VRegC());
1070 break;
1071 case Instruction::k22c: // op vA, vB, thing@CCCC
1072 // NOT SUPPORTED:
1073 // case Instruction::k22cs: // [opt] op vA, vB, field offset CCCC
1074 fprintf(gOutFile, " v%d, v%d, %s",
Aart Bika0e33fd2016-07-08 18:32:45 -07001075 pDecInsn->VRegA(), pDecInsn->VRegB(), indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001076 break;
1077 case Instruction::k30t:
1078 fprintf(gOutFile, " #%08x", pDecInsn->VRegA());
1079 break;
Aart Bikdce50862016-06-10 16:04:03 -07001080 case Instruction::k31i: { // op vAA, #+BBBBBBBB
1081 // This is often, but not always, a float.
1082 union {
1083 float f;
1084 u4 i;
1085 } conv;
1086 conv.i = pDecInsn->VRegB();
1087 fprintf(gOutFile, " v%d, #float %g // #%08x",
1088 pDecInsn->VRegA(), conv.f, pDecInsn->VRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001089 break;
Aart Bikdce50862016-06-10 16:04:03 -07001090 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001091 case Instruction::k31t: // op vAA, offset +BBBBBBBB
1092 fprintf(gOutFile, " v%d, %08x // +%08x",
1093 pDecInsn->VRegA(), insnIdx + pDecInsn->VRegB(), pDecInsn->VRegB());
1094 break;
1095 case Instruction::k32x: // op vAAAA, vBBBB
1096 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
1097 break;
Orion Hodsonb34bb192016-10-18 17:02:58 +01001098 case Instruction::k35c: // op {vC, vD, vE, vF, vG}, thing@BBBB
1099 case Instruction::k45cc: { // op {vC, vD, vE, vF, vG}, method@BBBB, proto@HHHH
Aart Bik69ae54a2015-07-01 14:52:26 -07001100 // NOT SUPPORTED:
1101 // case Instruction::k35ms: // [opt] invoke-virtual+super
1102 // case Instruction::k35mi: // [opt] inline invoke
Aart Bikdce50862016-06-10 16:04:03 -07001103 u4 arg[Instruction::kMaxVarArgRegs];
1104 pDecInsn->GetVarArgs(arg);
1105 fputs(" {", gOutFile);
1106 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1107 if (i == 0) {
1108 fprintf(gOutFile, "v%d", arg[i]);
1109 } else {
1110 fprintf(gOutFile, ", v%d", arg[i]);
1111 }
1112 } // for
Aart Bika0e33fd2016-07-08 18:32:45 -07001113 fprintf(gOutFile, "}, %s", indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001114 break;
Aart Bikdce50862016-06-10 16:04:03 -07001115 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001116 case Instruction::k3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB
Orion Hodsonb34bb192016-10-18 17:02:58 +01001117 case Instruction::k4rcc: { // op {vCCCC .. v(CCCC+AA-1)}, method@BBBB, proto@HHHH
Aart Bik69ae54a2015-07-01 14:52:26 -07001118 // NOT SUPPORTED:
1119 // case Instruction::k3rms: // [opt] invoke-virtual+super/range
1120 // case Instruction::k3rmi: // [opt] execute-inline/range
Aart Bik69ae54a2015-07-01 14:52:26 -07001121 // This doesn't match the "dx" output when some of the args are
1122 // 64-bit values -- dx only shows the first register.
1123 fputs(" {", gOutFile);
1124 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
1125 if (i == 0) {
1126 fprintf(gOutFile, "v%d", pDecInsn->VRegC() + i);
1127 } else {
1128 fprintf(gOutFile, ", v%d", pDecInsn->VRegC() + i);
1129 }
1130 } // for
Aart Bika0e33fd2016-07-08 18:32:45 -07001131 fprintf(gOutFile, "}, %s", indexBuf.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001132 }
1133 break;
Aart Bikdce50862016-06-10 16:04:03 -07001134 case Instruction::k51l: { // op vAA, #+BBBBBBBBBBBBBBBB
1135 // This is often, but not always, a double.
1136 union {
1137 double d;
1138 u8 j;
1139 } conv;
1140 conv.j = pDecInsn->WideVRegB();
1141 fprintf(gOutFile, " v%d, #double %g // #%016" PRIx64,
1142 pDecInsn->VRegA(), conv.d, pDecInsn->WideVRegB());
Aart Bik69ae54a2015-07-01 14:52:26 -07001143 break;
Aart Bikdce50862016-06-10 16:04:03 -07001144 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001145 // NOT SUPPORTED:
1146 // case Instruction::k00x: // unknown op or breakpoint
1147 // break;
1148 default:
1149 fprintf(gOutFile, " ???");
1150 break;
1151 } // switch
1152
1153 fputc('\n', gOutFile);
Aart Bik69ae54a2015-07-01 14:52:26 -07001154}
1155
1156/*
1157 * Dumps a bytecode disassembly.
1158 */
1159static void dumpBytecodes(const DexFile* pDexFile, u4 idx,
1160 const DexFile::CodeItem* pCode, u4 codeOffset) {
1161 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
1162 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
1163 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
1164 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
1165
1166 // Generate header.
Aart Bikc05e2f22016-07-12 15:53:13 -07001167 std::unique_ptr<char[]> dot(descriptorToDot(backDescriptor));
1168 fprintf(gOutFile, "%06x: |[%06x] %s.%s:%s\n",
1169 codeOffset, codeOffset, dot.get(), name, signature.ToString().c_str());
Aart Bik69ae54a2015-07-01 14:52:26 -07001170
1171 // Iterate over all instructions.
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001172 CodeItemDataAccessor accessor(*pDexFile, pCode);
Aart Bik7a9aaf12018-02-05 17:00:40 -08001173 const u4 maxPc = accessor.InsnsSizeInCodeUnits();
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001174 for (const DexInstructionPcPair& pair : accessor) {
Aart Bik7a9aaf12018-02-05 17:00:40 -08001175 const u4 dexPc = pair.DexPc();
1176 if (dexPc >= maxPc) {
1177 LOG(WARNING) << "GLITCH: run-away instruction at idx=0x" << std::hex << dexPc;
1178 break;
1179 }
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001180 const Instruction* instruction = &pair.Inst();
Aart Bik69ae54a2015-07-01 14:52:26 -07001181 const u4 insnWidth = instruction->SizeInCodeUnits();
1182 if (insnWidth == 0) {
Aart Bik7a9aaf12018-02-05 17:00:40 -08001183 LOG(WARNING) << "GLITCH: zero-width instruction at idx=0x" << std::hex << dexPc;
Aart Bik69ae54a2015-07-01 14:52:26 -07001184 break;
1185 }
Aart Bik7a9aaf12018-02-05 17:00:40 -08001186 dumpInstruction(pDexFile, pCode, codeOffset, dexPc, insnWidth, instruction);
Aart Bik69ae54a2015-07-01 14:52:26 -07001187 } // for
1188}
1189
1190/*
1191 * Dumps code of a method.
1192 */
1193static void dumpCode(const DexFile* pDexFile, u4 idx, u4 flags,
1194 const DexFile::CodeItem* pCode, u4 codeOffset) {
Mathieu Chartier8892c6b2018-01-09 15:10:17 -08001195 CodeItemDebugInfoAccessor accessor(*pDexFile, pCode, idx);
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001196
1197 fprintf(gOutFile, " registers : %d\n", accessor.RegistersSize());
1198 fprintf(gOutFile, " ins : %d\n", accessor.InsSize());
1199 fprintf(gOutFile, " outs : %d\n", accessor.OutsSize());
Aart Bik69ae54a2015-07-01 14:52:26 -07001200 fprintf(gOutFile, " insns size : %d 16-bit code units\n",
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001201 accessor.InsnsSizeInCodeUnits());
Aart Bik69ae54a2015-07-01 14:52:26 -07001202
1203 // Bytecode disassembly, if requested.
1204 if (gOptions.disassemble) {
1205 dumpBytecodes(pDexFile, idx, pCode, codeOffset);
1206 }
1207
1208 // Try-catch blocks.
1209 dumpCatches(pDexFile, pCode);
1210
1211 // Positions and locals table in the debug info.
1212 bool is_static = (flags & kAccStatic) != 0;
1213 fprintf(gOutFile, " positions : \n");
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001214 pDexFile->DecodeDebugPositionInfo(accessor.DebugInfoOffset(), dumpPositionsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001215 fprintf(gOutFile, " locals : \n");
Mathieu Chartier641a3af2017-12-15 11:42:58 -08001216 accessor.DecodeDebugLocalInfo(is_static, idx, dumpLocalsCb, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001217}
1218
1219/*
1220 * Dumps a method.
1221 */
1222static void dumpMethod(const DexFile* pDexFile, u4 idx, u4 flags,
1223 const DexFile::CodeItem* pCode, u4 codeOffset, int i) {
1224 // Bail for anything private if export only requested.
1225 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1226 return;
1227 }
1228
1229 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
1230 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
1231 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
1232 char* typeDescriptor = strdup(signature.ToString().c_str());
1233 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
1234 char* accessStr = createAccessFlagStr(flags, kAccessForMethod);
1235
1236 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1237 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1238 fprintf(gOutFile, " name : '%s'\n", name);
1239 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1240 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
1241 if (pCode == nullptr) {
1242 fprintf(gOutFile, " code : (none)\n");
1243 } else {
1244 fprintf(gOutFile, " code -\n");
1245 dumpCode(pDexFile, idx, flags, pCode, codeOffset);
1246 }
1247 if (gOptions.disassemble) {
1248 fputc('\n', gOutFile);
1249 }
1250 } else if (gOptions.outputFormat == OUTPUT_XML) {
1251 const bool constructor = (name[0] == '<');
1252
1253 // Method name and prototype.
1254 if (constructor) {
Aart Bikc05e2f22016-07-12 15:53:13 -07001255 std::unique_ptr<char[]> dot(descriptorClassToDot(backDescriptor));
1256 fprintf(gOutFile, "<constructor name=\"%s\"\n", dot.get());
1257 dot = descriptorToDot(backDescriptor);
1258 fprintf(gOutFile, " type=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001259 } else {
1260 fprintf(gOutFile, "<method name=\"%s\"\n", name);
1261 const char* returnType = strrchr(typeDescriptor, ')');
1262 if (returnType == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08001263 LOG(ERROR) << "bad method type descriptor '" << typeDescriptor << "'";
Aart Bik69ae54a2015-07-01 14:52:26 -07001264 goto bail;
1265 }
Aart Bikc05e2f22016-07-12 15:53:13 -07001266 std::unique_ptr<char[]> dot(descriptorToDot(returnType + 1));
1267 fprintf(gOutFile, " return=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001268 fprintf(gOutFile, " abstract=%s\n", quotedBool((flags & kAccAbstract) != 0));
1269 fprintf(gOutFile, " native=%s\n", quotedBool((flags & kAccNative) != 0));
1270 fprintf(gOutFile, " synchronized=%s\n", quotedBool(
1271 (flags & (kAccSynchronized | kAccDeclaredSynchronized)) != 0));
1272 }
1273
1274 // Additional method flags.
1275 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1276 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1277 // The "deprecated=" not knowable w/o parsing annotations.
1278 fprintf(gOutFile, " visibility=%s\n>\n", quotedVisibility(flags));
1279
1280 // Parameters.
1281 if (typeDescriptor[0] != '(') {
Andreas Gampe221d9812018-01-22 17:48:56 -08001282 LOG(ERROR) << "ERROR: bad descriptor '" << typeDescriptor << "'";
Aart Bik69ae54a2015-07-01 14:52:26 -07001283 goto bail;
1284 }
1285 char* tmpBuf = reinterpret_cast<char*>(malloc(strlen(typeDescriptor) + 1));
1286 const char* base = typeDescriptor + 1;
1287 int argNum = 0;
1288 while (*base != ')') {
1289 char* cp = tmpBuf;
1290 while (*base == '[') {
1291 *cp++ = *base++;
1292 }
1293 if (*base == 'L') {
1294 // Copy through ';'.
1295 do {
1296 *cp = *base++;
1297 } while (*cp++ != ';');
1298 } else {
1299 // Primitive char, copy it.
Aart Bikc05e2f22016-07-12 15:53:13 -07001300 if (strchr("ZBCSIFJD", *base) == nullptr) {
Andreas Gampe221d9812018-01-22 17:48:56 -08001301 LOG(ERROR) << "ERROR: bad method signature '" << base << "'";
Aart Bika0e33fd2016-07-08 18:32:45 -07001302 break; // while
Aart Bik69ae54a2015-07-01 14:52:26 -07001303 }
1304 *cp++ = *base++;
1305 }
1306 // Null terminate and display.
1307 *cp++ = '\0';
Aart Bikc05e2f22016-07-12 15:53:13 -07001308 std::unique_ptr<char[]> dot(descriptorToDot(tmpBuf));
Aart Bik69ae54a2015-07-01 14:52:26 -07001309 fprintf(gOutFile, "<parameter name=\"arg%d\" type=\"%s\">\n"
Aart Bikc05e2f22016-07-12 15:53:13 -07001310 "</parameter>\n", argNum++, dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001311 } // while
1312 free(tmpBuf);
1313 if (constructor) {
1314 fprintf(gOutFile, "</constructor>\n");
1315 } else {
1316 fprintf(gOutFile, "</method>\n");
1317 }
1318 }
1319
1320 bail:
1321 free(typeDescriptor);
1322 free(accessStr);
1323}
1324
1325/*
1326 * Dumps a static (class) field.
1327 */
Aart Bikdce50862016-06-10 16:04:03 -07001328static void dumpSField(const DexFile* pDexFile, u4 idx, u4 flags, int i, const u1** data) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001329 // Bail for anything private if export only requested.
1330 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1331 return;
1332 }
1333
1334 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(idx);
1335 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
1336 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
1337 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
1338 char* accessStr = createAccessFlagStr(flags, kAccessForField);
1339
1340 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1341 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1342 fprintf(gOutFile, " name : '%s'\n", name);
1343 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1344 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
Aart Bikdce50862016-06-10 16:04:03 -07001345 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001346 fputs(" value : ", gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -07001347 dumpEncodedValue(pDexFile, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001348 fputs("\n", gOutFile);
1349 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001350 } else if (gOptions.outputFormat == OUTPUT_XML) {
1351 fprintf(gOutFile, "<field name=\"%s\"\n", name);
Aart Bikc05e2f22016-07-12 15:53:13 -07001352 std::unique_ptr<char[]> dot(descriptorToDot(typeDescriptor));
1353 fprintf(gOutFile, " type=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001354 fprintf(gOutFile, " transient=%s\n", quotedBool((flags & kAccTransient) != 0));
1355 fprintf(gOutFile, " volatile=%s\n", quotedBool((flags & kAccVolatile) != 0));
1356 // The "value=" is not knowable w/o parsing annotations.
1357 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1358 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1359 // The "deprecated=" is not knowable w/o parsing annotations.
1360 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(flags));
Aart Bikdce50862016-06-10 16:04:03 -07001361 if (data != nullptr) {
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001362 fputs(" value=\"", gOutFile);
Aart Bikdce50862016-06-10 16:04:03 -07001363 dumpEncodedValue(pDexFile, data);
Shinichiro Hamaji82863f02015-11-05 16:51:33 +09001364 fputs("\"\n", gOutFile);
1365 }
1366 fputs(">\n</field>\n", gOutFile);
Aart Bik69ae54a2015-07-01 14:52:26 -07001367 }
1368
1369 free(accessStr);
1370}
1371
1372/*
1373 * Dumps an instance field.
1374 */
1375static void dumpIField(const DexFile* pDexFile, u4 idx, u4 flags, int i) {
Aart Bikdce50862016-06-10 16:04:03 -07001376 dumpSField(pDexFile, idx, flags, i, nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001377}
1378
1379/*
Andreas Gampe5073fed2015-08-10 11:40:25 -07001380 * Dumping a CFG. Note that this will do duplicate work. utils.h doesn't expose the code-item
1381 * version, so the DumpMethodCFG code will have to iterate again to find it. But dexdump is a
1382 * tool, so this is not performance-critical.
1383 */
1384
1385static void dumpCfg(const DexFile* dex_file,
Aart Bikdce50862016-06-10 16:04:03 -07001386 u4 dex_method_idx,
Andreas Gampe5073fed2015-08-10 11:40:25 -07001387 const DexFile::CodeItem* code_item) {
1388 if (code_item != nullptr) {
1389 std::ostringstream oss;
1390 DumpMethodCFG(dex_file, dex_method_idx, oss);
David Sehrcaacd112016-10-20 16:27:02 -07001391 fputs(oss.str().c_str(), gOutFile);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001392 }
1393}
1394
1395static void dumpCfg(const DexFile* dex_file, int idx) {
1396 const DexFile::ClassDef& class_def = dex_file->GetClassDef(idx);
Aart Bikdce50862016-06-10 16:04:03 -07001397 const u1* class_data = dex_file->GetClassData(class_def);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001398 if (class_data == nullptr) { // empty class such as a marker interface?
1399 return;
1400 }
1401 ClassDataItemIterator it(*dex_file, class_data);
Mathieu Chartiere17cf242017-06-19 11:05:51 -07001402 it.SkipAllFields();
Mathieu Chartierb7c273c2017-11-10 18:07:56 -08001403 while (it.HasNextMethod()) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001404 dumpCfg(dex_file,
1405 it.GetMemberIndex(),
1406 it.GetMethodCodeItem());
1407 it.Next();
1408 }
Andreas Gampe5073fed2015-08-10 11:40:25 -07001409}
1410
1411/*
Aart Bik69ae54a2015-07-01 14:52:26 -07001412 * Dumps the class.
1413 *
1414 * Note "idx" is a DexClassDef index, not a DexTypeId index.
1415 *
1416 * If "*pLastPackage" is nullptr or does not match the current class' package,
1417 * the value will be replaced with a newly-allocated string.
1418 */
1419static void dumpClass(const DexFile* pDexFile, int idx, char** pLastPackage) {
1420 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
1421
1422 // Omitting non-public class.
1423 if (gOptions.exportsOnly && (pClassDef.access_flags_ & kAccPublic) == 0) {
1424 return;
1425 }
1426
Aart Bikdce50862016-06-10 16:04:03 -07001427 if (gOptions.showSectionHeaders) {
1428 dumpClassDef(pDexFile, idx);
1429 }
1430
1431 if (gOptions.showAnnotations) {
1432 dumpClassAnnotations(pDexFile, idx);
1433 }
1434
1435 if (gOptions.showCfg) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001436 dumpCfg(pDexFile, idx);
1437 return;
1438 }
1439
Aart Bik69ae54a2015-07-01 14:52:26 -07001440 // For the XML output, show the package name. Ideally we'd gather
1441 // up the classes, sort them, and dump them alphabetically so the
1442 // package name wouldn't jump around, but that's not a great plan
1443 // for something that needs to run on the device.
1444 const char* classDescriptor = pDexFile->StringByTypeIdx(pClassDef.class_idx_);
1445 if (!(classDescriptor[0] == 'L' &&
1446 classDescriptor[strlen(classDescriptor)-1] == ';')) {
1447 // Arrays and primitives should not be defined explicitly. Keep going?
Andreas Gampe221d9812018-01-22 17:48:56 -08001448 LOG(WARNING) << "Malformed class name '" << classDescriptor << "'";
Aart Bik69ae54a2015-07-01 14:52:26 -07001449 } else if (gOptions.outputFormat == OUTPUT_XML) {
1450 char* mangle = strdup(classDescriptor + 1);
1451 mangle[strlen(mangle)-1] = '\0';
1452
1453 // Reduce to just the package name.
1454 char* lastSlash = strrchr(mangle, '/');
1455 if (lastSlash != nullptr) {
1456 *lastSlash = '\0';
1457 } else {
1458 *mangle = '\0';
1459 }
1460
1461 for (char* cp = mangle; *cp != '\0'; cp++) {
1462 if (*cp == '/') {
1463 *cp = '.';
1464 }
1465 } // for
1466
1467 if (*pLastPackage == nullptr || strcmp(mangle, *pLastPackage) != 0) {
1468 // Start of a new package.
1469 if (*pLastPackage != nullptr) {
1470 fprintf(gOutFile, "</package>\n");
1471 }
1472 fprintf(gOutFile, "<package name=\"%s\"\n>\n", mangle);
1473 free(*pLastPackage);
1474 *pLastPackage = mangle;
1475 } else {
1476 free(mangle);
1477 }
1478 }
1479
1480 // General class information.
1481 char* accessStr = createAccessFlagStr(pClassDef.access_flags_, kAccessForClass);
1482 const char* superclassDescriptor;
Andreas Gampea5b09a62016-11-17 15:21:22 -08001483 if (!pClassDef.superclass_idx_.IsValid()) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001484 superclassDescriptor = nullptr;
1485 } else {
1486 superclassDescriptor = pDexFile->StringByTypeIdx(pClassDef.superclass_idx_);
1487 }
1488 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1489 fprintf(gOutFile, "Class #%d -\n", idx);
1490 fprintf(gOutFile, " Class descriptor : '%s'\n", classDescriptor);
1491 fprintf(gOutFile, " Access flags : 0x%04x (%s)\n", pClassDef.access_flags_, accessStr);
1492 if (superclassDescriptor != nullptr) {
1493 fprintf(gOutFile, " Superclass : '%s'\n", superclassDescriptor);
1494 }
1495 fprintf(gOutFile, " Interfaces -\n");
1496 } else {
Aart Bikc05e2f22016-07-12 15:53:13 -07001497 std::unique_ptr<char[]> dot(descriptorClassToDot(classDescriptor));
1498 fprintf(gOutFile, "<class name=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001499 if (superclassDescriptor != nullptr) {
Aart Bikc05e2f22016-07-12 15:53:13 -07001500 dot = descriptorToDot(superclassDescriptor);
1501 fprintf(gOutFile, " extends=\"%s\"\n", dot.get());
Aart Bik69ae54a2015-07-01 14:52:26 -07001502 }
Alex Light1f12e282015-12-10 16:49:47 -08001503 fprintf(gOutFile, " interface=%s\n",
1504 quotedBool((pClassDef.access_flags_ & kAccInterface) != 0));
Aart Bik69ae54a2015-07-01 14:52:26 -07001505 fprintf(gOutFile, " abstract=%s\n", quotedBool((pClassDef.access_flags_ & kAccAbstract) != 0));
1506 fprintf(gOutFile, " static=%s\n", quotedBool((pClassDef.access_flags_ & kAccStatic) != 0));
1507 fprintf(gOutFile, " final=%s\n", quotedBool((pClassDef.access_flags_ & kAccFinal) != 0));
1508 // The "deprecated=" not knowable w/o parsing annotations.
1509 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(pClassDef.access_flags_));
1510 fprintf(gOutFile, ">\n");
1511 }
1512
1513 // Interfaces.
1514 const DexFile::TypeList* pInterfaces = pDexFile->GetInterfacesList(pClassDef);
1515 if (pInterfaces != nullptr) {
1516 for (u4 i = 0; i < pInterfaces->Size(); i++) {
1517 dumpInterface(pDexFile, pInterfaces->GetTypeItem(i), i);
1518 } // for
1519 }
1520
1521 // Fields and methods.
1522 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
1523 if (pEncodedData == nullptr) {
1524 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1525 fprintf(gOutFile, " Static fields -\n");
1526 fprintf(gOutFile, " Instance fields -\n");
1527 fprintf(gOutFile, " Direct methods -\n");
1528 fprintf(gOutFile, " Virtual methods -\n");
1529 }
1530 } else {
1531 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
Aart Bikdce50862016-06-10 16:04:03 -07001532
1533 // Prepare data for static fields.
1534 const u1* sData = pDexFile->GetEncodedStaticFieldValuesArray(pClassDef);
1535 const u4 sSize = sData != nullptr ? DecodeUnsignedLeb128(&sData) : 0;
1536
1537 // Static fields.
Aart Bik69ae54a2015-07-01 14:52:26 -07001538 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1539 fprintf(gOutFile, " Static fields -\n");
1540 }
Aart Bikdce50862016-06-10 16:04:03 -07001541 for (u4 i = 0; pClassData.HasNextStaticField(); i++, pClassData.Next()) {
1542 dumpSField(pDexFile,
1543 pClassData.GetMemberIndex(),
1544 pClassData.GetRawMemberAccessFlags(),
1545 i,
1546 i < sSize ? &sData : nullptr);
Aart Bik69ae54a2015-07-01 14:52:26 -07001547 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001548
1549 // Instance fields.
Aart Bik69ae54a2015-07-01 14:52:26 -07001550 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1551 fprintf(gOutFile, " Instance fields -\n");
1552 }
Aart Bikdce50862016-06-10 16:04:03 -07001553 for (u4 i = 0; pClassData.HasNextInstanceField(); i++, pClassData.Next()) {
1554 dumpIField(pDexFile,
1555 pClassData.GetMemberIndex(),
1556 pClassData.GetRawMemberAccessFlags(),
1557 i);
Aart Bik69ae54a2015-07-01 14:52:26 -07001558 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001559
1560 // Direct methods.
Aart Bik69ae54a2015-07-01 14:52:26 -07001561 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1562 fprintf(gOutFile, " Direct methods -\n");
1563 }
1564 for (int i = 0; pClassData.HasNextDirectMethod(); i++, pClassData.Next()) {
1565 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1566 pClassData.GetRawMemberAccessFlags(),
1567 pClassData.GetMethodCodeItem(),
1568 pClassData.GetMethodCodeItemOffset(), i);
1569 } // for
Aart Bikdce50862016-06-10 16:04:03 -07001570
1571 // Virtual methods.
Aart Bik69ae54a2015-07-01 14:52:26 -07001572 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1573 fprintf(gOutFile, " Virtual methods -\n");
1574 }
1575 for (int i = 0; pClassData.HasNextVirtualMethod(); i++, pClassData.Next()) {
1576 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1577 pClassData.GetRawMemberAccessFlags(),
1578 pClassData.GetMethodCodeItem(),
1579 pClassData.GetMethodCodeItemOffset(), i);
1580 } // for
1581 }
1582
1583 // End of class.
1584 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1585 const char* fileName;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001586 if (pClassDef.source_file_idx_.IsValid()) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001587 fileName = pDexFile->StringDataByIdx(pClassDef.source_file_idx_);
1588 } else {
1589 fileName = "unknown";
1590 }
1591 fprintf(gOutFile, " source_file_idx : %d (%s)\n\n",
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001592 pClassDef.source_file_idx_.index_, fileName);
Aart Bik69ae54a2015-07-01 14:52:26 -07001593 } else if (gOptions.outputFormat == OUTPUT_XML) {
1594 fprintf(gOutFile, "</class>\n");
1595 }
1596
1597 free(accessStr);
1598}
1599
Orion Hodsonc069a302017-01-18 09:23:12 +00001600static void dumpMethodHandle(const DexFile* pDexFile, u4 idx) {
1601 const DexFile::MethodHandleItem& mh = pDexFile->GetMethodHandle(idx);
Orion Hodson631827d2017-04-10 14:53:47 +01001602 const char* type = nullptr;
1603 bool is_instance = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001604 bool is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001605 switch (static_cast<DexFile::MethodHandleType>(mh.method_handle_type_)) {
1606 case DexFile::MethodHandleType::kStaticPut:
1607 type = "put-static";
Orion Hodson631827d2017-04-10 14:53:47 +01001608 is_instance = false;
1609 is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001610 break;
1611 case DexFile::MethodHandleType::kStaticGet:
1612 type = "get-static";
Orion Hodson631827d2017-04-10 14:53:47 +01001613 is_instance = false;
1614 is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001615 break;
1616 case DexFile::MethodHandleType::kInstancePut:
1617 type = "put-instance";
Orion Hodson631827d2017-04-10 14:53:47 +01001618 is_instance = true;
1619 is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001620 break;
1621 case DexFile::MethodHandleType::kInstanceGet:
1622 type = "get-instance";
Orion Hodson631827d2017-04-10 14:53:47 +01001623 is_instance = true;
1624 is_invoke = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001625 break;
1626 case DexFile::MethodHandleType::kInvokeStatic:
1627 type = "invoke-static";
Orion Hodson631827d2017-04-10 14:53:47 +01001628 is_instance = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00001629 is_invoke = true;
1630 break;
1631 case DexFile::MethodHandleType::kInvokeInstance:
1632 type = "invoke-instance";
Orion Hodson631827d2017-04-10 14:53:47 +01001633 is_instance = true;
Orion Hodsonc069a302017-01-18 09:23:12 +00001634 is_invoke = true;
1635 break;
1636 case DexFile::MethodHandleType::kInvokeConstructor:
1637 type = "invoke-constructor";
Orion Hodson631827d2017-04-10 14:53:47 +01001638 is_instance = true;
1639 is_invoke = true;
1640 break;
1641 case DexFile::MethodHandleType::kInvokeDirect:
1642 type = "invoke-direct";
1643 is_instance = true;
1644 is_invoke = true;
1645 break;
1646 case DexFile::MethodHandleType::kInvokeInterface:
1647 type = "invoke-interface";
1648 is_instance = true;
Orion Hodsonc069a302017-01-18 09:23:12 +00001649 is_invoke = true;
1650 break;
1651 }
1652
1653 const char* declaring_class;
1654 const char* member;
1655 std::string member_type;
Orion Hodson631827d2017-04-10 14:53:47 +01001656 if (type != nullptr) {
1657 if (is_invoke) {
1658 const DexFile::MethodId& method_id = pDexFile->GetMethodId(mh.field_or_method_idx_);
1659 declaring_class = pDexFile->GetMethodDeclaringClassDescriptor(method_id);
1660 member = pDexFile->GetMethodName(method_id);
1661 member_type = pDexFile->GetMethodSignature(method_id).ToString();
1662 } else {
1663 const DexFile::FieldId& field_id = pDexFile->GetFieldId(mh.field_or_method_idx_);
1664 declaring_class = pDexFile->GetFieldDeclaringClassDescriptor(field_id);
1665 member = pDexFile->GetFieldName(field_id);
1666 member_type = pDexFile->GetFieldTypeDescriptor(field_id);
1667 }
1668 if (is_instance) {
1669 member_type = android::base::StringPrintf("(%s%s", declaring_class, member_type.c_str() + 1);
1670 }
Orion Hodsonc069a302017-01-18 09:23:12 +00001671 } else {
Orion Hodson631827d2017-04-10 14:53:47 +01001672 type = "?";
1673 declaring_class = "?";
1674 member = "?";
1675 member_type = "?";
Orion Hodsonc069a302017-01-18 09:23:12 +00001676 }
1677
1678 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1679 fprintf(gOutFile, "Method handle #%u:\n", idx);
1680 fprintf(gOutFile, " type : %s\n", type);
1681 fprintf(gOutFile, " target : %s %s\n", declaring_class, member);
1682 fprintf(gOutFile, " target_type : %s\n", member_type.c_str());
1683 } else {
1684 fprintf(gOutFile, "<method_handle index=\"%u\"\n", idx);
1685 fprintf(gOutFile, " type=\"%s\"\n", type);
1686 fprintf(gOutFile, " target_class=\"%s\"\n", declaring_class);
1687 fprintf(gOutFile, " target_member=\"%s\"\n", member);
1688 fprintf(gOutFile, " target_member_type=");
1689 dumpEscapedString(member_type.c_str());
1690 fprintf(gOutFile, "\n>\n</method_handle>\n");
1691 }
1692}
1693
1694static void dumpCallSite(const DexFile* pDexFile, u4 idx) {
1695 const DexFile::CallSiteIdItem& call_site_id = pDexFile->GetCallSiteId(idx);
1696 CallSiteArrayValueIterator it(*pDexFile, call_site_id);
1697 if (it.Size() < 3) {
Andreas Gampe221d9812018-01-22 17:48:56 -08001698 LOG(ERROR) << "ERROR: Call site " << idx << " has too few values.";
Orion Hodsonc069a302017-01-18 09:23:12 +00001699 return;
1700 }
1701
1702 uint32_t method_handle_idx = static_cast<uint32_t>(it.GetJavaValue().i);
1703 it.Next();
1704 dex::StringIndex method_name_idx = static_cast<dex::StringIndex>(it.GetJavaValue().i);
1705 const char* method_name = pDexFile->StringDataByIdx(method_name_idx);
1706 it.Next();
Orion Hodson16b2adf2018-05-14 08:53:38 +01001707 dex::ProtoIndex method_type_idx = static_cast<dex::ProtoIndex>(it.GetJavaValue().i);
Orion Hodsonc069a302017-01-18 09:23:12 +00001708 const DexFile::ProtoId& method_type_id = pDexFile->GetProtoId(method_type_idx);
1709 std::string method_type = pDexFile->GetProtoSignature(method_type_id).ToString();
1710 it.Next();
1711
1712 if (gOptions.outputFormat == OUTPUT_PLAIN) {
Orion Hodson775224d2017-07-05 11:04:01 +01001713 fprintf(gOutFile, "Call site #%u: // offset %u\n", idx, call_site_id.data_off_);
Orion Hodsonc069a302017-01-18 09:23:12 +00001714 fprintf(gOutFile, " link_argument[0] : %u (MethodHandle)\n", method_handle_idx);
1715 fprintf(gOutFile, " link_argument[1] : %s (String)\n", method_name);
1716 fprintf(gOutFile, " link_argument[2] : %s (MethodType)\n", method_type.c_str());
1717 } else {
Orion Hodson775224d2017-07-05 11:04:01 +01001718 fprintf(gOutFile, "<call_site index=\"%u\" offset=\"%u\">\n", idx, call_site_id.data_off_);
Orion Hodsonc069a302017-01-18 09:23:12 +00001719 fprintf(gOutFile,
1720 "<link_argument index=\"0\" type=\"MethodHandle\" value=\"%u\"/>\n",
1721 method_handle_idx);
1722 fprintf(gOutFile,
1723 "<link_argument index=\"1\" type=\"String\" values=\"%s\"/>\n",
1724 method_name);
1725 fprintf(gOutFile,
1726 "<link_argument index=\"2\" type=\"MethodType\" value=\"%s\"/>\n",
1727 method_type.c_str());
1728 }
1729
1730 size_t argument = 3;
1731 while (it.HasNext()) {
1732 const char* type;
1733 std::string value;
1734 switch (it.GetValueType()) {
1735 case EncodedArrayValueIterator::ValueType::kByte:
1736 type = "byte";
1737 value = android::base::StringPrintf("%u", it.GetJavaValue().b);
1738 break;
1739 case EncodedArrayValueIterator::ValueType::kShort:
1740 type = "short";
1741 value = android::base::StringPrintf("%d", it.GetJavaValue().s);
1742 break;
1743 case EncodedArrayValueIterator::ValueType::kChar:
1744 type = "char";
1745 value = android::base::StringPrintf("%u", it.GetJavaValue().c);
1746 break;
1747 case EncodedArrayValueIterator::ValueType::kInt:
1748 type = "int";
1749 value = android::base::StringPrintf("%d", it.GetJavaValue().i);
1750 break;
1751 case EncodedArrayValueIterator::ValueType::kLong:
1752 type = "long";
1753 value = android::base::StringPrintf("%" PRId64, it.GetJavaValue().j);
1754 break;
1755 case EncodedArrayValueIterator::ValueType::kFloat:
1756 type = "float";
1757 value = android::base::StringPrintf("%g", it.GetJavaValue().f);
1758 break;
1759 case EncodedArrayValueIterator::ValueType::kDouble:
1760 type = "double";
1761 value = android::base::StringPrintf("%g", it.GetJavaValue().d);
1762 break;
1763 case EncodedArrayValueIterator::ValueType::kMethodType: {
1764 type = "MethodType";
Orion Hodson16b2adf2018-05-14 08:53:38 +01001765 dex::ProtoIndex proto_idx = static_cast<dex::ProtoIndex>(it.GetJavaValue().i);
Orion Hodsonc069a302017-01-18 09:23:12 +00001766 const DexFile::ProtoId& proto_id = pDexFile->GetProtoId(proto_idx);
1767 value = pDexFile->GetProtoSignature(proto_id).ToString();
1768 break;
1769 }
1770 case EncodedArrayValueIterator::ValueType::kMethodHandle:
1771 type = "MethodHandle";
1772 value = android::base::StringPrintf("%d", it.GetJavaValue().i);
1773 break;
1774 case EncodedArrayValueIterator::ValueType::kString: {
1775 type = "String";
1776 dex::StringIndex string_idx = static_cast<dex::StringIndex>(it.GetJavaValue().i);
1777 value = pDexFile->StringDataByIdx(string_idx);
1778 break;
1779 }
1780 case EncodedArrayValueIterator::ValueType::kType: {
1781 type = "Class";
1782 dex::TypeIndex type_idx = static_cast<dex::TypeIndex>(it.GetJavaValue().i);
1783 const DexFile::ClassDef* class_def = pDexFile->FindClassDef(type_idx);
1784 value = pDexFile->GetClassDescriptor(*class_def);
1785 value = descriptorClassToDot(value.c_str()).get();
1786 break;
1787 }
1788 case EncodedArrayValueIterator::ValueType::kField:
1789 case EncodedArrayValueIterator::ValueType::kMethod:
1790 case EncodedArrayValueIterator::ValueType::kEnum:
1791 case EncodedArrayValueIterator::ValueType::kArray:
1792 case EncodedArrayValueIterator::ValueType::kAnnotation:
1793 // Unreachable based on current EncodedArrayValueIterator::Next().
Andreas Gampef45d61c2017-06-07 10:29:33 -07001794 UNIMPLEMENTED(FATAL) << " type " << it.GetValueType();
Orion Hodsonc069a302017-01-18 09:23:12 +00001795 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00001796 case EncodedArrayValueIterator::ValueType::kNull:
1797 type = "Null";
1798 value = "null";
1799 break;
1800 case EncodedArrayValueIterator::ValueType::kBoolean:
1801 type = "boolean";
1802 value = it.GetJavaValue().z ? "true" : "false";
1803 break;
1804 }
1805
1806 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1807 fprintf(gOutFile, " link_argument[%zu] : %s (%s)\n", argument, value.c_str(), type);
1808 } else {
1809 fprintf(gOutFile, "<link_argument index=\"%zu\" type=\"%s\" value=", argument, type);
1810 dumpEscapedString(value.c_str());
1811 fprintf(gOutFile, "/>\n");
1812 }
1813
1814 it.Next();
1815 argument++;
1816 }
1817
1818 if (gOptions.outputFormat == OUTPUT_XML) {
1819 fprintf(gOutFile, "</call_site>\n");
1820 }
1821}
1822
Aart Bik69ae54a2015-07-01 14:52:26 -07001823/*
1824 * Dumps the requested sections of the file.
1825 */
Aart Bik7b45a8a2016-10-24 16:07:59 -07001826static void processDexFile(const char* fileName,
1827 const DexFile* pDexFile, size_t i, size_t n) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001828 if (gOptions.verbose) {
Aart Bik7b45a8a2016-10-24 16:07:59 -07001829 fputs("Opened '", gOutFile);
1830 fputs(fileName, gOutFile);
1831 if (n > 1) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001832 fprintf(gOutFile, ":%s", DexFileLoader::GetMultiDexClassesDexName(i).c_str());
Aart Bik7b45a8a2016-10-24 16:07:59 -07001833 }
1834 fprintf(gOutFile, "', DEX version '%.3s'\n", pDexFile->GetHeader().magic_ + 4);
Aart Bik69ae54a2015-07-01 14:52:26 -07001835 }
1836
1837 // Headers.
1838 if (gOptions.showFileHeaders) {
1839 dumpFileHeader(pDexFile);
1840 }
1841
1842 // Open XML context.
1843 if (gOptions.outputFormat == OUTPUT_XML) {
1844 fprintf(gOutFile, "<api>\n");
1845 }
1846
1847 // Iterate over all classes.
1848 char* package = nullptr;
1849 const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
1850 for (u4 i = 0; i < classDefsSize; i++) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001851 dumpClass(pDexFile, i, &package);
1852 } // for
1853
Orion Hodsonc069a302017-01-18 09:23:12 +00001854 // Iterate over all method handles.
1855 for (u4 i = 0; i < pDexFile->NumMethodHandles(); ++i) {
1856 dumpMethodHandle(pDexFile, i);
1857 } // for
1858
1859 // Iterate over all call site ids.
1860 for (u4 i = 0; i < pDexFile->NumCallSiteIds(); ++i) {
1861 dumpCallSite(pDexFile, i);
1862 } // for
1863
Aart Bik69ae54a2015-07-01 14:52:26 -07001864 // Free the last package allocated.
1865 if (package != nullptr) {
1866 fprintf(gOutFile, "</package>\n");
1867 free(package);
1868 }
1869
1870 // Close XML context.
1871 if (gOptions.outputFormat == OUTPUT_XML) {
1872 fprintf(gOutFile, "</api>\n");
1873 }
1874}
1875
1876/*
1877 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
1878 */
1879int processFile(const char* fileName) {
1880 if (gOptions.verbose) {
1881 fprintf(gOutFile, "Processing '%s'...\n", fileName);
1882 }
1883
Nicolas Geoffrayc1d8caa2018-02-27 10:15:14 +00001884 const bool kVerifyChecksum = !gOptions.ignoreBadChecksum;
1885 const bool kVerify = !gOptions.disableVerifier;
1886 std::string content;
Aart Bik69ae54a2015-07-01 14:52:26 -07001887 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
Aart Bikdce50862016-06-10 16:04:03 -07001888 // all of which are Zip archives with "classes.dex" inside.
David Sehr999646d2018-02-16 10:22:33 -08001889 // TODO: add an api to android::base to read a std::vector<uint8_t>.
1890 if (!android::base::ReadFileToString(fileName, &content)) {
1891 LOG(ERROR) << "ReadFileToString failed";
David Sehr5a1f6292018-01-19 11:08:51 -08001892 return -1;
1893 }
1894 const DexFileLoader dex_file_loader;
David Sehr999646d2018-02-16 10:22:33 -08001895 std::string error_msg;
Aart Bik69ae54a2015-07-01 14:52:26 -07001896 std::vector<std::unique_ptr<const DexFile>> dex_files;
David Sehr999646d2018-02-16 10:22:33 -08001897 if (!dex_file_loader.OpenAll(reinterpret_cast<const uint8_t*>(content.data()),
1898 content.size(),
1899 fileName,
Nicolas Geoffrayc1d8caa2018-02-27 10:15:14 +00001900 kVerify,
David Sehr999646d2018-02-16 10:22:33 -08001901 kVerifyChecksum,
1902 &error_msg,
1903 &dex_files)) {
Aart Bik69ae54a2015-07-01 14:52:26 -07001904 // Display returned error message to user. Note that this error behavior
1905 // differs from the error messages shown by the original Dalvik dexdump.
Andreas Gampe221d9812018-01-22 17:48:56 -08001906 LOG(ERROR) << error_msg;
Aart Bik69ae54a2015-07-01 14:52:26 -07001907 return -1;
1908 }
1909
Aart Bik4e149602015-07-09 11:45:28 -07001910 // Success. Either report checksum verification or process
1911 // all dex files found in given file.
Aart Bik69ae54a2015-07-01 14:52:26 -07001912 if (gOptions.checksumOnly) {
1913 fprintf(gOutFile, "Checksum verified\n");
1914 } else {
Aart Bik7b45a8a2016-10-24 16:07:59 -07001915 for (size_t i = 0, n = dex_files.size(); i < n; i++) {
1916 processDexFile(fileName, dex_files[i].get(), i, n);
Aart Bik4e149602015-07-09 11:45:28 -07001917 }
Aart Bik69ae54a2015-07-01 14:52:26 -07001918 }
1919 return 0;
1920}
1921
1922} // namespace art