blob: f55dccd069f8a714a31b519ef2b4973b3121022c [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
20 * based on Art functions in libart instead. The output is identical to
21 * the original for correct DEX files. Error messages may differ, however.
22 * 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
30 * - no "value" on fields
31 * - no parameter names
32 * - no generic signatures on parameters, e.g. type="java.lang.Class<?>"
33 * - class shows declared fields and methods; does not show inherited fields
34 */
35
36#include "dexdump.h"
37
38#include <inttypes.h>
39#include <stdio.h>
40
41#include <memory>
42#include <vector>
43
44#include "dex_file-inl.h"
45#include "dex_instruction-inl.h"
46
47namespace art {
48
49/*
50 * Options parsed in main driver.
51 */
52struct Options gOptions;
53
54/*
55 * Output file. Defaults to stdout, but tests can modify.
56 */
57FILE* gOutFile = stdout;
58
59/*
60 * Data types that match the definitions in the VM specification.
61 */
62typedef uint8_t u1;
63typedef uint16_t u2;
64typedef uint32_t u4;
65typedef uint64_t u8;
66typedef int8_t s1;
67typedef int16_t s2;
68typedef int32_t s4;
69typedef int64_t s8;
70
71/*
72 * Basic information about a field or a method.
73 */
74struct FieldMethodInfo {
75 const char* classDescriptor;
76 const char* name;
77 const char* signature;
78};
79
80/*
81 * Flags for use with createAccessFlagStr().
82 */
83enum AccessFor {
84 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
85};
86const int kNumFlags = 18;
87
88/*
89 * Gets 2 little-endian bytes.
90 */
91static inline u2 get2LE(unsigned char const* pSrc) {
92 return pSrc[0] | (pSrc[1] << 8);
93}
94
95/*
96 * Converts a single-character primitive type into human-readable form.
97 */
98static const char* primitiveTypeLabel(char typeChar) {
99 switch (typeChar) {
100 case 'B': return "byte";
101 case 'C': return "char";
102 case 'D': return "double";
103 case 'F': return "float";
104 case 'I': return "int";
105 case 'J': return "long";
106 case 'S': return "short";
107 case 'V': return "void";
108 case 'Z': return "boolean";
109 default: return "UNKNOWN";
110 } // switch
111}
112
113/*
114 * Converts a type descriptor to human-readable "dotted" form. For
115 * example, "Ljava/lang/String;" becomes "java.lang.String", and
116 * "[I" becomes "int[]". Also converts '$' to '.', which means this
117 * form can't be converted back to a descriptor.
118 */
119static char* descriptorToDot(const char* str) {
120 int targetLen = strlen(str);
121 int offset = 0;
122
123 // Strip leading [s; will be added to end.
124 while (targetLen > 1 && str[offset] == '[') {
125 offset++;
126 targetLen--;
127 } // while
128
129 const int arrayDepth = offset;
130
131 if (targetLen == 1) {
132 // Primitive type.
133 str = primitiveTypeLabel(str[offset]);
134 offset = 0;
135 targetLen = strlen(str);
136 } else {
137 // Account for leading 'L' and trailing ';'.
138 if (targetLen >= 2 && str[offset] == 'L' &&
139 str[offset + targetLen - 1] == ';') {
140 targetLen -= 2;
141 offset++;
142 }
143 }
144
145 // Copy class name over.
146 char* newStr = reinterpret_cast<char*>(
147 malloc(targetLen + arrayDepth * 2 + 1));
148 int i = 0;
149 for (; i < targetLen; i++) {
150 const char ch = str[offset + i];
151 newStr[i] = (ch == '/' || ch == '$') ? '.' : ch;
152 } // for
153
154 // Add the appropriate number of brackets for arrays.
155 for (int j = 0; j < arrayDepth; j++) {
156 newStr[i++] = '[';
157 newStr[i++] = ']';
158 } // for
159
160 newStr[i] = '\0';
161 return newStr;
162}
163
164/*
165 * Converts the class name portion of a type descriptor to human-readable
166 * "dotted" form.
167 *
168 * Returns a newly-allocated string.
169 */
170static char* descriptorClassToDot(const char* str) {
171 // Reduce to just the class name, trimming trailing ';'.
172 const char* lastSlash = strrchr(str, '/');
173 if (lastSlash == nullptr) {
174 lastSlash = str + 1; // start past 'L'
175 } else {
176 lastSlash++; // start past '/'
177 }
178
179 char* newStr = strdup(lastSlash);
180 newStr[strlen(lastSlash) - 1] = '\0';
181 for (char* cp = newStr; *cp != '\0'; cp++) {
182 if (*cp == '$') {
183 *cp = '.';
184 }
185 } // for
186 return newStr;
187}
188
189/*
190 * Returns a quoted string representing the boolean value.
191 */
192static const char* quotedBool(bool val) {
193 return val ? "\"true\"" : "\"false\"";
194}
195
196/*
197 * Returns a quoted string representing the access flags.
198 */
199static const char* quotedVisibility(u4 accessFlags) {
200 if (accessFlags & kAccPublic) {
201 return "\"public\"";
202 } else if (accessFlags & kAccProtected) {
203 return "\"protected\"";
204 } else if (accessFlags & kAccPrivate) {
205 return "\"private\"";
206 } else {
207 return "\"package\"";
208 }
209}
210
211/*
212 * Counts the number of '1' bits in a word.
213 */
214static int countOnes(u4 val) {
215 val = val - ((val >> 1) & 0x55555555);
216 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
217 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
218}
219
220/*
221 * Creates a new string with human-readable access flags.
222 *
223 * In the base language the access_flags fields are type u2; in Dalvik
224 * they're u4.
225 */
226static char* createAccessFlagStr(u4 flags, AccessFor forWhat) {
227 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
228 {
229 "PUBLIC", /* 0x00001 */
230 "PRIVATE", /* 0x00002 */
231 "PROTECTED", /* 0x00004 */
232 "STATIC", /* 0x00008 */
233 "FINAL", /* 0x00010 */
234 "?", /* 0x00020 */
235 "?", /* 0x00040 */
236 "?", /* 0x00080 */
237 "?", /* 0x00100 */
238 "INTERFACE", /* 0x00200 */
239 "ABSTRACT", /* 0x00400 */
240 "?", /* 0x00800 */
241 "SYNTHETIC", /* 0x01000 */
242 "ANNOTATION", /* 0x02000 */
243 "ENUM", /* 0x04000 */
244 "?", /* 0x08000 */
245 "VERIFIED", /* 0x10000 */
246 "OPTIMIZED", /* 0x20000 */
247 }, {
248 "PUBLIC", /* 0x00001 */
249 "PRIVATE", /* 0x00002 */
250 "PROTECTED", /* 0x00004 */
251 "STATIC", /* 0x00008 */
252 "FINAL", /* 0x00010 */
253 "SYNCHRONIZED", /* 0x00020 */
254 "BRIDGE", /* 0x00040 */
255 "VARARGS", /* 0x00080 */
256 "NATIVE", /* 0x00100 */
257 "?", /* 0x00200 */
258 "ABSTRACT", /* 0x00400 */
259 "STRICT", /* 0x00800 */
260 "SYNTHETIC", /* 0x01000 */
261 "?", /* 0x02000 */
262 "?", /* 0x04000 */
263 "MIRANDA", /* 0x08000 */
264 "CONSTRUCTOR", /* 0x10000 */
265 "DECLARED_SYNCHRONIZED", /* 0x20000 */
266 }, {
267 "PUBLIC", /* 0x00001 */
268 "PRIVATE", /* 0x00002 */
269 "PROTECTED", /* 0x00004 */
270 "STATIC", /* 0x00008 */
271 "FINAL", /* 0x00010 */
272 "?", /* 0x00020 */
273 "VOLATILE", /* 0x00040 */
274 "TRANSIENT", /* 0x00080 */
275 "?", /* 0x00100 */
276 "?", /* 0x00200 */
277 "?", /* 0x00400 */
278 "?", /* 0x00800 */
279 "SYNTHETIC", /* 0x01000 */
280 "?", /* 0x02000 */
281 "ENUM", /* 0x04000 */
282 "?", /* 0x08000 */
283 "?", /* 0x10000 */
284 "?", /* 0x20000 */
285 },
286 };
287
288 // Allocate enough storage to hold the expected number of strings,
289 // plus a space between each. We over-allocate, using the longest
290 // string above as the base metric.
291 const int kLongest = 21; // The strlen of longest string above.
292 const int count = countOnes(flags);
293 char* str;
294 char* cp;
295 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
296
297 for (int i = 0; i < kNumFlags; i++) {
298 if (flags & 0x01) {
299 const char* accessStr = kAccessStrings[forWhat][i];
300 const int len = strlen(accessStr);
301 if (cp != str) {
302 *cp++ = ' ';
303 }
304 memcpy(cp, accessStr, len);
305 cp += len;
306 }
307 flags >>= 1;
308 } // for
309
310 *cp = '\0';
311 return str;
312}
313
314/*
315 * Copies character data from "data" to "out", converting non-ASCII values
316 * to fprintf format chars or an ASCII filler ('.' or '?').
317 *
318 * The output buffer must be able to hold (2*len)+1 bytes. The result is
319 * NULL-terminated.
320 */
321static void asciify(char* out, const unsigned char* data, size_t len) {
322 while (len--) {
323 if (*data < 0x20) {
324 // Could do more here, but we don't need them yet.
325 switch (*data) {
326 case '\0':
327 *out++ = '\\';
328 *out++ = '0';
329 break;
330 case '\n':
331 *out++ = '\\';
332 *out++ = 'n';
333 break;
334 default:
335 *out++ = '.';
336 break;
337 } // switch
338 } else if (*data >= 0x80) {
339 *out++ = '?';
340 } else {
341 *out++ = *data;
342 }
343 data++;
344 } // while
345 *out = '\0';
346}
347
348/*
349 * Dumps the file header.
350 *
351 * Note that some of the : are misaligned on purpose to preserve
352 * the exact output of the original Dalvik dexdump.
353 */
354static void dumpFileHeader(const DexFile* pDexFile) {
355 const DexFile::Header& pHeader = pDexFile->GetHeader();
356 char sanitized[sizeof(pHeader.magic_) * 2 + 1];
357 fprintf(gOutFile, "DEX file header:\n");
358 asciify(sanitized, pHeader.magic_, sizeof(pHeader.magic_));
359 fprintf(gOutFile, "magic : '%s'\n", sanitized);
360 fprintf(gOutFile, "checksum : %08x\n", pHeader.checksum_);
361 fprintf(gOutFile, "signature : %02x%02x...%02x%02x\n",
362 pHeader.signature_[0], pHeader.signature_[1],
363 pHeader.signature_[DexFile::kSha1DigestSize - 2],
364 pHeader.signature_[DexFile::kSha1DigestSize - 1]);
365 fprintf(gOutFile, "file_size : %d\n", pHeader.file_size_);
366 fprintf(gOutFile, "header_size : %d\n", pHeader.header_size_);
367 fprintf(gOutFile, "link_size : %d\n", pHeader.link_size_);
368 fprintf(gOutFile, "link_off : %d (0x%06x)\n",
369 pHeader.link_off_, pHeader.link_off_);
370 fprintf(gOutFile, "string_ids_size : %d\n", pHeader.string_ids_size_);
371 fprintf(gOutFile, "string_ids_off : %d (0x%06x)\n",
372 pHeader.string_ids_off_, pHeader.string_ids_off_);
373 fprintf(gOutFile, "type_ids_size : %d\n", pHeader.type_ids_size_);
374 fprintf(gOutFile, "type_ids_off : %d (0x%06x)\n",
375 pHeader.type_ids_off_, pHeader.type_ids_off_);
376 fprintf(gOutFile, "proto_ids_size : %d\n", pHeader.proto_ids_size_);
377 fprintf(gOutFile, "proto_ids_off : %d (0x%06x)\n",
378 pHeader.proto_ids_off_, pHeader.proto_ids_off_);
379 fprintf(gOutFile, "field_ids_size : %d\n", pHeader.field_ids_size_);
380 fprintf(gOutFile, "field_ids_off : %d (0x%06x)\n",
381 pHeader.field_ids_off_, pHeader.field_ids_off_);
382 fprintf(gOutFile, "method_ids_size : %d\n", pHeader.method_ids_size_);
383 fprintf(gOutFile, "method_ids_off : %d (0x%06x)\n",
384 pHeader.method_ids_off_, pHeader.method_ids_off_);
385 fprintf(gOutFile, "class_defs_size : %d\n", pHeader.class_defs_size_);
386 fprintf(gOutFile, "class_defs_off : %d (0x%06x)\n",
387 pHeader.class_defs_off_, pHeader.class_defs_off_);
388 fprintf(gOutFile, "data_size : %d\n", pHeader.data_size_);
389 fprintf(gOutFile, "data_off : %d (0x%06x)\n\n",
390 pHeader.data_off_, pHeader.data_off_);
391}
392
393/*
394 * Dumps a class_def_item.
395 */
396static void dumpClassDef(const DexFile* pDexFile, int idx) {
397 // General class information.
398 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
399 fprintf(gOutFile, "Class #%d header:\n", idx);
400 fprintf(gOutFile, "class_idx : %d\n", pClassDef.class_idx_);
401 fprintf(gOutFile, "access_flags : %d (0x%04x)\n",
402 pClassDef.access_flags_, pClassDef.access_flags_);
403 fprintf(gOutFile, "superclass_idx : %d\n", pClassDef.superclass_idx_);
404 fprintf(gOutFile, "interfaces_off : %d (0x%06x)\n",
405 pClassDef.interfaces_off_, pClassDef.interfaces_off_);
406 fprintf(gOutFile, "source_file_idx : %d\n", pClassDef.source_file_idx_);
407 fprintf(gOutFile, "annotations_off : %d (0x%06x)\n",
408 pClassDef.annotations_off_, pClassDef.annotations_off_);
409 fprintf(gOutFile, "class_data_off : %d (0x%06x)\n",
410 pClassDef.class_data_off_, pClassDef.class_data_off_);
411
412 // Fields and methods.
413 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
414 if (pEncodedData != nullptr) {
415 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
416 fprintf(gOutFile, "static_fields_size : %d\n", pClassData.NumStaticFields());
417 fprintf(gOutFile, "instance_fields_size: %d\n", pClassData.NumInstanceFields());
418 fprintf(gOutFile, "direct_methods_size : %d\n", pClassData.NumDirectMethods());
419 fprintf(gOutFile, "virtual_methods_size: %d\n", pClassData.NumVirtualMethods());
420 } else {
421 fprintf(gOutFile, "static_fields_size : 0\n");
422 fprintf(gOutFile, "instance_fields_size: 0\n");
423 fprintf(gOutFile, "direct_methods_size : 0\n");
424 fprintf(gOutFile, "virtual_methods_size: 0\n");
425 }
426 fprintf(gOutFile, "\n");
427}
428
429/*
430 * Dumps an interface that a class declares to implement.
431 */
432static void dumpInterface(const DexFile* pDexFile, const DexFile::TypeItem& pTypeItem, int i) {
433 const char* interfaceName = pDexFile->StringByTypeIdx(pTypeItem.type_idx_);
434 if (gOptions.outputFormat == OUTPUT_PLAIN) {
435 fprintf(gOutFile, " #%d : '%s'\n", i, interfaceName);
436 } else {
437 char* dotted = descriptorToDot(interfaceName);
438 fprintf(gOutFile, "<implements name=\"%s\">\n</implements>\n", dotted);
439 free(dotted);
440 }
441}
442
443/*
444 * Dumps the catches table associated with the code.
445 */
446static void dumpCatches(const DexFile* pDexFile, const DexFile::CodeItem* pCode) {
447 const u4 triesSize = pCode->tries_size_;
448
449 // No catch table.
450 if (triesSize == 0) {
451 fprintf(gOutFile, " catches : (none)\n");
452 return;
453 }
454
455 // Dump all table entries.
456 fprintf(gOutFile, " catches : %d\n", triesSize);
457 for (u4 i = 0; i < triesSize; i++) {
458 const DexFile::TryItem* pTry = pDexFile->GetTryItems(*pCode, i);
459 const u4 start = pTry->start_addr_;
460 const u4 end = start + pTry->insn_count_;
461 fprintf(gOutFile, " 0x%04x - 0x%04x\n", start, end);
462 for (CatchHandlerIterator it(*pCode, *pTry); it.HasNext(); it.Next()) {
463 const u2 tidx = it.GetHandlerTypeIndex();
464 const char* descriptor =
465 (tidx == DexFile::kDexNoIndex16) ? "<any>" : pDexFile->StringByTypeIdx(tidx);
466 fprintf(gOutFile, " %s -> 0x%04x\n", descriptor, it.GetHandlerAddress());
467 } // for
468 } // for
469}
470
471/*
472 * Callback for dumping each positions table entry.
473 */
474static bool dumpPositionsCb(void* /*context*/, u4 address, u4 lineNum) {
475 fprintf(gOutFile, " 0x%04x line=%d\n", address, lineNum);
476 return false;
477}
478
479/*
480 * Callback for dumping locals table entry.
481 */
482static void dumpLocalsCb(void* /*context*/, u2 slot, u4 startAddress, u4 endAddress,
483 const char* name, const char* descriptor, const char* signature) {
484 fprintf(gOutFile, " 0x%04x - 0x%04x reg=%d %s %s %s\n",
485 startAddress, endAddress, slot, name, descriptor, signature);
486}
487
488/*
489 * Helper for dumpInstruction(), which builds the string
490 * representation for the index in the given instruction. This will
491 * first try to use the given buffer, but if the result won't fit,
492 * then this will allocate a new buffer to hold the result. A pointer
493 * to the buffer which holds the full result is always returned, and
494 * this can be compared with the one passed in, to see if the result
495 * needs to be free()d.
496 */
497static char* indexString(const DexFile* pDexFile,
498 const Instruction* pDecInsn, char* buf, size_t bufSize) {
499 // Determine index and width of the string.
500 u4 index = 0;
501 u4 width = 4;
502 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
503 // SOME NOT SUPPORTED:
504 // case Instruction::k20bc:
505 case Instruction::k21c:
506 case Instruction::k35c:
507 // case Instruction::k35ms:
508 case Instruction::k3rc:
509 // case Instruction::k3rms:
510 // case Instruction::k35mi:
511 // case Instruction::k3rmi:
512 index = pDecInsn->VRegB();
513 width = 4;
514 break;
515 case Instruction::k31c:
516 index = pDecInsn->VRegB();
517 width = 8;
518 break;
519 case Instruction::k22c:
520 // case Instruction::k22cs:
521 index = pDecInsn->VRegC();
522 width = 4;
523 break;
524 default:
525 break;
526 } // switch
527
528 // Determine index type.
529 size_t outSize = 0;
530 switch (Instruction::IndexTypeOf(pDecInsn->Opcode())) {
531 case Instruction::kIndexUnknown:
532 // This function should never get called for this type, but do
533 // something sensible here, just to help with debugging.
534 outSize = snprintf(buf, bufSize, "<unknown-index>");
535 break;
536 case Instruction::kIndexNone:
537 // This function should never get called for this type, but do
538 // something sensible here, just to help with debugging.
539 outSize = snprintf(buf, bufSize, "<no-index>");
540 break;
541 case Instruction::kIndexTypeRef:
542 if (index < pDexFile->GetHeader().type_ids_size_) {
543 const char* tp = pDexFile->StringByTypeIdx(index);
544 outSize = snprintf(buf, bufSize, "%s // type@%0*x", tp, width, index);
545 } else {
546 outSize = snprintf(buf, bufSize, "<type?> // type@%0*x", width, index);
547 }
548 break;
549 case Instruction::kIndexStringRef:
550 if (index < pDexFile->GetHeader().string_ids_size_) {
551 const char* st = pDexFile->StringDataByIdx(index);
552 outSize = snprintf(buf, bufSize, "\"%s\" // string@%0*x", st, width, index);
553 } else {
554 outSize = snprintf(buf, bufSize, "<string?> // string@%0*x", width, index);
555 }
556 break;
557 case Instruction::kIndexMethodRef:
558 if (index < pDexFile->GetHeader().method_ids_size_) {
559 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(index);
560 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
561 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
562 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
563 outSize = snprintf(buf, bufSize, "%s.%s:%s // method@%0*x",
564 backDescriptor, name, signature.ToString().c_str(), width, index);
565 } else {
566 outSize = snprintf(buf, bufSize, "<method?> // method@%0*x", width, index);
567 }
568 break;
569 case Instruction::kIndexFieldRef:
570 if (index < pDexFile->GetHeader().field_ids_size_) {
571 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(index);
572 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
573 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
574 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
575 outSize = snprintf(buf, bufSize, "%s.%s:%s // field@%0*x",
576 backDescriptor, name, typeDescriptor, width, index);
577 } else {
578 outSize = snprintf(buf, bufSize, "<field?> // field@%0*x", width, index);
579 }
580 break;
581 case Instruction::kIndexVtableOffset:
582 outSize = snprintf(buf, bufSize, "[%0*x] // vtable #%0*x",
583 width, index, width, index);
584 break;
585 case Instruction::kIndexFieldOffset:
586 outSize = snprintf(buf, bufSize, "[obj+%0*x]", width, index);
587 break;
588 // SOME NOT SUPPORTED:
589 // case Instruction::kIndexVaries:
590 // case Instruction::kIndexInlineMethod:
591 default:
592 outSize = snprintf(buf, bufSize, "<?>");
593 break;
594 } // switch
595
596 // Determine success of string construction.
597 if (outSize >= bufSize) {
598 // The buffer wasn't big enough; allocate and retry. Note:
599 // snprintf() doesn't count the '\0' as part of its returned
600 // size, so we add explicit space for it here.
601 outSize++;
602 buf = reinterpret_cast<char*>(malloc(outSize));
603 if (buf == nullptr) {
604 return nullptr;
605 }
606 return indexString(pDexFile, pDecInsn, buf, outSize);
607 }
608 return buf;
609}
610
611/*
612 * Dumps a single instruction.
613 */
614static void dumpInstruction(const DexFile* pDexFile,
615 const DexFile::CodeItem* pCode,
616 u4 codeOffset, u4 insnIdx, u4 insnWidth,
617 const Instruction* pDecInsn) {
618 // Address of instruction (expressed as byte offset).
619 fprintf(gOutFile, "%06x:", codeOffset + 0x10 + insnIdx * 2);
620
621 // Dump (part of) raw bytes.
622 const u2* insns = pCode->insns_;
623 for (u4 i = 0; i < 8; i++) {
624 if (i < insnWidth) {
625 if (i == 7) {
626 fprintf(gOutFile, " ... ");
627 } else {
628 // Print 16-bit value in little-endian order.
629 const u1* bytePtr = (const u1*) &insns[insnIdx + i];
630 fprintf(gOutFile, " %02x%02x", bytePtr[0], bytePtr[1]);
631 }
632 } else {
633 fputs(" ", gOutFile);
634 }
635 } // for
636
637 // Dump pseudo-instruction or opcode.
638 if (pDecInsn->Opcode() == Instruction::NOP) {
639 const u2 instr = get2LE((const u1*) &insns[insnIdx]);
640 if (instr == Instruction::kPackedSwitchSignature) {
641 fprintf(gOutFile, "|%04x: packed-switch-data (%d units)", insnIdx, insnWidth);
642 } else if (instr == Instruction::kSparseSwitchSignature) {
643 fprintf(gOutFile, "|%04x: sparse-switch-data (%d units)", insnIdx, insnWidth);
644 } else if (instr == Instruction::kArrayDataSignature) {
645 fprintf(gOutFile, "|%04x: array-data (%d units)", insnIdx, insnWidth);
646 } else {
647 fprintf(gOutFile, "|%04x: nop // spacer", insnIdx);
648 }
649 } else {
650 fprintf(gOutFile, "|%04x: %s", insnIdx, pDecInsn->Name());
651 }
652
653 // Set up additional argument.
654 char indexBufChars[200];
655 char *indexBuf = indexBufChars;
656 if (Instruction::IndexTypeOf(pDecInsn->Opcode()) != Instruction::kIndexNone) {
657 indexBuf = indexString(pDexFile, pDecInsn,
658 indexBufChars, sizeof(indexBufChars));
659 }
660
661 // Dump the instruction.
662 //
663 // NOTE: pDecInsn->DumpString(pDexFile) differs too much from original.
664 //
665 switch (Instruction::FormatOf(pDecInsn->Opcode())) {
666 case Instruction::k10x: // op
667 break;
668 case Instruction::k12x: // op vA, vB
669 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
670 break;
671 case Instruction::k11n: // op vA, #+B
672 fprintf(gOutFile, " v%d, #int %d // #%x",
673 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u1)pDecInsn->VRegB());
674 break;
675 case Instruction::k11x: // op vAA
676 fprintf(gOutFile, " v%d", pDecInsn->VRegA());
677 break;
678 case Instruction::k10t: // op +AA
679 case Instruction::k20t: // op +AAAA
680 {
681 const s4 targ = (s4) pDecInsn->VRegA();
682 fprintf(gOutFile, " %04x // %c%04x",
683 insnIdx + targ,
684 (targ < 0) ? '-' : '+',
685 (targ < 0) ? -targ : targ);
686 }
687 break;
688 case Instruction::k22x: // op vAA, vBBBB
689 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
690 break;
691 case Instruction::k21t: // op vAA, +BBBB
692 {
693 const s4 targ = (s4) pDecInsn->VRegB();
694 fprintf(gOutFile, " v%d, %04x // %c%04x", pDecInsn->VRegA(),
695 insnIdx + targ,
696 (targ < 0) ? '-' : '+',
697 (targ < 0) ? -targ : targ);
698 }
699 break;
700 case Instruction::k21s: // op vAA, #+BBBB
701 fprintf(gOutFile, " v%d, #int %d // #%x",
702 pDecInsn->VRegA(), (s4) pDecInsn->VRegB(), (u2)pDecInsn->VRegB());
703 break;
704 case Instruction::k21h: // op vAA, #+BBBB0000[00000000]
705 // The printed format varies a bit based on the actual opcode.
706 if (pDecInsn->Opcode() == Instruction::CONST_HIGH16) {
707 const s4 value = pDecInsn->VRegB() << 16;
708 fprintf(gOutFile, " v%d, #int %d // #%x",
709 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
710 } else {
711 const s8 value = ((s8) pDecInsn->VRegB()) << 48;
712 fprintf(gOutFile, " v%d, #long %" PRId64 " // #%x",
713 pDecInsn->VRegA(), value, (u2) pDecInsn->VRegB());
714 }
715 break;
716 case Instruction::k21c: // op vAA, thing@BBBB
717 case Instruction::k31c: // op vAA, thing@BBBBBBBB
718 fprintf(gOutFile, " v%d, %s", pDecInsn->VRegA(), indexBuf);
719 break;
720 case Instruction::k23x: // op vAA, vBB, vCC
721 fprintf(gOutFile, " v%d, v%d, v%d",
722 pDecInsn->VRegA(), pDecInsn->VRegB(), pDecInsn->VRegC());
723 break;
724 case Instruction::k22b: // op vAA, vBB, #+CC
725 fprintf(gOutFile, " v%d, v%d, #int %d // #%02x",
726 pDecInsn->VRegA(), pDecInsn->VRegB(),
727 (s4) pDecInsn->VRegC(), (u1) pDecInsn->VRegC());
728 break;
729 case Instruction::k22t: // op vA, vB, +CCCC
730 {
731 const s4 targ = (s4) pDecInsn->VRegC();
732 fprintf(gOutFile, " v%d, v%d, %04x // %c%04x",
733 pDecInsn->VRegA(), pDecInsn->VRegB(),
734 insnIdx + targ,
735 (targ < 0) ? '-' : '+',
736 (targ < 0) ? -targ : targ);
737 }
738 break;
739 case Instruction::k22s: // op vA, vB, #+CCCC
740 fprintf(gOutFile, " v%d, v%d, #int %d // #%04x",
741 pDecInsn->VRegA(), pDecInsn->VRegB(),
742 (s4) pDecInsn->VRegC(), (u2) pDecInsn->VRegC());
743 break;
744 case Instruction::k22c: // op vA, vB, thing@CCCC
745 // NOT SUPPORTED:
746 // case Instruction::k22cs: // [opt] op vA, vB, field offset CCCC
747 fprintf(gOutFile, " v%d, v%d, %s",
748 pDecInsn->VRegA(), pDecInsn->VRegB(), indexBuf);
749 break;
750 case Instruction::k30t:
751 fprintf(gOutFile, " #%08x", pDecInsn->VRegA());
752 break;
753 case Instruction::k31i: // op vAA, #+BBBBBBBB
754 {
755 // This is often, but not always, a float.
756 union {
757 float f;
758 u4 i;
759 } conv;
760 conv.i = pDecInsn->VRegB();
761 fprintf(gOutFile, " v%d, #float %f // #%08x",
762 pDecInsn->VRegA(), conv.f, pDecInsn->VRegB());
763 }
764 break;
765 case Instruction::k31t: // op vAA, offset +BBBBBBBB
766 fprintf(gOutFile, " v%d, %08x // +%08x",
767 pDecInsn->VRegA(), insnIdx + pDecInsn->VRegB(), pDecInsn->VRegB());
768 break;
769 case Instruction::k32x: // op vAAAA, vBBBB
770 fprintf(gOutFile, " v%d, v%d", pDecInsn->VRegA(), pDecInsn->VRegB());
771 break;
772 case Instruction::k35c: // op {vC, vD, vE, vF, vG}, thing@BBBB
773 // NOT SUPPORTED:
774 // case Instruction::k35ms: // [opt] invoke-virtual+super
775 // case Instruction::k35mi: // [opt] inline invoke
776 {
777 u4 arg[5];
778 pDecInsn->GetVarArgs(arg);
779 fputs(" {", gOutFile);
780 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
781 if (i == 0) {
782 fprintf(gOutFile, "v%d", arg[i]);
783 } else {
784 fprintf(gOutFile, ", v%d", arg[i]);
785 }
786 } // for
787 fprintf(gOutFile, "}, %s", indexBuf);
788 }
789 break;
790 case Instruction::k3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB
791 // NOT SUPPORTED:
792 // case Instruction::k3rms: // [opt] invoke-virtual+super/range
793 // case Instruction::k3rmi: // [opt] execute-inline/range
794 {
795 // This doesn't match the "dx" output when some of the args are
796 // 64-bit values -- dx only shows the first register.
797 fputs(" {", gOutFile);
798 for (int i = 0, n = pDecInsn->VRegA(); i < n; i++) {
799 if (i == 0) {
800 fprintf(gOutFile, "v%d", pDecInsn->VRegC() + i);
801 } else {
802 fprintf(gOutFile, ", v%d", pDecInsn->VRegC() + i);
803 }
804 } // for
805 fprintf(gOutFile, "}, %s", indexBuf);
806 }
807 break;
808 case Instruction::k51l: // op vAA, #+BBBBBBBBBBBBBBBB
809 {
810 // This is often, but not always, a double.
811 union {
812 double d;
813 u8 j;
814 } conv;
815 conv.j = pDecInsn->WideVRegB();
816 fprintf(gOutFile, " v%d, #double %f // #%016" PRIx64,
817 pDecInsn->VRegA(), conv.d, pDecInsn->WideVRegB());
818 }
819 break;
820 // NOT SUPPORTED:
821 // case Instruction::k00x: // unknown op or breakpoint
822 // break;
823 default:
824 fprintf(gOutFile, " ???");
825 break;
826 } // switch
827
828 fputc('\n', gOutFile);
829
830 if (indexBuf != indexBufChars) {
831 free(indexBuf);
832 }
833}
834
835/*
836 * Dumps a bytecode disassembly.
837 */
838static void dumpBytecodes(const DexFile* pDexFile, u4 idx,
839 const DexFile::CodeItem* pCode, u4 codeOffset) {
840 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
841 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
842 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
843 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
844
845 // Generate header.
846 char* tmp = descriptorToDot(backDescriptor);
847 fprintf(gOutFile, "%06x: "
848 "|[%06x] %s.%s:%s\n",
849 codeOffset, codeOffset, tmp, name, signature.ToString().c_str());
850 free(tmp);
851
852 // Iterate over all instructions.
853 const u2* insns = pCode->insns_;
854 for (u4 insnIdx = 0; insnIdx < pCode->insns_size_in_code_units_;) {
855 const Instruction* instruction = Instruction::At(&insns[insnIdx]);
856 const u4 insnWidth = instruction->SizeInCodeUnits();
857 if (insnWidth == 0) {
858 fprintf(stderr, "GLITCH: zero-width instruction at idx=0x%04x\n", insnIdx);
859 break;
860 }
861 dumpInstruction(pDexFile, pCode, codeOffset, insnIdx, insnWidth, instruction);
862 insnIdx += insnWidth;
863 } // for
864}
865
866/*
867 * Dumps code of a method.
868 */
869static void dumpCode(const DexFile* pDexFile, u4 idx, u4 flags,
870 const DexFile::CodeItem* pCode, u4 codeOffset) {
871 fprintf(gOutFile, " registers : %d\n", pCode->registers_size_);
872 fprintf(gOutFile, " ins : %d\n", pCode->ins_size_);
873 fprintf(gOutFile, " outs : %d\n", pCode->outs_size_);
874 fprintf(gOutFile, " insns size : %d 16-bit code units\n",
875 pCode->insns_size_in_code_units_);
876
877 // Bytecode disassembly, if requested.
878 if (gOptions.disassemble) {
879 dumpBytecodes(pDexFile, idx, pCode, codeOffset);
880 }
881
882 // Try-catch blocks.
883 dumpCatches(pDexFile, pCode);
884
885 // Positions and locals table in the debug info.
886 bool is_static = (flags & kAccStatic) != 0;
887 fprintf(gOutFile, " positions : \n");
888 pDexFile->DecodeDebugInfo(
889 pCode, is_static, idx, dumpPositionsCb, nullptr, nullptr);
890 fprintf(gOutFile, " locals : \n");
891 pDexFile->DecodeDebugInfo(
892 pCode, is_static, idx, nullptr, dumpLocalsCb, nullptr);
893}
894
895/*
896 * Dumps a method.
897 */
898static void dumpMethod(const DexFile* pDexFile, u4 idx, u4 flags,
899 const DexFile::CodeItem* pCode, u4 codeOffset, int i) {
900 // Bail for anything private if export only requested.
901 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
902 return;
903 }
904
905 const DexFile::MethodId& pMethodId = pDexFile->GetMethodId(idx);
906 const char* name = pDexFile->StringDataByIdx(pMethodId.name_idx_);
907 const Signature signature = pDexFile->GetMethodSignature(pMethodId);
908 char* typeDescriptor = strdup(signature.ToString().c_str());
909 const char* backDescriptor = pDexFile->StringByTypeIdx(pMethodId.class_idx_);
910 char* accessStr = createAccessFlagStr(flags, kAccessForMethod);
911
912 if (gOptions.outputFormat == OUTPUT_PLAIN) {
913 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
914 fprintf(gOutFile, " name : '%s'\n", name);
915 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
916 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
917 if (pCode == nullptr) {
918 fprintf(gOutFile, " code : (none)\n");
919 } else {
920 fprintf(gOutFile, " code -\n");
921 dumpCode(pDexFile, idx, flags, pCode, codeOffset);
922 }
923 if (gOptions.disassemble) {
924 fputc('\n', gOutFile);
925 }
926 } else if (gOptions.outputFormat == OUTPUT_XML) {
927 const bool constructor = (name[0] == '<');
928
929 // Method name and prototype.
930 if (constructor) {
931 char* tmp = descriptorClassToDot(backDescriptor);
932 fprintf(gOutFile, "<constructor name=\"%s\"\n", tmp);
933 free(tmp);
934 tmp = descriptorToDot(backDescriptor);
935 fprintf(gOutFile, " type=\"%s\"\n", tmp);
936 free(tmp);
937 } else {
938 fprintf(gOutFile, "<method name=\"%s\"\n", name);
939 const char* returnType = strrchr(typeDescriptor, ')');
940 if (returnType == nullptr) {
941 fprintf(stderr, "bad method type descriptor '%s'\n", typeDescriptor);
942 goto bail;
943 }
944 char* tmp = descriptorToDot(returnType+1);
945 fprintf(gOutFile, " return=\"%s\"\n", tmp);
946 free(tmp);
947 fprintf(gOutFile, " abstract=%s\n", quotedBool((flags & kAccAbstract) != 0));
948 fprintf(gOutFile, " native=%s\n", quotedBool((flags & kAccNative) != 0));
949 fprintf(gOutFile, " synchronized=%s\n", quotedBool(
950 (flags & (kAccSynchronized | kAccDeclaredSynchronized)) != 0));
951 }
952
953 // Additional method flags.
954 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
955 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
956 // The "deprecated=" not knowable w/o parsing annotations.
957 fprintf(gOutFile, " visibility=%s\n>\n", quotedVisibility(flags));
958
959 // Parameters.
960 if (typeDescriptor[0] != '(') {
961 fprintf(stderr, "ERROR: bad descriptor '%s'\n", typeDescriptor);
962 goto bail;
963 }
964 char* tmpBuf = reinterpret_cast<char*>(malloc(strlen(typeDescriptor) + 1));
965 const char* base = typeDescriptor + 1;
966 int argNum = 0;
967 while (*base != ')') {
968 char* cp = tmpBuf;
969 while (*base == '[') {
970 *cp++ = *base++;
971 }
972 if (*base == 'L') {
973 // Copy through ';'.
974 do {
975 *cp = *base++;
976 } while (*cp++ != ';');
977 } else {
978 // Primitive char, copy it.
979 if (strchr("ZBCSIFJD", *base) == NULL) {
980 fprintf(stderr, "ERROR: bad method signature '%s'\n", base);
981 goto bail;
982 }
983 *cp++ = *base++;
984 }
985 // Null terminate and display.
986 *cp++ = '\0';
987 char* tmp = descriptorToDot(tmpBuf);
988 fprintf(gOutFile, "<parameter name=\"arg%d\" type=\"%s\">\n"
989 "</parameter>\n", argNum++, tmp);
990 free(tmp);
991 } // while
992 free(tmpBuf);
993 if (constructor) {
994 fprintf(gOutFile, "</constructor>\n");
995 } else {
996 fprintf(gOutFile, "</method>\n");
997 }
998 }
999
1000 bail:
1001 free(typeDescriptor);
1002 free(accessStr);
1003}
1004
1005/*
1006 * Dumps a static (class) field.
1007 */
1008static void dumpSField(const DexFile* pDexFile, u4 idx, u4 flags, int i) {
1009 // Bail for anything private if export only requested.
1010 if (gOptions.exportsOnly && (flags & (kAccPublic | kAccProtected)) == 0) {
1011 return;
1012 }
1013
1014 const DexFile::FieldId& pFieldId = pDexFile->GetFieldId(idx);
1015 const char* name = pDexFile->StringDataByIdx(pFieldId.name_idx_);
1016 const char* typeDescriptor = pDexFile->StringByTypeIdx(pFieldId.type_idx_);
1017 const char* backDescriptor = pDexFile->StringByTypeIdx(pFieldId.class_idx_);
1018 char* accessStr = createAccessFlagStr(flags, kAccessForField);
1019
1020 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1021 fprintf(gOutFile, " #%d : (in %s)\n", i, backDescriptor);
1022 fprintf(gOutFile, " name : '%s'\n", name);
1023 fprintf(gOutFile, " type : '%s'\n", typeDescriptor);
1024 fprintf(gOutFile, " access : 0x%04x (%s)\n", flags, accessStr);
1025 } else if (gOptions.outputFormat == OUTPUT_XML) {
1026 fprintf(gOutFile, "<field name=\"%s\"\n", name);
1027 char *tmp = descriptorToDot(typeDescriptor);
1028 fprintf(gOutFile, " type=\"%s\"\n", tmp);
1029 free(tmp);
1030 fprintf(gOutFile, " transient=%s\n", quotedBool((flags & kAccTransient) != 0));
1031 fprintf(gOutFile, " volatile=%s\n", quotedBool((flags & kAccVolatile) != 0));
1032 // The "value=" is not knowable w/o parsing annotations.
1033 fprintf(gOutFile, " static=%s\n", quotedBool((flags & kAccStatic) != 0));
1034 fprintf(gOutFile, " final=%s\n", quotedBool((flags & kAccFinal) != 0));
1035 // The "deprecated=" is not knowable w/o parsing annotations.
1036 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(flags));
1037 fprintf(gOutFile, ">\n</field>\n");
1038 }
1039
1040 free(accessStr);
1041}
1042
1043/*
1044 * Dumps an instance field.
1045 */
1046static void dumpIField(const DexFile* pDexFile, u4 idx, u4 flags, int i) {
1047 dumpSField(pDexFile, idx, flags, i);
1048}
1049
1050/*
1051 * Dumps the class.
1052 *
1053 * Note "idx" is a DexClassDef index, not a DexTypeId index.
1054 *
1055 * If "*pLastPackage" is nullptr or does not match the current class' package,
1056 * the value will be replaced with a newly-allocated string.
1057 */
1058static void dumpClass(const DexFile* pDexFile, int idx, char** pLastPackage) {
1059 const DexFile::ClassDef& pClassDef = pDexFile->GetClassDef(idx);
1060
1061 // Omitting non-public class.
1062 if (gOptions.exportsOnly && (pClassDef.access_flags_ & kAccPublic) == 0) {
1063 return;
1064 }
1065
1066 // For the XML output, show the package name. Ideally we'd gather
1067 // up the classes, sort them, and dump them alphabetically so the
1068 // package name wouldn't jump around, but that's not a great plan
1069 // for something that needs to run on the device.
1070 const char* classDescriptor = pDexFile->StringByTypeIdx(pClassDef.class_idx_);
1071 if (!(classDescriptor[0] == 'L' &&
1072 classDescriptor[strlen(classDescriptor)-1] == ';')) {
1073 // Arrays and primitives should not be defined explicitly. Keep going?
1074 fprintf(stderr, "Malformed class name '%s'\n", classDescriptor);
1075 } else if (gOptions.outputFormat == OUTPUT_XML) {
1076 char* mangle = strdup(classDescriptor + 1);
1077 mangle[strlen(mangle)-1] = '\0';
1078
1079 // Reduce to just the package name.
1080 char* lastSlash = strrchr(mangle, '/');
1081 if (lastSlash != nullptr) {
1082 *lastSlash = '\0';
1083 } else {
1084 *mangle = '\0';
1085 }
1086
1087 for (char* cp = mangle; *cp != '\0'; cp++) {
1088 if (*cp == '/') {
1089 *cp = '.';
1090 }
1091 } // for
1092
1093 if (*pLastPackage == nullptr || strcmp(mangle, *pLastPackage) != 0) {
1094 // Start of a new package.
1095 if (*pLastPackage != nullptr) {
1096 fprintf(gOutFile, "</package>\n");
1097 }
1098 fprintf(gOutFile, "<package name=\"%s\"\n>\n", mangle);
1099 free(*pLastPackage);
1100 *pLastPackage = mangle;
1101 } else {
1102 free(mangle);
1103 }
1104 }
1105
1106 // General class information.
1107 char* accessStr = createAccessFlagStr(pClassDef.access_flags_, kAccessForClass);
1108 const char* superclassDescriptor;
1109 if (pClassDef.superclass_idx_ == DexFile::kDexNoIndex16) {
1110 superclassDescriptor = nullptr;
1111 } else {
1112 superclassDescriptor = pDexFile->StringByTypeIdx(pClassDef.superclass_idx_);
1113 }
1114 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1115 fprintf(gOutFile, "Class #%d -\n", idx);
1116 fprintf(gOutFile, " Class descriptor : '%s'\n", classDescriptor);
1117 fprintf(gOutFile, " Access flags : 0x%04x (%s)\n", pClassDef.access_flags_, accessStr);
1118 if (superclassDescriptor != nullptr) {
1119 fprintf(gOutFile, " Superclass : '%s'\n", superclassDescriptor);
1120 }
1121 fprintf(gOutFile, " Interfaces -\n");
1122 } else {
1123 char* tmp = descriptorClassToDot(classDescriptor);
1124 fprintf(gOutFile, "<class name=\"%s\"\n", tmp);
1125 free(tmp);
1126 if (superclassDescriptor != nullptr) {
1127 tmp = descriptorToDot(superclassDescriptor);
1128 fprintf(gOutFile, " extends=\"%s\"\n", tmp);
1129 free(tmp);
1130 }
1131 fprintf(gOutFile, " abstract=%s\n", quotedBool((pClassDef.access_flags_ & kAccAbstract) != 0));
1132 fprintf(gOutFile, " static=%s\n", quotedBool((pClassDef.access_flags_ & kAccStatic) != 0));
1133 fprintf(gOutFile, " final=%s\n", quotedBool((pClassDef.access_flags_ & kAccFinal) != 0));
1134 // The "deprecated=" not knowable w/o parsing annotations.
1135 fprintf(gOutFile, " visibility=%s\n", quotedVisibility(pClassDef.access_flags_));
1136 fprintf(gOutFile, ">\n");
1137 }
1138
1139 // Interfaces.
1140 const DexFile::TypeList* pInterfaces = pDexFile->GetInterfacesList(pClassDef);
1141 if (pInterfaces != nullptr) {
1142 for (u4 i = 0; i < pInterfaces->Size(); i++) {
1143 dumpInterface(pDexFile, pInterfaces->GetTypeItem(i), i);
1144 } // for
1145 }
1146
1147 // Fields and methods.
1148 const u1* pEncodedData = pDexFile->GetClassData(pClassDef);
1149 if (pEncodedData == nullptr) {
1150 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1151 fprintf(gOutFile, " Static fields -\n");
1152 fprintf(gOutFile, " Instance fields -\n");
1153 fprintf(gOutFile, " Direct methods -\n");
1154 fprintf(gOutFile, " Virtual methods -\n");
1155 }
1156 } else {
1157 ClassDataItemIterator pClassData(*pDexFile, pEncodedData);
1158 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1159 fprintf(gOutFile, " Static fields -\n");
1160 }
1161 for (int i = 0; pClassData.HasNextStaticField(); i++, pClassData.Next()) {
1162 dumpSField(pDexFile, pClassData.GetMemberIndex(),
1163 pClassData.GetRawMemberAccessFlags(), i);
1164 } // for
1165 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1166 fprintf(gOutFile, " Instance fields -\n");
1167 }
1168 for (int i = 0; pClassData.HasNextInstanceField(); i++, pClassData.Next()) {
1169 dumpIField(pDexFile, pClassData.GetMemberIndex(),
1170 pClassData.GetRawMemberAccessFlags(), i);
1171 } // for
1172 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1173 fprintf(gOutFile, " Direct methods -\n");
1174 }
1175 for (int i = 0; pClassData.HasNextDirectMethod(); i++, pClassData.Next()) {
1176 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1177 pClassData.GetRawMemberAccessFlags(),
1178 pClassData.GetMethodCodeItem(),
1179 pClassData.GetMethodCodeItemOffset(), i);
1180 } // for
1181 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1182 fprintf(gOutFile, " Virtual methods -\n");
1183 }
1184 for (int i = 0; pClassData.HasNextVirtualMethod(); i++, pClassData.Next()) {
1185 dumpMethod(pDexFile, pClassData.GetMemberIndex(),
1186 pClassData.GetRawMemberAccessFlags(),
1187 pClassData.GetMethodCodeItem(),
1188 pClassData.GetMethodCodeItemOffset(), i);
1189 } // for
1190 }
1191
1192 // End of class.
1193 if (gOptions.outputFormat == OUTPUT_PLAIN) {
1194 const char* fileName;
1195 if (pClassDef.source_file_idx_ != DexFile::kDexNoIndex) {
1196 fileName = pDexFile->StringDataByIdx(pClassDef.source_file_idx_);
1197 } else {
1198 fileName = "unknown";
1199 }
1200 fprintf(gOutFile, " source_file_idx : %d (%s)\n\n",
1201 pClassDef.source_file_idx_, fileName);
1202 } else if (gOptions.outputFormat == OUTPUT_XML) {
1203 fprintf(gOutFile, "</class>\n");
1204 }
1205
1206 free(accessStr);
1207}
1208
1209/*
1210 * Dumps the requested sections of the file.
1211 */
1212static void processDexFile(const char* fileName, const DexFile* pDexFile) {
1213 if (gOptions.verbose) {
1214 fprintf(gOutFile, "Opened '%s', DEX version '%.3s'\n",
1215 fileName, pDexFile->GetHeader().magic_ + 4);
1216 }
1217
1218 // Headers.
1219 if (gOptions.showFileHeaders) {
1220 dumpFileHeader(pDexFile);
1221 }
1222
1223 // Open XML context.
1224 if (gOptions.outputFormat == OUTPUT_XML) {
1225 fprintf(gOutFile, "<api>\n");
1226 }
1227
1228 // Iterate over all classes.
1229 char* package = nullptr;
1230 const u4 classDefsSize = pDexFile->GetHeader().class_defs_size_;
1231 for (u4 i = 0; i < classDefsSize; i++) {
1232 if (gOptions.showSectionHeaders) {
1233 dumpClassDef(pDexFile, i);
1234 }
1235 dumpClass(pDexFile, i, &package);
1236 } // for
1237
1238 // Free the last package allocated.
1239 if (package != nullptr) {
1240 fprintf(gOutFile, "</package>\n");
1241 free(package);
1242 }
1243
1244 // Close XML context.
1245 if (gOptions.outputFormat == OUTPUT_XML) {
1246 fprintf(gOutFile, "</api>\n");
1247 }
1248}
1249
1250/*
1251 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
1252 */
1253int processFile(const char* fileName) {
1254 if (gOptions.verbose) {
1255 fprintf(gOutFile, "Processing '%s'...\n", fileName);
1256 }
1257
1258 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
1259 // all of which are Zip archives with "classes.dex" inside. The compressed
1260 // data needs to be extracted to a temp file, the location of which varies.
1261 //
1262 // TODO(ajcbik): fix following issues
1263 //
1264 // (1) gOptions.tempFileName is not accounted for
1265 // (2) gOptions.ignoreBadChecksum is not accounted for
1266 //
1267 std::string error_msg;
1268 std::vector<std::unique_ptr<const DexFile>> dex_files;
1269 if (!DexFile::Open(fileName, fileName, &error_msg, &dex_files)) {
1270 // Display returned error message to user. Note that this error behavior
1271 // differs from the error messages shown by the original Dalvik dexdump.
1272 fputs(error_msg.c_str(), stderr);
1273 fputc('\n', stderr);
1274 return -1;
1275 }
1276
1277 // Determine if opening file yielded a single dex file. On failure,
1278 // the parse error message of the original dexdump utility is shown.
1279 //
1280 // TODO(ajcbik): this restriction is not really needed, but kept
1281 // for now to stay close to original dexdump; we can
1282 // later relax this!
1283 //
1284 if (dex_files.size() != 1) {
1285 fprintf(stderr, "ERROR: DEX parse failed\n");
1286 return -1;
1287 }
1288
1289 // Success. Either report checksum verification or process dex file.
1290 if (gOptions.checksumOnly) {
1291 fprintf(gOutFile, "Checksum verified\n");
1292 } else {
1293 processDexFile(fileName, dex_files[0].get());
1294 }
1295 return 0;
1296}
1297
1298} // namespace art