blob: a23db38632160be111dbb835f5c5e5864bb93d4e [file] [log] [blame]
David Sehr7629f602016-08-07 16:01:51 -07001/*
2 * Copyright (C) 2016 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 dexlayout utility.
17 *
18 * This is a tool to read dex files into an internal representation,
19 * reorganize the representation, and emit dex files with a better
20 * file layout.
21 */
22
23#include "dexlayout.h"
24
25#include <inttypes.h>
26#include <stdio.h>
27
28#include <iostream>
29#include <memory>
30#include <sstream>
31#include <vector>
32
David Sehr853a8e12016-09-01 13:03:50 -070033#include "dex_ir_builder.h"
David Sehr7629f602016-08-07 16:01:51 -070034#include "dex_file-inl.h"
35#include "dex_instruction-inl.h"
Jeff Hao69b58cf2016-09-22 18:02:49 -070036#include "dex_writer.h"
David Sehr7629f602016-08-07 16:01:51 -070037#include "utils.h"
38
39namespace art {
40
41/*
42 * Options parsed in main driver.
43 */
44struct Options options_;
45
46/*
47 * Output file. Defaults to stdout.
48 */
49FILE* out_file_ = stdout;
50
51/*
52 * Flags for use with createAccessFlagStr().
53 */
54enum AccessFor {
55 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
56};
57const int kNumFlags = 18;
58
59/*
60 * Gets 2 little-endian bytes.
61 */
62static inline uint16_t Get2LE(unsigned char const* src) {
63 return src[0] | (src[1] << 8);
64}
65
66/*
Jeff Haoc3acfc52016-08-29 14:18:26 -070067 * Converts a type descriptor to human-readable "dotted" form. For
68 * example, "Ljava/lang/String;" becomes "java.lang.String", and
69 * "[I" becomes "int[]". Also converts '$' to '.', which means this
70 * form can't be converted back to a descriptor.
71 */
72static std::string DescriptorToDotWrapper(const char* descriptor) {
73 std::string result = DescriptorToDot(descriptor);
74 size_t found = result.find('$');
75 while (found != std::string::npos) {
76 result[found] = '.';
77 found = result.find('$', found);
78 }
79 return result;
80}
81
82/*
David Sehr7629f602016-08-07 16:01:51 -070083 * Converts the class name portion of a type descriptor to human-readable
84 * "dotted" form. For example, "Ljava/lang/String;" becomes "String".
85 */
86static std::string DescriptorClassToDot(const char* str) {
87 std::string descriptor(str);
88 // Reduce to just the class name prefix.
89 size_t last_slash = descriptor.rfind('/');
90 if (last_slash == std::string::npos) {
91 last_slash = 0;
92 }
93 // Start past the '/' or 'L'.
94 last_slash++;
95
96 // Copy class name over, trimming trailing ';'.
97 size_t size = descriptor.size() - 1 - last_slash;
98 std::string result(descriptor.substr(last_slash, size));
99
100 // Replace '$' with '.'.
101 size_t dollar_sign = result.find('$');
102 while (dollar_sign != std::string::npos) {
103 result[dollar_sign] = '.';
104 dollar_sign = result.find('$', dollar_sign);
105 }
106
107 return result;
108}
109
110/*
111 * Returns string representing the boolean value.
112 */
113static const char* StrBool(bool val) {
114 return val ? "true" : "false";
115}
116
117/*
118 * Returns a quoted string representing the boolean value.
119 */
120static const char* QuotedBool(bool val) {
121 return val ? "\"true\"" : "\"false\"";
122}
123
124/*
125 * Returns a quoted string representing the access flags.
126 */
127static const char* QuotedVisibility(uint32_t access_flags) {
128 if (access_flags & kAccPublic) {
129 return "\"public\"";
130 } else if (access_flags & kAccProtected) {
131 return "\"protected\"";
132 } else if (access_flags & kAccPrivate) {
133 return "\"private\"";
134 } else {
135 return "\"package\"";
136 }
137}
138
139/*
140 * Counts the number of '1' bits in a word.
141 */
142static int CountOnes(uint32_t val) {
143 val = val - ((val >> 1) & 0x55555555);
144 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
145 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
146}
147
148/*
149 * Creates a new string with human-readable access flags.
150 *
151 * In the base language the access_flags fields are type uint16_t; in Dalvik they're uint32_t.
152 */
153static char* CreateAccessFlagStr(uint32_t flags, AccessFor for_what) {
154 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
155 {
156 "PUBLIC", /* 0x00001 */
157 "PRIVATE", /* 0x00002 */
158 "PROTECTED", /* 0x00004 */
159 "STATIC", /* 0x00008 */
160 "FINAL", /* 0x00010 */
161 "?", /* 0x00020 */
162 "?", /* 0x00040 */
163 "?", /* 0x00080 */
164 "?", /* 0x00100 */
165 "INTERFACE", /* 0x00200 */
166 "ABSTRACT", /* 0x00400 */
167 "?", /* 0x00800 */
168 "SYNTHETIC", /* 0x01000 */
169 "ANNOTATION", /* 0x02000 */
170 "ENUM", /* 0x04000 */
171 "?", /* 0x08000 */
172 "VERIFIED", /* 0x10000 */
173 "OPTIMIZED", /* 0x20000 */
174 }, {
175 "PUBLIC", /* 0x00001 */
176 "PRIVATE", /* 0x00002 */
177 "PROTECTED", /* 0x00004 */
178 "STATIC", /* 0x00008 */
179 "FINAL", /* 0x00010 */
180 "SYNCHRONIZED", /* 0x00020 */
181 "BRIDGE", /* 0x00040 */
182 "VARARGS", /* 0x00080 */
183 "NATIVE", /* 0x00100 */
184 "?", /* 0x00200 */
185 "ABSTRACT", /* 0x00400 */
186 "STRICT", /* 0x00800 */
187 "SYNTHETIC", /* 0x01000 */
188 "?", /* 0x02000 */
189 "?", /* 0x04000 */
190 "MIRANDA", /* 0x08000 */
191 "CONSTRUCTOR", /* 0x10000 */
192 "DECLARED_SYNCHRONIZED", /* 0x20000 */
193 }, {
194 "PUBLIC", /* 0x00001 */
195 "PRIVATE", /* 0x00002 */
196 "PROTECTED", /* 0x00004 */
197 "STATIC", /* 0x00008 */
198 "FINAL", /* 0x00010 */
199 "?", /* 0x00020 */
200 "VOLATILE", /* 0x00040 */
201 "TRANSIENT", /* 0x00080 */
202 "?", /* 0x00100 */
203 "?", /* 0x00200 */
204 "?", /* 0x00400 */
205 "?", /* 0x00800 */
206 "SYNTHETIC", /* 0x01000 */
207 "?", /* 0x02000 */
208 "ENUM", /* 0x04000 */
209 "?", /* 0x08000 */
210 "?", /* 0x10000 */
211 "?", /* 0x20000 */
212 },
213 };
214
215 // Allocate enough storage to hold the expected number of strings,
216 // plus a space between each. We over-allocate, using the longest
217 // string above as the base metric.
218 const int kLongest = 21; // The strlen of longest string above.
219 const int count = CountOnes(flags);
220 char* str;
221 char* cp;
222 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
223
224 for (int i = 0; i < kNumFlags; i++) {
225 if (flags & 0x01) {
226 const char* accessStr = kAccessStrings[for_what][i];
227 const int len = strlen(accessStr);
228 if (cp != str) {
229 *cp++ = ' ';
230 }
231 memcpy(cp, accessStr, len);
232 cp += len;
233 }
234 flags >>= 1;
235 } // for
236
237 *cp = '\0';
238 return str;
239}
240
241static std::string GetSignatureForProtoId(const dex_ir::ProtoId* proto) {
242 if (proto == nullptr) {
243 return "<no signature>";
244 }
245
David Sehr7629f602016-08-07 16:01:51 -0700246 std::string result("(");
Jeff Hao69b58cf2016-09-22 18:02:49 -0700247 const dex_ir::TypeList* type_list = proto->Parameters();
248 if (type_list != nullptr) {
249 for (const dex_ir::TypeId* type_id : *type_list->GetTypeList()) {
250 result += type_id->GetStringId()->Data();
251 }
David Sehr7629f602016-08-07 16:01:51 -0700252 }
253 result += ")";
254 result += proto->ReturnType()->GetStringId()->Data();
255 return result;
256}
257
258/*
259 * Copies character data from "data" to "out", converting non-ASCII values
260 * to fprintf format chars or an ASCII filler ('.' or '?').
261 *
262 * The output buffer must be able to hold (2*len)+1 bytes. The result is
263 * NULL-terminated.
264 */
265static void Asciify(char* out, const unsigned char* data, size_t len) {
266 while (len--) {
267 if (*data < 0x20) {
268 // Could do more here, but we don't need them yet.
269 switch (*data) {
270 case '\0':
271 *out++ = '\\';
272 *out++ = '0';
273 break;
274 case '\n':
275 *out++ = '\\';
276 *out++ = 'n';
277 break;
278 default:
279 *out++ = '.';
280 break;
281 } // switch
282 } else if (*data >= 0x80) {
283 *out++ = '?';
284 } else {
285 *out++ = *data;
286 }
287 data++;
288 } // while
289 *out = '\0';
290}
291
292/*
293 * Dumps a string value with some escape characters.
294 */
295static void DumpEscapedString(const char* p) {
296 fputs("\"", out_file_);
297 for (; *p; p++) {
298 switch (*p) {
299 case '\\':
300 fputs("\\\\", out_file_);
301 break;
302 case '\"':
303 fputs("\\\"", out_file_);
304 break;
305 case '\t':
306 fputs("\\t", out_file_);
307 break;
308 case '\n':
309 fputs("\\n", out_file_);
310 break;
311 case '\r':
312 fputs("\\r", out_file_);
313 break;
314 default:
315 putc(*p, out_file_);
316 } // switch
317 } // for
318 fputs("\"", out_file_);
319}
320
321/*
322 * Dumps a string as an XML attribute value.
323 */
324static void DumpXmlAttribute(const char* p) {
325 for (; *p; p++) {
326 switch (*p) {
327 case '&':
328 fputs("&amp;", out_file_);
329 break;
330 case '<':
331 fputs("&lt;", out_file_);
332 break;
333 case '>':
334 fputs("&gt;", out_file_);
335 break;
336 case '"':
337 fputs("&quot;", out_file_);
338 break;
339 case '\t':
340 fputs("&#x9;", out_file_);
341 break;
342 case '\n':
343 fputs("&#xA;", out_file_);
344 break;
345 case '\r':
346 fputs("&#xD;", out_file_);
347 break;
348 default:
349 putc(*p, out_file_);
350 } // switch
351 } // for
352}
353
Jeff Hao3ab96b42016-09-09 18:35:01 -0700354// Forward declare to resolve circular dependence.
355static void DumpEncodedValue(const dex_ir::EncodedValue* data);
356
357/*
358 * Dumps encoded annotation.
359 */
360static void DumpEncodedAnnotation(dex_ir::EncodedAnnotation* annotation) {
361 fputs(annotation->GetType()->GetStringId()->Data(), out_file_);
362 // Display all name=value pairs.
363 for (auto& subannotation : *annotation->GetAnnotationElements()) {
364 fputc(' ', out_file_);
365 fputs(subannotation->GetName()->Data(), out_file_);
366 fputc('=', out_file_);
367 DumpEncodedValue(subannotation->GetValue());
368 }
369}
David Sehr7629f602016-08-07 16:01:51 -0700370/*
371 * Dumps encoded value.
372 */
Jeff Hao3ab96b42016-09-09 18:35:01 -0700373static void DumpEncodedValue(const dex_ir::EncodedValue* data) {
David Sehr7629f602016-08-07 16:01:51 -0700374 switch (data->Type()) {
375 case DexFile::kDexAnnotationByte:
376 fprintf(out_file_, "%" PRId8, data->GetByte());
377 break;
378 case DexFile::kDexAnnotationShort:
379 fprintf(out_file_, "%" PRId16, data->GetShort());
380 break;
381 case DexFile::kDexAnnotationChar:
382 fprintf(out_file_, "%" PRIu16, data->GetChar());
383 break;
384 case DexFile::kDexAnnotationInt:
385 fprintf(out_file_, "%" PRId32, data->GetInt());
386 break;
387 case DexFile::kDexAnnotationLong:
388 fprintf(out_file_, "%" PRId64, data->GetLong());
389 break;
390 case DexFile::kDexAnnotationFloat: {
391 fprintf(out_file_, "%g", data->GetFloat());
392 break;
393 }
394 case DexFile::kDexAnnotationDouble: {
395 fprintf(out_file_, "%g", data->GetDouble());
396 break;
397 }
398 case DexFile::kDexAnnotationString: {
399 dex_ir::StringId* string_id = data->GetStringId();
400 if (options_.output_format_ == kOutputPlain) {
401 DumpEscapedString(string_id->Data());
402 } else {
403 DumpXmlAttribute(string_id->Data());
404 }
405 break;
406 }
407 case DexFile::kDexAnnotationType: {
Jeff Hao3ab96b42016-09-09 18:35:01 -0700408 dex_ir::TypeId* type_id = data->GetTypeId();
409 fputs(type_id->GetStringId()->Data(), out_file_);
David Sehr7629f602016-08-07 16:01:51 -0700410 break;
411 }
412 case DexFile::kDexAnnotationField:
413 case DexFile::kDexAnnotationEnum: {
414 dex_ir::FieldId* field_id = data->GetFieldId();
415 fputs(field_id->Name()->Data(), out_file_);
416 break;
417 }
418 case DexFile::kDexAnnotationMethod: {
419 dex_ir::MethodId* method_id = data->GetMethodId();
420 fputs(method_id->Name()->Data(), out_file_);
421 break;
422 }
423 case DexFile::kDexAnnotationArray: {
424 fputc('{', out_file_);
425 // Display all elements.
Jeff Hao3ab96b42016-09-09 18:35:01 -0700426 for (auto& value : *data->GetEncodedArray()->GetEncodedValues()) {
David Sehr7629f602016-08-07 16:01:51 -0700427 fputc(' ', out_file_);
Jeff Hao3ab96b42016-09-09 18:35:01 -0700428 DumpEncodedValue(value.get());
David Sehr7629f602016-08-07 16:01:51 -0700429 }
430 fputs(" }", out_file_);
431 break;
432 }
433 case DexFile::kDexAnnotationAnnotation: {
Jeff Hao3ab96b42016-09-09 18:35:01 -0700434 DumpEncodedAnnotation(data->GetEncodedAnnotation());
David Sehr7629f602016-08-07 16:01:51 -0700435 break;
436 }
437 case DexFile::kDexAnnotationNull:
438 fputs("null", out_file_);
439 break;
440 case DexFile::kDexAnnotationBoolean:
441 fputs(StrBool(data->GetBoolean()), out_file_);
442 break;
443 default:
444 fputs("????", out_file_);
445 break;
446 } // switch
447}
448
449/*
450 * Dumps the file header.
451 */
Jeff Hao3ab96b42016-09-09 18:35:01 -0700452static void DumpFileHeader(dex_ir::Header* header) {
David Sehr7629f602016-08-07 16:01:51 -0700453 char sanitized[8 * 2 + 1];
Jeff Hao3ab96b42016-09-09 18:35:01 -0700454 dex_ir::Collections& collections = header->GetCollections();
David Sehr7629f602016-08-07 16:01:51 -0700455 fprintf(out_file_, "DEX file header:\n");
456 Asciify(sanitized, header->Magic(), 8);
457 fprintf(out_file_, "magic : '%s'\n", sanitized);
458 fprintf(out_file_, "checksum : %08x\n", header->Checksum());
459 fprintf(out_file_, "signature : %02x%02x...%02x%02x\n",
460 header->Signature()[0], header->Signature()[1],
461 header->Signature()[DexFile::kSha1DigestSize - 2],
462 header->Signature()[DexFile::kSha1DigestSize - 1]);
463 fprintf(out_file_, "file_size : %d\n", header->FileSize());
464 fprintf(out_file_, "header_size : %d\n", header->HeaderSize());
465 fprintf(out_file_, "link_size : %d\n", header->LinkSize());
466 fprintf(out_file_, "link_off : %d (0x%06x)\n",
467 header->LinkOffset(), header->LinkOffset());
Jeff Hao3ab96b42016-09-09 18:35:01 -0700468 fprintf(out_file_, "string_ids_size : %d\n", collections.StringIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700469 fprintf(out_file_, "string_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700470 collections.StringIdsOffset(), collections.StringIdsOffset());
471 fprintf(out_file_, "type_ids_size : %d\n", collections.TypeIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700472 fprintf(out_file_, "type_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700473 collections.TypeIdsOffset(), collections.TypeIdsOffset());
474 fprintf(out_file_, "proto_ids_size : %d\n", collections.ProtoIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700475 fprintf(out_file_, "proto_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700476 collections.ProtoIdsOffset(), collections.ProtoIdsOffset());
477 fprintf(out_file_, "field_ids_size : %d\n", collections.FieldIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700478 fprintf(out_file_, "field_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700479 collections.FieldIdsOffset(), collections.FieldIdsOffset());
480 fprintf(out_file_, "method_ids_size : %d\n", collections.MethodIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700481 fprintf(out_file_, "method_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700482 collections.MethodIdsOffset(), collections.MethodIdsOffset());
483 fprintf(out_file_, "class_defs_size : %d\n", collections.ClassDefsSize());
David Sehr7629f602016-08-07 16:01:51 -0700484 fprintf(out_file_, "class_defs_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700485 collections.ClassDefsOffset(), collections.ClassDefsOffset());
David Sehr7629f602016-08-07 16:01:51 -0700486 fprintf(out_file_, "data_size : %d\n", header->DataSize());
487 fprintf(out_file_, "data_off : %d (0x%06x)\n\n",
488 header->DataOffset(), header->DataOffset());
489}
490
491/*
492 * Dumps a class_def_item.
493 */
494static void DumpClassDef(dex_ir::Header* header, int idx) {
495 // General class information.
Jeff Hao3ab96b42016-09-09 18:35:01 -0700496 dex_ir::ClassDef* class_def = header->GetCollections().GetClassDef(idx);
David Sehr7629f602016-08-07 16:01:51 -0700497 fprintf(out_file_, "Class #%d header:\n", idx);
Jeff Hao3ab96b42016-09-09 18:35:01 -0700498 fprintf(out_file_, "class_idx : %d\n", class_def->ClassType()->GetIndex());
David Sehr7629f602016-08-07 16:01:51 -0700499 fprintf(out_file_, "access_flags : %d (0x%04x)\n",
500 class_def->GetAccessFlags(), class_def->GetAccessFlags());
Jeff Haoc3acfc52016-08-29 14:18:26 -0700501 uint32_t superclass_idx = class_def->Superclass() == nullptr ?
Jeff Hao3ab96b42016-09-09 18:35:01 -0700502 DexFile::kDexNoIndex16 : class_def->Superclass()->GetIndex();
Jeff Haoc3acfc52016-08-29 14:18:26 -0700503 fprintf(out_file_, "superclass_idx : %d\n", superclass_idx);
David Sehr7629f602016-08-07 16:01:51 -0700504 fprintf(out_file_, "interfaces_off : %d (0x%06x)\n",
505 class_def->InterfacesOffset(), class_def->InterfacesOffset());
506 uint32_t source_file_offset = 0xffffffffU;
507 if (class_def->SourceFile() != nullptr) {
Jeff Hao3ab96b42016-09-09 18:35:01 -0700508 source_file_offset = class_def->SourceFile()->GetIndex();
David Sehr7629f602016-08-07 16:01:51 -0700509 }
510 fprintf(out_file_, "source_file_idx : %d\n", source_file_offset);
511 uint32_t annotations_offset = 0;
512 if (class_def->Annotations() != nullptr) {
513 annotations_offset = class_def->Annotations()->GetOffset();
514 }
515 fprintf(out_file_, "annotations_off : %d (0x%06x)\n",
516 annotations_offset, annotations_offset);
David Sehr853a8e12016-09-01 13:03:50 -0700517 if (class_def->GetClassData() == nullptr) {
518 fprintf(out_file_, "class_data_off : %d (0x%06x)\n", 0, 0);
519 } else {
520 fprintf(out_file_, "class_data_off : %d (0x%06x)\n",
521 class_def->GetClassData()->GetOffset(), class_def->GetClassData()->GetOffset());
522 }
David Sehr7629f602016-08-07 16:01:51 -0700523
524 // Fields and methods.
525 dex_ir::ClassData* class_data = class_def->GetClassData();
David Sehr853a8e12016-09-01 13:03:50 -0700526 if (class_data != nullptr && class_data->StaticFields() != nullptr) {
527 fprintf(out_file_, "static_fields_size : %zu\n", class_data->StaticFields()->size());
David Sehr7629f602016-08-07 16:01:51 -0700528 } else {
529 fprintf(out_file_, "static_fields_size : 0\n");
David Sehr853a8e12016-09-01 13:03:50 -0700530 }
531 if (class_data != nullptr && class_data->InstanceFields() != nullptr) {
532 fprintf(out_file_, "instance_fields_size: %zu\n", class_data->InstanceFields()->size());
533 } else {
David Sehr7629f602016-08-07 16:01:51 -0700534 fprintf(out_file_, "instance_fields_size: 0\n");
David Sehr853a8e12016-09-01 13:03:50 -0700535 }
536 if (class_data != nullptr && class_data->DirectMethods() != nullptr) {
537 fprintf(out_file_, "direct_methods_size : %zu\n", class_data->DirectMethods()->size());
538 } else {
David Sehr7629f602016-08-07 16:01:51 -0700539 fprintf(out_file_, "direct_methods_size : 0\n");
David Sehr853a8e12016-09-01 13:03:50 -0700540 }
541 if (class_data != nullptr && class_data->VirtualMethods() != nullptr) {
542 fprintf(out_file_, "virtual_methods_size: %zu\n", class_data->VirtualMethods()->size());
543 } else {
David Sehr7629f602016-08-07 16:01:51 -0700544 fprintf(out_file_, "virtual_methods_size: 0\n");
545 }
546 fprintf(out_file_, "\n");
547}
548
549/**
550 * Dumps an annotation set item.
551 */
552static void DumpAnnotationSetItem(dex_ir::AnnotationSetItem* set_item) {
David Sehr853a8e12016-09-01 13:03:50 -0700553 if (set_item == nullptr || set_item->GetItems()->size() == 0) {
David Sehr7629f602016-08-07 16:01:51 -0700554 fputs(" empty-annotation-set\n", out_file_);
555 return;
556 }
Jeff Hao3ab96b42016-09-09 18:35:01 -0700557 for (dex_ir::AnnotationItem* annotation : *set_item->GetItems()) {
David Sehr7629f602016-08-07 16:01:51 -0700558 if (annotation == nullptr) {
559 continue;
560 }
561 fputs(" ", out_file_);
562 switch (annotation->GetVisibility()) {
563 case DexFile::kDexVisibilityBuild: fputs("VISIBILITY_BUILD ", out_file_); break;
564 case DexFile::kDexVisibilityRuntime: fputs("VISIBILITY_RUNTIME ", out_file_); break;
565 case DexFile::kDexVisibilitySystem: fputs("VISIBILITY_SYSTEM ", out_file_); break;
566 default: fputs("VISIBILITY_UNKNOWN ", out_file_); break;
567 } // switch
Jeff Hao3ab96b42016-09-09 18:35:01 -0700568 DumpEncodedAnnotation(annotation->GetAnnotation());
David Sehr7629f602016-08-07 16:01:51 -0700569 fputc('\n', out_file_);
570 }
571}
572
573/*
574 * Dumps class annotations.
575 */
576static void DumpClassAnnotations(dex_ir::Header* header, int idx) {
Jeff Hao3ab96b42016-09-09 18:35:01 -0700577 dex_ir::ClassDef* class_def = header->GetCollections().GetClassDef(idx);
David Sehr7629f602016-08-07 16:01:51 -0700578 dex_ir::AnnotationsDirectoryItem* annotations_directory = class_def->Annotations();
579 if (annotations_directory == nullptr) {
580 return; // none
581 }
582
583 fprintf(out_file_, "Class #%d annotations:\n", idx);
584
585 dex_ir::AnnotationSetItem* class_set_item = annotations_directory->GetClassAnnotation();
David Sehr853a8e12016-09-01 13:03:50 -0700586 dex_ir::FieldAnnotationVector* fields = annotations_directory->GetFieldAnnotations();
587 dex_ir::MethodAnnotationVector* methods = annotations_directory->GetMethodAnnotations();
588 dex_ir::ParameterAnnotationVector* parameters = annotations_directory->GetParameterAnnotations();
David Sehr7629f602016-08-07 16:01:51 -0700589
590 // Annotations on the class itself.
591 if (class_set_item != nullptr) {
592 fprintf(out_file_, "Annotations on class\n");
593 DumpAnnotationSetItem(class_set_item);
594 }
595
596 // Annotations on fields.
David Sehr853a8e12016-09-01 13:03:50 -0700597 if (fields != nullptr) {
598 for (auto& field : *fields) {
599 const dex_ir::FieldId* field_id = field->GetFieldId();
Jeff Hao3ab96b42016-09-09 18:35:01 -0700600 const uint32_t field_idx = field_id->GetIndex();
David Sehr853a8e12016-09-01 13:03:50 -0700601 const char* field_name = field_id->Name()->Data();
602 fprintf(out_file_, "Annotations on field #%u '%s'\n", field_idx, field_name);
603 DumpAnnotationSetItem(field->GetAnnotationSetItem());
604 }
David Sehr7629f602016-08-07 16:01:51 -0700605 }
606
607 // Annotations on methods.
David Sehr853a8e12016-09-01 13:03:50 -0700608 if (methods != nullptr) {
609 for (auto& method : *methods) {
610 const dex_ir::MethodId* method_id = method->GetMethodId();
Jeff Hao3ab96b42016-09-09 18:35:01 -0700611 const uint32_t method_idx = method_id->GetIndex();
David Sehr853a8e12016-09-01 13:03:50 -0700612 const char* method_name = method_id->Name()->Data();
613 fprintf(out_file_, "Annotations on method #%u '%s'\n", method_idx, method_name);
614 DumpAnnotationSetItem(method->GetAnnotationSetItem());
615 }
David Sehr7629f602016-08-07 16:01:51 -0700616 }
617
618 // Annotations on method parameters.
David Sehr853a8e12016-09-01 13:03:50 -0700619 if (parameters != nullptr) {
620 for (auto& parameter : *parameters) {
621 const dex_ir::MethodId* method_id = parameter->GetMethodId();
Jeff Hao3ab96b42016-09-09 18:35:01 -0700622 const uint32_t method_idx = method_id->GetIndex();
David Sehr853a8e12016-09-01 13:03:50 -0700623 const char* method_name = method_id->Name()->Data();
624 fprintf(out_file_, "Annotations on method #%u '%s' parameters\n", method_idx, method_name);
625 uint32_t j = 0;
Jeff Hao3ab96b42016-09-09 18:35:01 -0700626 for (dex_ir::AnnotationSetItem* annotation : *parameter->GetAnnotations()->GetItems()) {
David Sehr853a8e12016-09-01 13:03:50 -0700627 fprintf(out_file_, "#%u\n", j);
Jeff Hao3ab96b42016-09-09 18:35:01 -0700628 DumpAnnotationSetItem(annotation);
David Sehr853a8e12016-09-01 13:03:50 -0700629 ++j;
630 }
David Sehr7629f602016-08-07 16:01:51 -0700631 }
632 }
633
634 fputc('\n', out_file_);
635}
636
637/*
638 * Dumps an interface that a class declares to implement.
639 */
David Sehr853a8e12016-09-01 13:03:50 -0700640static void DumpInterface(const dex_ir::TypeId* type_item, int i) {
David Sehr7629f602016-08-07 16:01:51 -0700641 const char* interface_name = type_item->GetStringId()->Data();
642 if (options_.output_format_ == kOutputPlain) {
643 fprintf(out_file_, " #%d : '%s'\n", i, interface_name);
644 } else {
Jeff Haoc3acfc52016-08-29 14:18:26 -0700645 std::string dot(DescriptorToDotWrapper(interface_name));
David Sehr7629f602016-08-07 16:01:51 -0700646 fprintf(out_file_, "<implements name=\"%s\">\n</implements>\n", dot.c_str());
647 }
648}
649
650/*
651 * Dumps the catches table associated with the code.
652 */
653static void DumpCatches(const dex_ir::CodeItem* code) {
654 const uint16_t tries_size = code->TriesSize();
655
656 // No catch table.
657 if (tries_size == 0) {
658 fprintf(out_file_, " catches : (none)\n");
659 return;
660 }
661
662 // Dump all table entries.
663 fprintf(out_file_, " catches : %d\n", tries_size);
664 std::vector<std::unique_ptr<const dex_ir::TryItem>>* tries = code->Tries();
665 for (uint32_t i = 0; i < tries_size; i++) {
666 const dex_ir::TryItem* try_item = (*tries)[i].get();
667 const uint32_t start = try_item->StartAddr();
668 const uint32_t end = start + try_item->InsnCount();
669 fprintf(out_file_, " 0x%04x - 0x%04x\n", start, end);
Jeff Hao69b58cf2016-09-22 18:02:49 -0700670 for (auto& handler : *try_item->GetHandlers()->GetHandlers()) {
David Sehr7629f602016-08-07 16:01:51 -0700671 const dex_ir::TypeId* type_id = handler->GetTypeId();
672 const char* descriptor = (type_id == nullptr) ? "<any>" : type_id->GetStringId()->Data();
673 fprintf(out_file_, " %s -> 0x%04x\n", descriptor, handler->GetAddress());
674 } // for
675 } // for
676}
677
678/*
679 * Dumps all positions table entries associated with the code.
680 */
681static void DumpPositionInfo(const dex_ir::CodeItem* code) {
682 dex_ir::DebugInfoItem* debug_info = code->DebugInfo();
683 if (debug_info == nullptr) {
684 return;
685 }
686 std::vector<std::unique_ptr<dex_ir::PositionInfo>>& positions = debug_info->GetPositionInfo();
687 for (size_t i = 0; i < positions.size(); ++i) {
688 fprintf(out_file_, " 0x%04x line=%d\n", positions[i]->address_, positions[i]->line_);
689 }
690}
691
692/*
693 * Dumps all locals table entries associated with the code.
694 */
695static void DumpLocalInfo(const dex_ir::CodeItem* code) {
696 dex_ir::DebugInfoItem* debug_info = code->DebugInfo();
697 if (debug_info == nullptr) {
698 return;
699 }
700 std::vector<std::unique_ptr<dex_ir::LocalInfo>>& locals = debug_info->GetLocalInfo();
701 for (size_t i = 0; i < locals.size(); ++i) {
702 dex_ir::LocalInfo* entry = locals[i].get();
703 fprintf(out_file_, " 0x%04x - 0x%04x reg=%d %s %s %s\n",
704 entry->start_address_, entry->end_address_, entry->reg_,
705 entry->name_.c_str(), entry->descriptor_.c_str(), entry->signature_.c_str());
706 }
707}
708
709/*
710 * Helper for dumpInstruction(), which builds the string
711 * representation for the index in the given instruction.
712 * Returns a pointer to a buffer of sufficient size.
713 */
714static std::unique_ptr<char[]> IndexString(dex_ir::Header* header,
715 const Instruction* dec_insn,
716 size_t buf_size) {
717 std::unique_ptr<char[]> buf(new char[buf_size]);
718 // Determine index and width of the string.
719 uint32_t index = 0;
720 uint32_t width = 4;
721 switch (Instruction::FormatOf(dec_insn->Opcode())) {
722 // SOME NOT SUPPORTED:
723 // case Instruction::k20bc:
724 case Instruction::k21c:
725 case Instruction::k35c:
726 // case Instruction::k35ms:
727 case Instruction::k3rc:
728 // case Instruction::k3rms:
729 // case Instruction::k35mi:
730 // case Instruction::k3rmi:
731 index = dec_insn->VRegB();
732 width = 4;
733 break;
734 case Instruction::k31c:
735 index = dec_insn->VRegB();
736 width = 8;
737 break;
738 case Instruction::k22c:
739 // case Instruction::k22cs:
740 index = dec_insn->VRegC();
741 width = 4;
742 break;
743 default:
744 break;
745 } // switch
746
747 // Determine index type.
748 size_t outSize = 0;
749 switch (Instruction::IndexTypeOf(dec_insn->Opcode())) {
750 case Instruction::kIndexUnknown:
751 // This function should never get called for this type, but do
752 // something sensible here, just to help with debugging.
753 outSize = snprintf(buf.get(), buf_size, "<unknown-index>");
754 break;
755 case Instruction::kIndexNone:
756 // This function should never get called for this type, but do
757 // something sensible here, just to help with debugging.
758 outSize = snprintf(buf.get(), buf_size, "<no-index>");
759 break;
760 case Instruction::kIndexTypeRef:
Jeff Hao3ab96b42016-09-09 18:35:01 -0700761 if (index < header->GetCollections().TypeIdsSize()) {
762 const char* tp = header->GetCollections().GetTypeId(index)->GetStringId()->Data();
David Sehr7629f602016-08-07 16:01:51 -0700763 outSize = snprintf(buf.get(), buf_size, "%s // type@%0*x", tp, width, index);
764 } else {
765 outSize = snprintf(buf.get(), buf_size, "<type?> // type@%0*x", width, index);
766 }
767 break;
768 case Instruction::kIndexStringRef:
Jeff Hao3ab96b42016-09-09 18:35:01 -0700769 if (index < header->GetCollections().StringIdsSize()) {
770 const char* st = header->GetCollections().GetStringId(index)->Data();
David Sehr7629f602016-08-07 16:01:51 -0700771 outSize = snprintf(buf.get(), buf_size, "\"%s\" // string@%0*x", st, width, index);
772 } else {
773 outSize = snprintf(buf.get(), buf_size, "<string?> // string@%0*x", width, index);
774 }
775 break;
776 case Instruction::kIndexMethodRef:
Jeff Hao3ab96b42016-09-09 18:35:01 -0700777 if (index < header->GetCollections().MethodIdsSize()) {
778 dex_ir::MethodId* method_id = header->GetCollections().GetMethodId(index);
David Sehr7629f602016-08-07 16:01:51 -0700779 const char* name = method_id->Name()->Data();
David Sehr72359222016-09-07 13:04:01 -0700780 std::string type_descriptor = GetSignatureForProtoId(method_id->Proto());
David Sehr7629f602016-08-07 16:01:51 -0700781 const char* back_descriptor = method_id->Class()->GetStringId()->Data();
782 outSize = snprintf(buf.get(), buf_size, "%s.%s:%s // method@%0*x",
David Sehr72359222016-09-07 13:04:01 -0700783 back_descriptor, name, type_descriptor.c_str(), width, index);
David Sehr7629f602016-08-07 16:01:51 -0700784 } else {
785 outSize = snprintf(buf.get(), buf_size, "<method?> // method@%0*x", width, index);
786 }
787 break;
788 case Instruction::kIndexFieldRef:
Jeff Hao3ab96b42016-09-09 18:35:01 -0700789 if (index < header->GetCollections().FieldIdsSize()) {
790 dex_ir::FieldId* field_id = header->GetCollections().GetFieldId(index);
David Sehr7629f602016-08-07 16:01:51 -0700791 const char* name = field_id->Name()->Data();
792 const char* type_descriptor = field_id->Type()->GetStringId()->Data();
793 const char* back_descriptor = field_id->Class()->GetStringId()->Data();
794 outSize = snprintf(buf.get(), buf_size, "%s.%s:%s // field@%0*x",
795 back_descriptor, name, type_descriptor, width, index);
796 } else {
797 outSize = snprintf(buf.get(), buf_size, "<field?> // field@%0*x", width, index);
798 }
799 break;
800 case Instruction::kIndexVtableOffset:
801 outSize = snprintf(buf.get(), buf_size, "[%0*x] // vtable #%0*x",
802 width, index, width, index);
803 break;
804 case Instruction::kIndexFieldOffset:
805 outSize = snprintf(buf.get(), buf_size, "[obj+%0*x]", width, index);
806 break;
807 // SOME NOT SUPPORTED:
808 // case Instruction::kIndexVaries:
809 // case Instruction::kIndexInlineMethod:
810 default:
811 outSize = snprintf(buf.get(), buf_size, "<?>");
812 break;
813 } // switch
814
815 // Determine success of string construction.
816 if (outSize >= buf_size) {
817 // The buffer wasn't big enough; retry with computed size. Note: snprintf()
818 // doesn't count/ the '\0' as part of its returned size, so we add explicit
819 // space for it here.
820 return IndexString(header, dec_insn, outSize + 1);
821 }
822 return buf;
823}
824
825/*
826 * Dumps a single instruction.
827 */
828static void DumpInstruction(dex_ir::Header* header, const dex_ir::CodeItem* code,
829 uint32_t code_offset, uint32_t insn_idx, uint32_t insn_width,
830 const Instruction* dec_insn) {
831 // Address of instruction (expressed as byte offset).
832 fprintf(out_file_, "%06x:", code_offset + 0x10 + insn_idx * 2);
833
834 // Dump (part of) raw bytes.
835 const uint16_t* insns = code->Insns();
836 for (uint32_t i = 0; i < 8; i++) {
837 if (i < insn_width) {
838 if (i == 7) {
839 fprintf(out_file_, " ... ");
840 } else {
841 // Print 16-bit value in little-endian order.
842 const uint8_t* bytePtr = (const uint8_t*) &insns[insn_idx + i];
843 fprintf(out_file_, " %02x%02x", bytePtr[0], bytePtr[1]);
844 }
845 } else {
846 fputs(" ", out_file_);
847 }
848 } // for
849
850 // Dump pseudo-instruction or opcode.
851 if (dec_insn->Opcode() == Instruction::NOP) {
852 const uint16_t instr = Get2LE((const uint8_t*) &insns[insn_idx]);
853 if (instr == Instruction::kPackedSwitchSignature) {
854 fprintf(out_file_, "|%04x: packed-switch-data (%d units)", insn_idx, insn_width);
855 } else if (instr == Instruction::kSparseSwitchSignature) {
856 fprintf(out_file_, "|%04x: sparse-switch-data (%d units)", insn_idx, insn_width);
857 } else if (instr == Instruction::kArrayDataSignature) {
858 fprintf(out_file_, "|%04x: array-data (%d units)", insn_idx, insn_width);
859 } else {
860 fprintf(out_file_, "|%04x: nop // spacer", insn_idx);
861 }
862 } else {
863 fprintf(out_file_, "|%04x: %s", insn_idx, dec_insn->Name());
864 }
865
866 // Set up additional argument.
867 std::unique_ptr<char[]> index_buf;
868 if (Instruction::IndexTypeOf(dec_insn->Opcode()) != Instruction::kIndexNone) {
869 index_buf = IndexString(header, dec_insn, 200);
870 }
871
872 // Dump the instruction.
873 //
874 // NOTE: pDecInsn->DumpString(pDexFile) differs too much from original.
875 //
876 switch (Instruction::FormatOf(dec_insn->Opcode())) {
877 case Instruction::k10x: // op
878 break;
879 case Instruction::k12x: // op vA, vB
880 fprintf(out_file_, " v%d, v%d", dec_insn->VRegA(), dec_insn->VRegB());
881 break;
882 case Instruction::k11n: // op vA, #+B
883 fprintf(out_file_, " v%d, #int %d // #%x",
884 dec_insn->VRegA(), (int32_t) dec_insn->VRegB(), (uint8_t)dec_insn->VRegB());
885 break;
886 case Instruction::k11x: // op vAA
887 fprintf(out_file_, " v%d", dec_insn->VRegA());
888 break;
889 case Instruction::k10t: // op +AA
890 case Instruction::k20t: { // op +AAAA
891 const int32_t targ = (int32_t) dec_insn->VRegA();
892 fprintf(out_file_, " %04x // %c%04x",
893 insn_idx + targ,
894 (targ < 0) ? '-' : '+',
895 (targ < 0) ? -targ : targ);
896 break;
897 }
898 case Instruction::k22x: // op vAA, vBBBB
899 fprintf(out_file_, " v%d, v%d", dec_insn->VRegA(), dec_insn->VRegB());
900 break;
901 case Instruction::k21t: { // op vAA, +BBBB
902 const int32_t targ = (int32_t) dec_insn->VRegB();
903 fprintf(out_file_, " v%d, %04x // %c%04x", dec_insn->VRegA(),
904 insn_idx + targ,
905 (targ < 0) ? '-' : '+',
906 (targ < 0) ? -targ : targ);
907 break;
908 }
909 case Instruction::k21s: // op vAA, #+BBBB
910 fprintf(out_file_, " v%d, #int %d // #%x",
911 dec_insn->VRegA(), (int32_t) dec_insn->VRegB(), (uint16_t)dec_insn->VRegB());
912 break;
913 case Instruction::k21h: // op vAA, #+BBBB0000[00000000]
914 // The printed format varies a bit based on the actual opcode.
915 if (dec_insn->Opcode() == Instruction::CONST_HIGH16) {
916 const int32_t value = dec_insn->VRegB() << 16;
917 fprintf(out_file_, " v%d, #int %d // #%x",
918 dec_insn->VRegA(), value, (uint16_t) dec_insn->VRegB());
919 } else {
920 const int64_t value = ((int64_t) dec_insn->VRegB()) << 48;
921 fprintf(out_file_, " v%d, #long %" PRId64 " // #%x",
922 dec_insn->VRegA(), value, (uint16_t) dec_insn->VRegB());
923 }
924 break;
925 case Instruction::k21c: // op vAA, thing@BBBB
926 case Instruction::k31c: // op vAA, thing@BBBBBBBB
927 fprintf(out_file_, " v%d, %s", dec_insn->VRegA(), index_buf.get());
928 break;
929 case Instruction::k23x: // op vAA, vBB, vCC
930 fprintf(out_file_, " v%d, v%d, v%d",
931 dec_insn->VRegA(), dec_insn->VRegB(), dec_insn->VRegC());
932 break;
933 case Instruction::k22b: // op vAA, vBB, #+CC
934 fprintf(out_file_, " v%d, v%d, #int %d // #%02x",
935 dec_insn->VRegA(), dec_insn->VRegB(),
936 (int32_t) dec_insn->VRegC(), (uint8_t) dec_insn->VRegC());
937 break;
938 case Instruction::k22t: { // op vA, vB, +CCCC
939 const int32_t targ = (int32_t) dec_insn->VRegC();
940 fprintf(out_file_, " v%d, v%d, %04x // %c%04x",
941 dec_insn->VRegA(), dec_insn->VRegB(),
942 insn_idx + targ,
943 (targ < 0) ? '-' : '+',
944 (targ < 0) ? -targ : targ);
945 break;
946 }
947 case Instruction::k22s: // op vA, vB, #+CCCC
948 fprintf(out_file_, " v%d, v%d, #int %d // #%04x",
949 dec_insn->VRegA(), dec_insn->VRegB(),
950 (int32_t) dec_insn->VRegC(), (uint16_t) dec_insn->VRegC());
951 break;
952 case Instruction::k22c: // op vA, vB, thing@CCCC
953 // NOT SUPPORTED:
954 // case Instruction::k22cs: // [opt] op vA, vB, field offset CCCC
955 fprintf(out_file_, " v%d, v%d, %s",
956 dec_insn->VRegA(), dec_insn->VRegB(), index_buf.get());
957 break;
958 case Instruction::k30t:
959 fprintf(out_file_, " #%08x", dec_insn->VRegA());
960 break;
961 case Instruction::k31i: { // op vAA, #+BBBBBBBB
962 // This is often, but not always, a float.
963 union {
964 float f;
965 uint32_t i;
966 } conv;
967 conv.i = dec_insn->VRegB();
968 fprintf(out_file_, " v%d, #float %g // #%08x",
969 dec_insn->VRegA(), conv.f, dec_insn->VRegB());
970 break;
971 }
972 case Instruction::k31t: // op vAA, offset +BBBBBBBB
973 fprintf(out_file_, " v%d, %08x // +%08x",
974 dec_insn->VRegA(), insn_idx + dec_insn->VRegB(), dec_insn->VRegB());
975 break;
976 case Instruction::k32x: // op vAAAA, vBBBB
977 fprintf(out_file_, " v%d, v%d", dec_insn->VRegA(), dec_insn->VRegB());
978 break;
979 case Instruction::k35c: { // op {vC, vD, vE, vF, vG}, thing@BBBB
980 // NOT SUPPORTED:
981 // case Instruction::k35ms: // [opt] invoke-virtual+super
982 // case Instruction::k35mi: // [opt] inline invoke
983 uint32_t arg[Instruction::kMaxVarArgRegs];
984 dec_insn->GetVarArgs(arg);
985 fputs(" {", out_file_);
986 for (int i = 0, n = dec_insn->VRegA(); i < n; i++) {
987 if (i == 0) {
988 fprintf(out_file_, "v%d", arg[i]);
989 } else {
990 fprintf(out_file_, ", v%d", arg[i]);
991 }
992 } // for
993 fprintf(out_file_, "}, %s", index_buf.get());
994 break;
995 }
996 case Instruction::k3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB
997 // NOT SUPPORTED:
998 // case Instruction::k3rms: // [opt] invoke-virtual+super/range
999 // case Instruction::k3rmi: // [opt] execute-inline/range
1000 {
1001 // This doesn't match the "dx" output when some of the args are
1002 // 64-bit values -- dx only shows the first register.
1003 fputs(" {", out_file_);
1004 for (int i = 0, n = dec_insn->VRegA(); i < n; i++) {
1005 if (i == 0) {
1006 fprintf(out_file_, "v%d", dec_insn->VRegC() + i);
1007 } else {
1008 fprintf(out_file_, ", v%d", dec_insn->VRegC() + i);
1009 }
1010 } // for
1011 fprintf(out_file_, "}, %s", index_buf.get());
1012 }
1013 break;
1014 case Instruction::k51l: { // op vAA, #+BBBBBBBBBBBBBBBB
1015 // This is often, but not always, a double.
1016 union {
1017 double d;
1018 uint64_t j;
1019 } conv;
1020 conv.j = dec_insn->WideVRegB();
1021 fprintf(out_file_, " v%d, #double %g // #%016" PRIx64,
1022 dec_insn->VRegA(), conv.d, dec_insn->WideVRegB());
1023 break;
1024 }
1025 // NOT SUPPORTED:
1026 // case Instruction::k00x: // unknown op or breakpoint
1027 // break;
1028 default:
1029 fprintf(out_file_, " ???");
1030 break;
1031 } // switch
1032
1033 fputc('\n', out_file_);
1034}
1035
1036/*
1037 * Dumps a bytecode disassembly.
1038 */
1039static void DumpBytecodes(dex_ir::Header* header, uint32_t idx,
1040 const dex_ir::CodeItem* code, uint32_t code_offset) {
Jeff Hao3ab96b42016-09-09 18:35:01 -07001041 dex_ir::MethodId* method_id = header->GetCollections().GetMethodId(idx);
David Sehr7629f602016-08-07 16:01:51 -07001042 const char* name = method_id->Name()->Data();
David Sehr72359222016-09-07 13:04:01 -07001043 std::string type_descriptor = GetSignatureForProtoId(method_id->Proto());
David Sehr7629f602016-08-07 16:01:51 -07001044 const char* back_descriptor = method_id->Class()->GetStringId()->Data();
1045
1046 // Generate header.
Jeff Haoc3acfc52016-08-29 14:18:26 -07001047 std::string dot(DescriptorToDotWrapper(back_descriptor));
David Sehr7629f602016-08-07 16:01:51 -07001048 fprintf(out_file_, "%06x: |[%06x] %s.%s:%s\n",
David Sehr72359222016-09-07 13:04:01 -07001049 code_offset, code_offset, dot.c_str(), name, type_descriptor.c_str());
David Sehr7629f602016-08-07 16:01:51 -07001050
1051 // Iterate over all instructions.
1052 const uint16_t* insns = code->Insns();
1053 for (uint32_t insn_idx = 0; insn_idx < code->InsnsSize();) {
1054 const Instruction* instruction = Instruction::At(&insns[insn_idx]);
1055 const uint32_t insn_width = instruction->SizeInCodeUnits();
1056 if (insn_width == 0) {
1057 fprintf(stderr, "GLITCH: zero-width instruction at idx=0x%04x\n", insn_idx);
1058 break;
1059 }
1060 DumpInstruction(header, code, code_offset, insn_idx, insn_width, instruction);
1061 insn_idx += insn_width;
1062 } // for
1063}
1064
1065/*
1066 * Dumps code of a method.
1067 */
1068static void DumpCode(dex_ir::Header* header, uint32_t idx, const dex_ir::CodeItem* code,
1069 uint32_t code_offset) {
1070 fprintf(out_file_, " registers : %d\n", code->RegistersSize());
1071 fprintf(out_file_, " ins : %d\n", code->InsSize());
1072 fprintf(out_file_, " outs : %d\n", code->OutsSize());
1073 fprintf(out_file_, " insns size : %d 16-bit code units\n",
1074 code->InsnsSize());
1075
1076 // Bytecode disassembly, if requested.
1077 if (options_.disassemble_) {
1078 DumpBytecodes(header, idx, code, code_offset);
1079 }
1080
1081 // Try-catch blocks.
1082 DumpCatches(code);
1083
1084 // Positions and locals table in the debug info.
1085 fprintf(out_file_, " positions : \n");
1086 DumpPositionInfo(code);
1087 fprintf(out_file_, " locals : \n");
1088 DumpLocalInfo(code);
1089}
1090
1091/*
1092 * Dumps a method.
1093 */
1094static void DumpMethod(dex_ir::Header* header, uint32_t idx, uint32_t flags,
1095 const dex_ir::CodeItem* code, int i) {
1096 // Bail for anything private if export only requested.
1097 if (options_.exports_only_ && (flags & (kAccPublic | kAccProtected)) == 0) {
1098 return;
1099 }
1100
Jeff Hao3ab96b42016-09-09 18:35:01 -07001101 dex_ir::MethodId* method_id = header->GetCollections().GetMethodId(idx);
David Sehr7629f602016-08-07 16:01:51 -07001102 const char* name = method_id->Name()->Data();
1103 char* type_descriptor = strdup(GetSignatureForProtoId(method_id->Proto()).c_str());
1104 const char* back_descriptor = method_id->Class()->GetStringId()->Data();
1105 char* access_str = CreateAccessFlagStr(flags, kAccessForMethod);
1106
1107 if (options_.output_format_ == kOutputPlain) {
1108 fprintf(out_file_, " #%d : (in %s)\n", i, back_descriptor);
1109 fprintf(out_file_, " name : '%s'\n", name);
1110 fprintf(out_file_, " type : '%s'\n", type_descriptor);
1111 fprintf(out_file_, " access : 0x%04x (%s)\n", flags, access_str);
1112 if (code == nullptr) {
1113 fprintf(out_file_, " code : (none)\n");
1114 } else {
1115 fprintf(out_file_, " code -\n");
1116 DumpCode(header, idx, code, code->GetOffset());
1117 }
1118 if (options_.disassemble_) {
1119 fputc('\n', out_file_);
1120 }
1121 } else if (options_.output_format_ == kOutputXml) {
1122 const bool constructor = (name[0] == '<');
1123
1124 // Method name and prototype.
1125 if (constructor) {
1126 std::string dot(DescriptorClassToDot(back_descriptor));
1127 fprintf(out_file_, "<constructor name=\"%s\"\n", dot.c_str());
Jeff Haoc3acfc52016-08-29 14:18:26 -07001128 dot = DescriptorToDotWrapper(back_descriptor);
David Sehr7629f602016-08-07 16:01:51 -07001129 fprintf(out_file_, " type=\"%s\"\n", dot.c_str());
1130 } else {
1131 fprintf(out_file_, "<method name=\"%s\"\n", name);
1132 const char* return_type = strrchr(type_descriptor, ')');
1133 if (return_type == nullptr) {
1134 fprintf(stderr, "bad method type descriptor '%s'\n", type_descriptor);
1135 goto bail;
1136 }
Jeff Haoc3acfc52016-08-29 14:18:26 -07001137 std::string dot(DescriptorToDotWrapper(return_type + 1));
David Sehr7629f602016-08-07 16:01:51 -07001138 fprintf(out_file_, " return=\"%s\"\n", dot.c_str());
1139 fprintf(out_file_, " abstract=%s\n", QuotedBool((flags & kAccAbstract) != 0));
1140 fprintf(out_file_, " native=%s\n", QuotedBool((flags & kAccNative) != 0));
1141 fprintf(out_file_, " synchronized=%s\n", QuotedBool(
1142 (flags & (kAccSynchronized | kAccDeclaredSynchronized)) != 0));
1143 }
1144
1145 // Additional method flags.
1146 fprintf(out_file_, " static=%s\n", QuotedBool((flags & kAccStatic) != 0));
1147 fprintf(out_file_, " final=%s\n", QuotedBool((flags & kAccFinal) != 0));
1148 // The "deprecated=" not knowable w/o parsing annotations.
1149 fprintf(out_file_, " visibility=%s\n>\n", QuotedVisibility(flags));
1150
1151 // Parameters.
1152 if (type_descriptor[0] != '(') {
1153 fprintf(stderr, "ERROR: bad descriptor '%s'\n", type_descriptor);
1154 goto bail;
1155 }
1156 char* tmp_buf = reinterpret_cast<char*>(malloc(strlen(type_descriptor) + 1));
1157 const char* base = type_descriptor + 1;
1158 int arg_num = 0;
1159 while (*base != ')') {
1160 char* cp = tmp_buf;
1161 while (*base == '[') {
1162 *cp++ = *base++;
1163 }
1164 if (*base == 'L') {
1165 // Copy through ';'.
1166 do {
1167 *cp = *base++;
1168 } while (*cp++ != ';');
1169 } else {
1170 // Primitive char, copy it.
1171 if (strchr("ZBCSIFJD", *base) == nullptr) {
1172 fprintf(stderr, "ERROR: bad method signature '%s'\n", base);
1173 break; // while
1174 }
1175 *cp++ = *base++;
1176 }
1177 // Null terminate and display.
1178 *cp++ = '\0';
Jeff Haoc3acfc52016-08-29 14:18:26 -07001179 std::string dot(DescriptorToDotWrapper(tmp_buf));
David Sehr7629f602016-08-07 16:01:51 -07001180 fprintf(out_file_, "<parameter name=\"arg%d\" type=\"%s\">\n"
1181 "</parameter>\n", arg_num++, dot.c_str());
1182 } // while
1183 free(tmp_buf);
1184 if (constructor) {
1185 fprintf(out_file_, "</constructor>\n");
1186 } else {
1187 fprintf(out_file_, "</method>\n");
1188 }
1189 }
1190
1191 bail:
1192 free(type_descriptor);
1193 free(access_str);
1194}
1195
1196/*
1197 * Dumps a static (class) field.
1198 */
1199static void DumpSField(dex_ir::Header* header, uint32_t idx, uint32_t flags,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001200 int i, dex_ir::EncodedValue* init) {
David Sehr7629f602016-08-07 16:01:51 -07001201 // Bail for anything private if export only requested.
1202 if (options_.exports_only_ && (flags & (kAccPublic | kAccProtected)) == 0) {
1203 return;
1204 }
1205
Jeff Hao3ab96b42016-09-09 18:35:01 -07001206 dex_ir::FieldId* field_id = header->GetCollections().GetFieldId(idx);
David Sehr7629f602016-08-07 16:01:51 -07001207 const char* name = field_id->Name()->Data();
1208 const char* type_descriptor = field_id->Type()->GetStringId()->Data();
1209 const char* back_descriptor = field_id->Class()->GetStringId()->Data();
1210 char* access_str = CreateAccessFlagStr(flags, kAccessForField);
1211
1212 if (options_.output_format_ == kOutputPlain) {
1213 fprintf(out_file_, " #%d : (in %s)\n", i, back_descriptor);
1214 fprintf(out_file_, " name : '%s'\n", name);
1215 fprintf(out_file_, " type : '%s'\n", type_descriptor);
1216 fprintf(out_file_, " access : 0x%04x (%s)\n", flags, access_str);
1217 if (init != nullptr) {
1218 fputs(" value : ", out_file_);
1219 DumpEncodedValue(init);
1220 fputs("\n", out_file_);
1221 }
1222 } else if (options_.output_format_ == kOutputXml) {
1223 fprintf(out_file_, "<field name=\"%s\"\n", name);
Jeff Haoc3acfc52016-08-29 14:18:26 -07001224 std::string dot(DescriptorToDotWrapper(type_descriptor));
David Sehr7629f602016-08-07 16:01:51 -07001225 fprintf(out_file_, " type=\"%s\"\n", dot.c_str());
1226 fprintf(out_file_, " transient=%s\n", QuotedBool((flags & kAccTransient) != 0));
1227 fprintf(out_file_, " volatile=%s\n", QuotedBool((flags & kAccVolatile) != 0));
1228 // The "value=" is not knowable w/o parsing annotations.
1229 fprintf(out_file_, " static=%s\n", QuotedBool((flags & kAccStatic) != 0));
1230 fprintf(out_file_, " final=%s\n", QuotedBool((flags & kAccFinal) != 0));
1231 // The "deprecated=" is not knowable w/o parsing annotations.
1232 fprintf(out_file_, " visibility=%s\n", QuotedVisibility(flags));
1233 if (init != nullptr) {
1234 fputs(" value=\"", out_file_);
1235 DumpEncodedValue(init);
1236 fputs("\"\n", out_file_);
1237 }
1238 fputs(">\n</field>\n", out_file_);
1239 }
1240
1241 free(access_str);
1242}
1243
1244/*
1245 * Dumps an instance field.
1246 */
1247static void DumpIField(dex_ir::Header* header, uint32_t idx, uint32_t flags, int i) {
1248 DumpSField(header, idx, flags, i, nullptr);
1249}
1250
1251/*
1252 * Dumping a CFG. Note that this will do duplicate work. utils.h doesn't expose the code-item
1253 * version, so the DumpMethodCFG code will have to iterate again to find it. But dexdump is a
1254 * tool, so this is not performance-critical.
1255 */
1256
1257static void DumpCFG(const DexFile* dex_file,
1258 uint32_t dex_method_idx,
1259 const DexFile::CodeItem* code) {
1260 if (code != nullptr) {
1261 std::ostringstream oss;
1262 DumpMethodCFG(dex_file, dex_method_idx, oss);
1263 fprintf(out_file_, "%s", oss.str().c_str());
1264 }
1265}
1266
1267static void DumpCFG(const DexFile* dex_file, int idx) {
1268 const DexFile::ClassDef& class_def = dex_file->GetClassDef(idx);
1269 const uint8_t* class_data = dex_file->GetClassData(class_def);
1270 if (class_data == nullptr) { // empty class such as a marker interface?
1271 return;
1272 }
1273 ClassDataItemIterator it(*dex_file, class_data);
1274 while (it.HasNextStaticField()) {
1275 it.Next();
1276 }
1277 while (it.HasNextInstanceField()) {
1278 it.Next();
1279 }
1280 while (it.HasNextDirectMethod()) {
1281 DumpCFG(dex_file,
1282 it.GetMemberIndex(),
1283 it.GetMethodCodeItem());
1284 it.Next();
1285 }
1286 while (it.HasNextVirtualMethod()) {
1287 DumpCFG(dex_file,
David Sehr853a8e12016-09-01 13:03:50 -07001288 it.GetMemberIndex(),
1289 it.GetMethodCodeItem());
David Sehr7629f602016-08-07 16:01:51 -07001290 it.Next();
1291 }
1292}
1293
1294/*
1295 * Dumps the class.
1296 *
1297 * Note "idx" is a DexClassDef index, not a DexTypeId index.
1298 *
1299 * If "*last_package" is nullptr or does not match the current class' package,
1300 * the value will be replaced with a newly-allocated string.
1301 */
David Sehr853a8e12016-09-01 13:03:50 -07001302static void DumpClass(const DexFile* dex_file,
1303 dex_ir::Header* header,
1304 int idx,
1305 char** last_package) {
Jeff Hao3ab96b42016-09-09 18:35:01 -07001306 dex_ir::ClassDef* class_def = header->GetCollections().GetClassDef(idx);
David Sehr7629f602016-08-07 16:01:51 -07001307 // Omitting non-public class.
1308 if (options_.exports_only_ && (class_def->GetAccessFlags() & kAccPublic) == 0) {
1309 return;
1310 }
1311
1312 if (options_.show_section_headers_) {
1313 DumpClassDef(header, idx);
1314 }
1315
1316 if (options_.show_annotations_) {
1317 DumpClassAnnotations(header, idx);
1318 }
1319
1320 if (options_.show_cfg_) {
David Sehr853a8e12016-09-01 13:03:50 -07001321 DumpCFG(dex_file, idx);
David Sehr7629f602016-08-07 16:01:51 -07001322 return;
1323 }
1324
1325 // For the XML output, show the package name. Ideally we'd gather
1326 // up the classes, sort them, and dump them alphabetically so the
1327 // package name wouldn't jump around, but that's not a great plan
1328 // for something that needs to run on the device.
Jeff Hao3ab96b42016-09-09 18:35:01 -07001329 const char* class_descriptor =
1330 header->GetCollections().GetClassDef(idx)->ClassType()->GetStringId()->Data();
David Sehr7629f602016-08-07 16:01:51 -07001331 if (!(class_descriptor[0] == 'L' &&
1332 class_descriptor[strlen(class_descriptor)-1] == ';')) {
1333 // Arrays and primitives should not be defined explicitly. Keep going?
1334 fprintf(stderr, "Malformed class name '%s'\n", class_descriptor);
1335 } else if (options_.output_format_ == kOutputXml) {
1336 char* mangle = strdup(class_descriptor + 1);
1337 mangle[strlen(mangle)-1] = '\0';
1338
1339 // Reduce to just the package name.
1340 char* last_slash = strrchr(mangle, '/');
1341 if (last_slash != nullptr) {
1342 *last_slash = '\0';
1343 } else {
1344 *mangle = '\0';
1345 }
1346
1347 for (char* cp = mangle; *cp != '\0'; cp++) {
1348 if (*cp == '/') {
1349 *cp = '.';
1350 }
1351 } // for
1352
1353 if (*last_package == nullptr || strcmp(mangle, *last_package) != 0) {
1354 // Start of a new package.
1355 if (*last_package != nullptr) {
1356 fprintf(out_file_, "</package>\n");
1357 }
1358 fprintf(out_file_, "<package name=\"%s\"\n>\n", mangle);
1359 free(*last_package);
1360 *last_package = mangle;
1361 } else {
1362 free(mangle);
1363 }
1364 }
1365
1366 // General class information.
1367 char* access_str = CreateAccessFlagStr(class_def->GetAccessFlags(), kAccessForClass);
1368 const char* superclass_descriptor = nullptr;
1369 if (class_def->Superclass() != nullptr) {
1370 superclass_descriptor = class_def->Superclass()->GetStringId()->Data();
1371 }
1372 if (options_.output_format_ == kOutputPlain) {
1373 fprintf(out_file_, "Class #%d -\n", idx);
1374 fprintf(out_file_, " Class descriptor : '%s'\n", class_descriptor);
1375 fprintf(out_file_, " Access flags : 0x%04x (%s)\n",
1376 class_def->GetAccessFlags(), access_str);
1377 if (superclass_descriptor != nullptr) {
1378 fprintf(out_file_, " Superclass : '%s'\n", superclass_descriptor);
1379 }
1380 fprintf(out_file_, " Interfaces -\n");
1381 } else {
1382 std::string dot(DescriptorClassToDot(class_descriptor));
1383 fprintf(out_file_, "<class name=\"%s\"\n", dot.c_str());
1384 if (superclass_descriptor != nullptr) {
Jeff Haoc3acfc52016-08-29 14:18:26 -07001385 dot = DescriptorToDotWrapper(superclass_descriptor);
David Sehr7629f602016-08-07 16:01:51 -07001386 fprintf(out_file_, " extends=\"%s\"\n", dot.c_str());
1387 }
1388 fprintf(out_file_, " interface=%s\n",
1389 QuotedBool((class_def->GetAccessFlags() & kAccInterface) != 0));
1390 fprintf(out_file_, " abstract=%s\n",
1391 QuotedBool((class_def->GetAccessFlags() & kAccAbstract) != 0));
1392 fprintf(out_file_, " static=%s\n", QuotedBool((class_def->GetAccessFlags() & kAccStatic) != 0));
1393 fprintf(out_file_, " final=%s\n", QuotedBool((class_def->GetAccessFlags() & kAccFinal) != 0));
1394 // The "deprecated=" not knowable w/o parsing annotations.
1395 fprintf(out_file_, " visibility=%s\n", QuotedVisibility(class_def->GetAccessFlags()));
1396 fprintf(out_file_, ">\n");
1397 }
1398
1399 // Interfaces.
Jeff Hao3ab96b42016-09-09 18:35:01 -07001400 const dex_ir::TypeIdVector* interfaces = class_def->Interfaces();
David Sehr853a8e12016-09-01 13:03:50 -07001401 if (interfaces != nullptr) {
1402 for (uint32_t i = 0; i < interfaces->size(); i++) {
1403 DumpInterface((*interfaces)[i], i);
1404 } // for
1405 }
David Sehr7629f602016-08-07 16:01:51 -07001406
1407 // Fields and methods.
1408 dex_ir::ClassData* class_data = class_def->GetClassData();
1409 // Prepare data for static fields.
Jeff Hao3ab96b42016-09-09 18:35:01 -07001410 dex_ir::EncodedArrayItem* static_values = class_def->StaticValues();
1411 dex_ir::EncodedValueVector* encoded_values =
1412 static_values == nullptr ? nullptr : static_values->GetEncodedValues();
1413 const uint32_t encoded_values_size = (encoded_values == nullptr) ? 0 : encoded_values->size();
David Sehr7629f602016-08-07 16:01:51 -07001414
1415 // Static fields.
1416 if (options_.output_format_ == kOutputPlain) {
1417 fprintf(out_file_, " Static fields -\n");
1418 }
David Sehr853a8e12016-09-01 13:03:50 -07001419 if (class_data != nullptr) {
1420 dex_ir::FieldItemVector* static_fields = class_data->StaticFields();
1421 if (static_fields != nullptr) {
1422 for (uint32_t i = 0; i < static_fields->size(); i++) {
1423 DumpSField(header,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001424 (*static_fields)[i]->GetFieldId()->GetIndex(),
David Sehr853a8e12016-09-01 13:03:50 -07001425 (*static_fields)[i]->GetAccessFlags(),
1426 i,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001427 i < encoded_values_size ? (*encoded_values)[i].get() : nullptr);
David Sehr853a8e12016-09-01 13:03:50 -07001428 } // for
1429 }
1430 }
David Sehr7629f602016-08-07 16:01:51 -07001431
1432 // Instance fields.
1433 if (options_.output_format_ == kOutputPlain) {
1434 fprintf(out_file_, " Instance fields -\n");
1435 }
David Sehr853a8e12016-09-01 13:03:50 -07001436 if (class_data != nullptr) {
1437 dex_ir::FieldItemVector* instance_fields = class_data->InstanceFields();
1438 if (instance_fields != nullptr) {
1439 for (uint32_t i = 0; i < instance_fields->size(); i++) {
1440 DumpIField(header,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001441 (*instance_fields)[i]->GetFieldId()->GetIndex(),
David Sehr853a8e12016-09-01 13:03:50 -07001442 (*instance_fields)[i]->GetAccessFlags(),
1443 i);
1444 } // for
1445 }
1446 }
David Sehr7629f602016-08-07 16:01:51 -07001447
1448 // Direct methods.
1449 if (options_.output_format_ == kOutputPlain) {
1450 fprintf(out_file_, " Direct methods -\n");
1451 }
David Sehr853a8e12016-09-01 13:03:50 -07001452 if (class_data != nullptr) {
1453 dex_ir::MethodItemVector* direct_methods = class_data->DirectMethods();
1454 if (direct_methods != nullptr) {
1455 for (uint32_t i = 0; i < direct_methods->size(); i++) {
1456 DumpMethod(header,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001457 (*direct_methods)[i]->GetMethodId()->GetIndex(),
David Sehr853a8e12016-09-01 13:03:50 -07001458 (*direct_methods)[i]->GetAccessFlags(),
1459 (*direct_methods)[i]->GetCodeItem(),
1460 i);
1461 } // for
1462 }
1463 }
David Sehr7629f602016-08-07 16:01:51 -07001464
1465 // Virtual methods.
1466 if (options_.output_format_ == kOutputPlain) {
1467 fprintf(out_file_, " Virtual methods -\n");
1468 }
David Sehr853a8e12016-09-01 13:03:50 -07001469 if (class_data != nullptr) {
1470 dex_ir::MethodItemVector* virtual_methods = class_data->VirtualMethods();
1471 if (virtual_methods != nullptr) {
1472 for (uint32_t i = 0; i < virtual_methods->size(); i++) {
1473 DumpMethod(header,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001474 (*virtual_methods)[i]->GetMethodId()->GetIndex(),
David Sehr853a8e12016-09-01 13:03:50 -07001475 (*virtual_methods)[i]->GetAccessFlags(),
1476 (*virtual_methods)[i]->GetCodeItem(),
1477 i);
1478 } // for
1479 }
1480 }
David Sehr7629f602016-08-07 16:01:51 -07001481
1482 // End of class.
1483 if (options_.output_format_ == kOutputPlain) {
1484 const char* file_name = "unknown";
1485 if (class_def->SourceFile() != nullptr) {
1486 file_name = class_def->SourceFile()->Data();
1487 }
1488 const dex_ir::StringId* source_file = class_def->SourceFile();
1489 fprintf(out_file_, " source_file_idx : %d (%s)\n\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -07001490 source_file == nullptr ? 0xffffffffU : source_file->GetIndex(), file_name);
David Sehr7629f602016-08-07 16:01:51 -07001491 } else if (options_.output_format_ == kOutputXml) {
1492 fprintf(out_file_, "</class>\n");
1493 }
1494
1495 free(access_str);
1496}
1497
1498/*
1499 * Dumps the requested sections of the file.
1500 */
1501static void ProcessDexFile(const char* file_name, const DexFile* dex_file) {
1502 if (options_.verbose_) {
1503 fprintf(out_file_, "Opened '%s', DEX version '%.3s'\n",
1504 file_name, dex_file->GetHeader().magic_ + 4);
1505 }
David Sehr72359222016-09-07 13:04:01 -07001506 std::unique_ptr<dex_ir::Header> header(dex_ir::DexIrBuilder(*dex_file));
David Sehr7629f602016-08-07 16:01:51 -07001507
1508 // Headers.
1509 if (options_.show_file_headers_) {
David Sehr72359222016-09-07 13:04:01 -07001510 DumpFileHeader(header.get());
David Sehr7629f602016-08-07 16:01:51 -07001511 }
1512
1513 // Open XML context.
1514 if (options_.output_format_ == kOutputXml) {
1515 fprintf(out_file_, "<api>\n");
1516 }
1517
1518 // Iterate over all classes.
1519 char* package = nullptr;
Jeff Hao3ab96b42016-09-09 18:35:01 -07001520 const uint32_t class_defs_size = header->GetCollections().ClassDefsSize();
David Sehr7629f602016-08-07 16:01:51 -07001521 for (uint32_t i = 0; i < class_defs_size; i++) {
David Sehr72359222016-09-07 13:04:01 -07001522 DumpClass(dex_file, header.get(), i, &package);
David Sehr7629f602016-08-07 16:01:51 -07001523 } // for
1524
1525 // Free the last package allocated.
1526 if (package != nullptr) {
1527 fprintf(out_file_, "</package>\n");
1528 free(package);
1529 }
1530
1531 // Close XML context.
1532 if (options_.output_format_ == kOutputXml) {
1533 fprintf(out_file_, "</api>\n");
1534 }
Jeff Hao3ab96b42016-09-09 18:35:01 -07001535
Jeff Hao3ab96b42016-09-09 18:35:01 -07001536 // Output dex file.
1537 if (options_.output_dex_files_) {
1538 std::string output_dex_filename = dex_file->GetLocation() + ".out";
Jeff Hao69b58cf2016-09-22 18:02:49 -07001539 DexWriter::OutputDexFile(*header, output_dex_filename.c_str());
Jeff Hao3ab96b42016-09-09 18:35:01 -07001540 }
David Sehr7629f602016-08-07 16:01:51 -07001541}
1542
1543/*
1544 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
1545 */
1546int ProcessFile(const char* file_name) {
1547 if (options_.verbose_) {
1548 fprintf(out_file_, "Processing '%s'...\n", file_name);
1549 }
1550
1551 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
1552 // all of which are Zip archives with "classes.dex" inside.
1553 const bool verify_checksum = !options_.ignore_bad_checksum_;
1554 std::string error_msg;
1555 std::vector<std::unique_ptr<const DexFile>> dex_files;
1556 if (!DexFile::Open(file_name, file_name, verify_checksum, &error_msg, &dex_files)) {
1557 // Display returned error message to user. Note that this error behavior
1558 // differs from the error messages shown by the original Dalvik dexdump.
1559 fputs(error_msg.c_str(), stderr);
1560 fputc('\n', stderr);
1561 return -1;
1562 }
1563
1564 // Success. Either report checksum verification or process
1565 // all dex files found in given file.
1566 if (options_.checksum_only_) {
1567 fprintf(out_file_, "Checksum verified\n");
1568 } else {
1569 for (size_t i = 0; i < dex_files.size(); i++) {
1570 ProcessDexFile(file_name, dex_files[i].get());
1571 }
1572 }
1573 return 0;
1574}
1575
1576} // namespace art