blob: e6141372a6ca0baba3f70ce486d963ade2313c37 [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
Nicolas Geoffrayfd1a6c22016-10-04 11:01:17 +000033#include "base/unix_file/fd_file.h"
David Sehr853a8e12016-09-01 13:03:50 -070034#include "dex_ir_builder.h"
David Sehr7629f602016-08-07 16:01:51 -070035#include "dex_file-inl.h"
36#include "dex_instruction-inl.h"
David Sehrcdcfde72016-09-26 07:44:04 -070037#include "dex_visualize.h"
38#include "jit/offline_profiling_info.h"
Nicolas Geoffrayfd1a6c22016-10-04 11:01:17 +000039#include "os.h"
David Sehr7629f602016-08-07 16:01:51 -070040#include "utils.h"
41
42namespace art {
43
44/*
45 * Options parsed in main driver.
46 */
47struct Options options_;
48
49/*
50 * Output file. Defaults to stdout.
51 */
52FILE* out_file_ = stdout;
53
54/*
David Sehrcdcfde72016-09-26 07:44:04 -070055 * Profile information file.
56 */
57ProfileCompilationInfo* profile_info_ = nullptr;
58
59/*
David Sehr7629f602016-08-07 16:01:51 -070060 * Flags for use with createAccessFlagStr().
61 */
62enum AccessFor {
63 kAccessForClass = 0, kAccessForMethod = 1, kAccessForField = 2, kAccessForMAX
64};
65const int kNumFlags = 18;
66
67/*
68 * Gets 2 little-endian bytes.
69 */
70static inline uint16_t Get2LE(unsigned char const* src) {
71 return src[0] | (src[1] << 8);
72}
73
74/*
Jeff Haoc3acfc52016-08-29 14:18:26 -070075 * Converts a type descriptor to human-readable "dotted" form. For
76 * example, "Ljava/lang/String;" becomes "java.lang.String", and
77 * "[I" becomes "int[]". Also converts '$' to '.', which means this
78 * form can't be converted back to a descriptor.
79 */
80static std::string DescriptorToDotWrapper(const char* descriptor) {
81 std::string result = DescriptorToDot(descriptor);
82 size_t found = result.find('$');
83 while (found != std::string::npos) {
84 result[found] = '.';
85 found = result.find('$', found);
86 }
87 return result;
88}
89
90/*
David Sehr7629f602016-08-07 16:01:51 -070091 * Converts the class name portion of a type descriptor to human-readable
92 * "dotted" form. For example, "Ljava/lang/String;" becomes "String".
93 */
94static std::string DescriptorClassToDot(const char* str) {
95 std::string descriptor(str);
96 // Reduce to just the class name prefix.
97 size_t last_slash = descriptor.rfind('/');
98 if (last_slash == std::string::npos) {
99 last_slash = 0;
100 }
101 // Start past the '/' or 'L'.
102 last_slash++;
103
104 // Copy class name over, trimming trailing ';'.
105 size_t size = descriptor.size() - 1 - last_slash;
106 std::string result(descriptor.substr(last_slash, size));
107
108 // Replace '$' with '.'.
109 size_t dollar_sign = result.find('$');
110 while (dollar_sign != std::string::npos) {
111 result[dollar_sign] = '.';
112 dollar_sign = result.find('$', dollar_sign);
113 }
114
115 return result;
116}
117
118/*
119 * Returns string representing the boolean value.
120 */
121static const char* StrBool(bool val) {
122 return val ? "true" : "false";
123}
124
125/*
126 * Returns a quoted string representing the boolean value.
127 */
128static const char* QuotedBool(bool val) {
129 return val ? "\"true\"" : "\"false\"";
130}
131
132/*
133 * Returns a quoted string representing the access flags.
134 */
135static const char* QuotedVisibility(uint32_t access_flags) {
136 if (access_flags & kAccPublic) {
137 return "\"public\"";
138 } else if (access_flags & kAccProtected) {
139 return "\"protected\"";
140 } else if (access_flags & kAccPrivate) {
141 return "\"private\"";
142 } else {
143 return "\"package\"";
144 }
145}
146
147/*
148 * Counts the number of '1' bits in a word.
149 */
150static int CountOnes(uint32_t val) {
151 val = val - ((val >> 1) & 0x55555555);
152 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
153 return (((val + (val >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
154}
155
156/*
157 * Creates a new string with human-readable access flags.
158 *
159 * In the base language the access_flags fields are type uint16_t; in Dalvik they're uint32_t.
160 */
161static char* CreateAccessFlagStr(uint32_t flags, AccessFor for_what) {
162 static const char* kAccessStrings[kAccessForMAX][kNumFlags] = {
163 {
164 "PUBLIC", /* 0x00001 */
165 "PRIVATE", /* 0x00002 */
166 "PROTECTED", /* 0x00004 */
167 "STATIC", /* 0x00008 */
168 "FINAL", /* 0x00010 */
169 "?", /* 0x00020 */
170 "?", /* 0x00040 */
171 "?", /* 0x00080 */
172 "?", /* 0x00100 */
173 "INTERFACE", /* 0x00200 */
174 "ABSTRACT", /* 0x00400 */
175 "?", /* 0x00800 */
176 "SYNTHETIC", /* 0x01000 */
177 "ANNOTATION", /* 0x02000 */
178 "ENUM", /* 0x04000 */
179 "?", /* 0x08000 */
180 "VERIFIED", /* 0x10000 */
181 "OPTIMIZED", /* 0x20000 */
182 }, {
183 "PUBLIC", /* 0x00001 */
184 "PRIVATE", /* 0x00002 */
185 "PROTECTED", /* 0x00004 */
186 "STATIC", /* 0x00008 */
187 "FINAL", /* 0x00010 */
188 "SYNCHRONIZED", /* 0x00020 */
189 "BRIDGE", /* 0x00040 */
190 "VARARGS", /* 0x00080 */
191 "NATIVE", /* 0x00100 */
192 "?", /* 0x00200 */
193 "ABSTRACT", /* 0x00400 */
194 "STRICT", /* 0x00800 */
195 "SYNTHETIC", /* 0x01000 */
196 "?", /* 0x02000 */
197 "?", /* 0x04000 */
198 "MIRANDA", /* 0x08000 */
199 "CONSTRUCTOR", /* 0x10000 */
200 "DECLARED_SYNCHRONIZED", /* 0x20000 */
201 }, {
202 "PUBLIC", /* 0x00001 */
203 "PRIVATE", /* 0x00002 */
204 "PROTECTED", /* 0x00004 */
205 "STATIC", /* 0x00008 */
206 "FINAL", /* 0x00010 */
207 "?", /* 0x00020 */
208 "VOLATILE", /* 0x00040 */
209 "TRANSIENT", /* 0x00080 */
210 "?", /* 0x00100 */
211 "?", /* 0x00200 */
212 "?", /* 0x00400 */
213 "?", /* 0x00800 */
214 "SYNTHETIC", /* 0x01000 */
215 "?", /* 0x02000 */
216 "ENUM", /* 0x04000 */
217 "?", /* 0x08000 */
218 "?", /* 0x10000 */
219 "?", /* 0x20000 */
220 },
221 };
222
223 // Allocate enough storage to hold the expected number of strings,
224 // plus a space between each. We over-allocate, using the longest
225 // string above as the base metric.
226 const int kLongest = 21; // The strlen of longest string above.
227 const int count = CountOnes(flags);
228 char* str;
229 char* cp;
230 cp = str = reinterpret_cast<char*>(malloc(count * (kLongest + 1) + 1));
231
232 for (int i = 0; i < kNumFlags; i++) {
233 if (flags & 0x01) {
234 const char* accessStr = kAccessStrings[for_what][i];
235 const int len = strlen(accessStr);
236 if (cp != str) {
237 *cp++ = ' ';
238 }
239 memcpy(cp, accessStr, len);
240 cp += len;
241 }
242 flags >>= 1;
243 } // for
244
245 *cp = '\0';
246 return str;
247}
248
249static std::string GetSignatureForProtoId(const dex_ir::ProtoId* proto) {
250 if (proto == nullptr) {
251 return "<no signature>";
252 }
253
Nicolas Geoffrayfd1a6c22016-10-04 11:01:17 +0000254 const std::vector<const dex_ir::TypeId*>& params = proto->Parameters();
David Sehr7629f602016-08-07 16:01:51 -0700255 std::string result("(");
Nicolas Geoffrayfd1a6c22016-10-04 11:01:17 +0000256 for (uint32_t i = 0; i < params.size(); ++i) {
257 result += params[i]->GetStringId()->Data();
David Sehr7629f602016-08-07 16:01:51 -0700258 }
259 result += ")";
260 result += proto->ReturnType()->GetStringId()->Data();
261 return result;
262}
263
264/*
265 * Copies character data from "data" to "out", converting non-ASCII values
266 * to fprintf format chars or an ASCII filler ('.' or '?').
267 *
268 * The output buffer must be able to hold (2*len)+1 bytes. The result is
269 * NULL-terminated.
270 */
271static void Asciify(char* out, const unsigned char* data, size_t len) {
272 while (len--) {
273 if (*data < 0x20) {
274 // Could do more here, but we don't need them yet.
275 switch (*data) {
276 case '\0':
277 *out++ = '\\';
278 *out++ = '0';
279 break;
280 case '\n':
281 *out++ = '\\';
282 *out++ = 'n';
283 break;
284 default:
285 *out++ = '.';
286 break;
287 } // switch
288 } else if (*data >= 0x80) {
289 *out++ = '?';
290 } else {
291 *out++ = *data;
292 }
293 data++;
294 } // while
295 *out = '\0';
296}
297
298/*
299 * Dumps a string value with some escape characters.
300 */
301static void DumpEscapedString(const char* p) {
302 fputs("\"", out_file_);
303 for (; *p; p++) {
304 switch (*p) {
305 case '\\':
306 fputs("\\\\", out_file_);
307 break;
308 case '\"':
309 fputs("\\\"", out_file_);
310 break;
311 case '\t':
312 fputs("\\t", out_file_);
313 break;
314 case '\n':
315 fputs("\\n", out_file_);
316 break;
317 case '\r':
318 fputs("\\r", out_file_);
319 break;
320 default:
321 putc(*p, out_file_);
322 } // switch
323 } // for
324 fputs("\"", out_file_);
325}
326
327/*
328 * Dumps a string as an XML attribute value.
329 */
330static void DumpXmlAttribute(const char* p) {
331 for (; *p; p++) {
332 switch (*p) {
333 case '&':
334 fputs("&amp;", out_file_);
335 break;
336 case '<':
337 fputs("&lt;", out_file_);
338 break;
339 case '>':
340 fputs("&gt;", out_file_);
341 break;
342 case '"':
343 fputs("&quot;", out_file_);
344 break;
345 case '\t':
346 fputs("&#x9;", out_file_);
347 break;
348 case '\n':
349 fputs("&#xA;", out_file_);
350 break;
351 case '\r':
352 fputs("&#xD;", out_file_);
353 break;
354 default:
355 putc(*p, out_file_);
356 } // switch
357 } // for
358}
359
Jeff Hao3ab96b42016-09-09 18:35:01 -0700360// Forward declare to resolve circular dependence.
361static void DumpEncodedValue(const dex_ir::EncodedValue* data);
362
363/*
364 * Dumps encoded annotation.
365 */
366static void DumpEncodedAnnotation(dex_ir::EncodedAnnotation* annotation) {
367 fputs(annotation->GetType()->GetStringId()->Data(), out_file_);
368 // Display all name=value pairs.
369 for (auto& subannotation : *annotation->GetAnnotationElements()) {
370 fputc(' ', out_file_);
371 fputs(subannotation->GetName()->Data(), out_file_);
372 fputc('=', out_file_);
373 DumpEncodedValue(subannotation->GetValue());
374 }
375}
David Sehr7629f602016-08-07 16:01:51 -0700376/*
377 * Dumps encoded value.
378 */
Jeff Hao3ab96b42016-09-09 18:35:01 -0700379static void DumpEncodedValue(const dex_ir::EncodedValue* data) {
David Sehr7629f602016-08-07 16:01:51 -0700380 switch (data->Type()) {
381 case DexFile::kDexAnnotationByte:
382 fprintf(out_file_, "%" PRId8, data->GetByte());
383 break;
384 case DexFile::kDexAnnotationShort:
385 fprintf(out_file_, "%" PRId16, data->GetShort());
386 break;
387 case DexFile::kDexAnnotationChar:
388 fprintf(out_file_, "%" PRIu16, data->GetChar());
389 break;
390 case DexFile::kDexAnnotationInt:
391 fprintf(out_file_, "%" PRId32, data->GetInt());
392 break;
393 case DexFile::kDexAnnotationLong:
394 fprintf(out_file_, "%" PRId64, data->GetLong());
395 break;
396 case DexFile::kDexAnnotationFloat: {
397 fprintf(out_file_, "%g", data->GetFloat());
398 break;
399 }
400 case DexFile::kDexAnnotationDouble: {
401 fprintf(out_file_, "%g", data->GetDouble());
402 break;
403 }
404 case DexFile::kDexAnnotationString: {
405 dex_ir::StringId* string_id = data->GetStringId();
406 if (options_.output_format_ == kOutputPlain) {
407 DumpEscapedString(string_id->Data());
408 } else {
409 DumpXmlAttribute(string_id->Data());
410 }
411 break;
412 }
413 case DexFile::kDexAnnotationType: {
Jeff Hao3ab96b42016-09-09 18:35:01 -0700414 dex_ir::TypeId* type_id = data->GetTypeId();
415 fputs(type_id->GetStringId()->Data(), out_file_);
David Sehr7629f602016-08-07 16:01:51 -0700416 break;
417 }
418 case DexFile::kDexAnnotationField:
419 case DexFile::kDexAnnotationEnum: {
420 dex_ir::FieldId* field_id = data->GetFieldId();
421 fputs(field_id->Name()->Data(), out_file_);
422 break;
423 }
424 case DexFile::kDexAnnotationMethod: {
425 dex_ir::MethodId* method_id = data->GetMethodId();
426 fputs(method_id->Name()->Data(), out_file_);
427 break;
428 }
429 case DexFile::kDexAnnotationArray: {
430 fputc('{', out_file_);
431 // Display all elements.
Jeff Hao3ab96b42016-09-09 18:35:01 -0700432 for (auto& value : *data->GetEncodedArray()->GetEncodedValues()) {
David Sehr7629f602016-08-07 16:01:51 -0700433 fputc(' ', out_file_);
Jeff Hao3ab96b42016-09-09 18:35:01 -0700434 DumpEncodedValue(value.get());
David Sehr7629f602016-08-07 16:01:51 -0700435 }
436 fputs(" }", out_file_);
437 break;
438 }
439 case DexFile::kDexAnnotationAnnotation: {
Jeff Hao3ab96b42016-09-09 18:35:01 -0700440 DumpEncodedAnnotation(data->GetEncodedAnnotation());
David Sehr7629f602016-08-07 16:01:51 -0700441 break;
442 }
443 case DexFile::kDexAnnotationNull:
444 fputs("null", out_file_);
445 break;
446 case DexFile::kDexAnnotationBoolean:
447 fputs(StrBool(data->GetBoolean()), out_file_);
448 break;
449 default:
450 fputs("????", out_file_);
451 break;
452 } // switch
453}
454
455/*
456 * Dumps the file header.
457 */
Jeff Hao3ab96b42016-09-09 18:35:01 -0700458static void DumpFileHeader(dex_ir::Header* header) {
David Sehr7629f602016-08-07 16:01:51 -0700459 char sanitized[8 * 2 + 1];
Jeff Hao3ab96b42016-09-09 18:35:01 -0700460 dex_ir::Collections& collections = header->GetCollections();
David Sehr7629f602016-08-07 16:01:51 -0700461 fprintf(out_file_, "DEX file header:\n");
462 Asciify(sanitized, header->Magic(), 8);
463 fprintf(out_file_, "magic : '%s'\n", sanitized);
464 fprintf(out_file_, "checksum : %08x\n", header->Checksum());
465 fprintf(out_file_, "signature : %02x%02x...%02x%02x\n",
466 header->Signature()[0], header->Signature()[1],
467 header->Signature()[DexFile::kSha1DigestSize - 2],
468 header->Signature()[DexFile::kSha1DigestSize - 1]);
469 fprintf(out_file_, "file_size : %d\n", header->FileSize());
470 fprintf(out_file_, "header_size : %d\n", header->HeaderSize());
471 fprintf(out_file_, "link_size : %d\n", header->LinkSize());
472 fprintf(out_file_, "link_off : %d (0x%06x)\n",
473 header->LinkOffset(), header->LinkOffset());
Jeff Hao3ab96b42016-09-09 18:35:01 -0700474 fprintf(out_file_, "string_ids_size : %d\n", collections.StringIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700475 fprintf(out_file_, "string_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700476 collections.StringIdsOffset(), collections.StringIdsOffset());
477 fprintf(out_file_, "type_ids_size : %d\n", collections.TypeIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700478 fprintf(out_file_, "type_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700479 collections.TypeIdsOffset(), collections.TypeIdsOffset());
480 fprintf(out_file_, "proto_ids_size : %d\n", collections.ProtoIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700481 fprintf(out_file_, "proto_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700482 collections.ProtoIdsOffset(), collections.ProtoIdsOffset());
483 fprintf(out_file_, "field_ids_size : %d\n", collections.FieldIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700484 fprintf(out_file_, "field_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700485 collections.FieldIdsOffset(), collections.FieldIdsOffset());
486 fprintf(out_file_, "method_ids_size : %d\n", collections.MethodIdsSize());
David Sehr7629f602016-08-07 16:01:51 -0700487 fprintf(out_file_, "method_ids_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700488 collections.MethodIdsOffset(), collections.MethodIdsOffset());
489 fprintf(out_file_, "class_defs_size : %d\n", collections.ClassDefsSize());
David Sehr7629f602016-08-07 16:01:51 -0700490 fprintf(out_file_, "class_defs_off : %d (0x%06x)\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -0700491 collections.ClassDefsOffset(), collections.ClassDefsOffset());
David Sehr7629f602016-08-07 16:01:51 -0700492 fprintf(out_file_, "data_size : %d\n", header->DataSize());
493 fprintf(out_file_, "data_off : %d (0x%06x)\n\n",
494 header->DataOffset(), header->DataOffset());
495}
496
497/*
498 * Dumps a class_def_item.
499 */
500static void DumpClassDef(dex_ir::Header* header, int idx) {
501 // General class information.
Jeff Hao3ab96b42016-09-09 18:35:01 -0700502 dex_ir::ClassDef* class_def = header->GetCollections().GetClassDef(idx);
David Sehr7629f602016-08-07 16:01:51 -0700503 fprintf(out_file_, "Class #%d header:\n", idx);
Jeff Hao3ab96b42016-09-09 18:35:01 -0700504 fprintf(out_file_, "class_idx : %d\n", class_def->ClassType()->GetIndex());
David Sehr7629f602016-08-07 16:01:51 -0700505 fprintf(out_file_, "access_flags : %d (0x%04x)\n",
506 class_def->GetAccessFlags(), class_def->GetAccessFlags());
Jeff Haoc3acfc52016-08-29 14:18:26 -0700507 uint32_t superclass_idx = class_def->Superclass() == nullptr ?
Jeff Hao3ab96b42016-09-09 18:35:01 -0700508 DexFile::kDexNoIndex16 : class_def->Superclass()->GetIndex();
Jeff Haoc3acfc52016-08-29 14:18:26 -0700509 fprintf(out_file_, "superclass_idx : %d\n", superclass_idx);
David Sehr7629f602016-08-07 16:01:51 -0700510 fprintf(out_file_, "interfaces_off : %d (0x%06x)\n",
511 class_def->InterfacesOffset(), class_def->InterfacesOffset());
512 uint32_t source_file_offset = 0xffffffffU;
513 if (class_def->SourceFile() != nullptr) {
Jeff Hao3ab96b42016-09-09 18:35:01 -0700514 source_file_offset = class_def->SourceFile()->GetIndex();
David Sehr7629f602016-08-07 16:01:51 -0700515 }
516 fprintf(out_file_, "source_file_idx : %d\n", source_file_offset);
517 uint32_t annotations_offset = 0;
518 if (class_def->Annotations() != nullptr) {
519 annotations_offset = class_def->Annotations()->GetOffset();
520 }
521 fprintf(out_file_, "annotations_off : %d (0x%06x)\n",
522 annotations_offset, annotations_offset);
David Sehr853a8e12016-09-01 13:03:50 -0700523 if (class_def->GetClassData() == nullptr) {
524 fprintf(out_file_, "class_data_off : %d (0x%06x)\n", 0, 0);
525 } else {
526 fprintf(out_file_, "class_data_off : %d (0x%06x)\n",
527 class_def->GetClassData()->GetOffset(), class_def->GetClassData()->GetOffset());
528 }
David Sehr7629f602016-08-07 16:01:51 -0700529
530 // Fields and methods.
531 dex_ir::ClassData* class_data = class_def->GetClassData();
David Sehr853a8e12016-09-01 13:03:50 -0700532 if (class_data != nullptr && class_data->StaticFields() != nullptr) {
533 fprintf(out_file_, "static_fields_size : %zu\n", class_data->StaticFields()->size());
David Sehr7629f602016-08-07 16:01:51 -0700534 } else {
535 fprintf(out_file_, "static_fields_size : 0\n");
David Sehr853a8e12016-09-01 13:03:50 -0700536 }
537 if (class_data != nullptr && class_data->InstanceFields() != nullptr) {
538 fprintf(out_file_, "instance_fields_size: %zu\n", class_data->InstanceFields()->size());
539 } else {
David Sehr7629f602016-08-07 16:01:51 -0700540 fprintf(out_file_, "instance_fields_size: 0\n");
David Sehr853a8e12016-09-01 13:03:50 -0700541 }
542 if (class_data != nullptr && class_data->DirectMethods() != nullptr) {
543 fprintf(out_file_, "direct_methods_size : %zu\n", class_data->DirectMethods()->size());
544 } else {
David Sehr7629f602016-08-07 16:01:51 -0700545 fprintf(out_file_, "direct_methods_size : 0\n");
David Sehr853a8e12016-09-01 13:03:50 -0700546 }
547 if (class_data != nullptr && class_data->VirtualMethods() != nullptr) {
548 fprintf(out_file_, "virtual_methods_size: %zu\n", class_data->VirtualMethods()->size());
549 } else {
David Sehr7629f602016-08-07 16:01:51 -0700550 fprintf(out_file_, "virtual_methods_size: 0\n");
551 }
552 fprintf(out_file_, "\n");
553}
554
555/**
556 * Dumps an annotation set item.
557 */
558static void DumpAnnotationSetItem(dex_ir::AnnotationSetItem* set_item) {
David Sehr853a8e12016-09-01 13:03:50 -0700559 if (set_item == nullptr || set_item->GetItems()->size() == 0) {
David Sehr7629f602016-08-07 16:01:51 -0700560 fputs(" empty-annotation-set\n", out_file_);
561 return;
562 }
Jeff Hao3ab96b42016-09-09 18:35:01 -0700563 for (dex_ir::AnnotationItem* annotation : *set_item->GetItems()) {
David Sehr7629f602016-08-07 16:01:51 -0700564 if (annotation == nullptr) {
565 continue;
566 }
567 fputs(" ", out_file_);
568 switch (annotation->GetVisibility()) {
569 case DexFile::kDexVisibilityBuild: fputs("VISIBILITY_BUILD ", out_file_); break;
570 case DexFile::kDexVisibilityRuntime: fputs("VISIBILITY_RUNTIME ", out_file_); break;
571 case DexFile::kDexVisibilitySystem: fputs("VISIBILITY_SYSTEM ", out_file_); break;
572 default: fputs("VISIBILITY_UNKNOWN ", out_file_); break;
573 } // switch
Jeff Hao3ab96b42016-09-09 18:35:01 -0700574 DumpEncodedAnnotation(annotation->GetAnnotation());
David Sehr7629f602016-08-07 16:01:51 -0700575 fputc('\n', out_file_);
576 }
577}
578
579/*
580 * Dumps class annotations.
581 */
582static void DumpClassAnnotations(dex_ir::Header* header, int idx) {
Jeff Hao3ab96b42016-09-09 18:35:01 -0700583 dex_ir::ClassDef* class_def = header->GetCollections().GetClassDef(idx);
David Sehr7629f602016-08-07 16:01:51 -0700584 dex_ir::AnnotationsDirectoryItem* annotations_directory = class_def->Annotations();
585 if (annotations_directory == nullptr) {
586 return; // none
587 }
588
589 fprintf(out_file_, "Class #%d annotations:\n", idx);
590
591 dex_ir::AnnotationSetItem* class_set_item = annotations_directory->GetClassAnnotation();
David Sehr853a8e12016-09-01 13:03:50 -0700592 dex_ir::FieldAnnotationVector* fields = annotations_directory->GetFieldAnnotations();
593 dex_ir::MethodAnnotationVector* methods = annotations_directory->GetMethodAnnotations();
594 dex_ir::ParameterAnnotationVector* parameters = annotations_directory->GetParameterAnnotations();
David Sehr7629f602016-08-07 16:01:51 -0700595
596 // Annotations on the class itself.
597 if (class_set_item != nullptr) {
598 fprintf(out_file_, "Annotations on class\n");
599 DumpAnnotationSetItem(class_set_item);
600 }
601
602 // Annotations on fields.
David Sehr853a8e12016-09-01 13:03:50 -0700603 if (fields != nullptr) {
604 for (auto& field : *fields) {
605 const dex_ir::FieldId* field_id = field->GetFieldId();
Jeff Hao3ab96b42016-09-09 18:35:01 -0700606 const uint32_t field_idx = field_id->GetIndex();
David Sehr853a8e12016-09-01 13:03:50 -0700607 const char* field_name = field_id->Name()->Data();
608 fprintf(out_file_, "Annotations on field #%u '%s'\n", field_idx, field_name);
609 DumpAnnotationSetItem(field->GetAnnotationSetItem());
610 }
David Sehr7629f602016-08-07 16:01:51 -0700611 }
612
613 // Annotations on methods.
David Sehr853a8e12016-09-01 13:03:50 -0700614 if (methods != nullptr) {
615 for (auto& method : *methods) {
616 const dex_ir::MethodId* method_id = method->GetMethodId();
Jeff Hao3ab96b42016-09-09 18:35:01 -0700617 const uint32_t method_idx = method_id->GetIndex();
David Sehr853a8e12016-09-01 13:03:50 -0700618 const char* method_name = method_id->Name()->Data();
619 fprintf(out_file_, "Annotations on method #%u '%s'\n", method_idx, method_name);
620 DumpAnnotationSetItem(method->GetAnnotationSetItem());
621 }
David Sehr7629f602016-08-07 16:01:51 -0700622 }
623
624 // Annotations on method parameters.
David Sehr853a8e12016-09-01 13:03:50 -0700625 if (parameters != nullptr) {
626 for (auto& parameter : *parameters) {
627 const dex_ir::MethodId* method_id = parameter->GetMethodId();
Jeff Hao3ab96b42016-09-09 18:35:01 -0700628 const uint32_t method_idx = method_id->GetIndex();
David Sehr853a8e12016-09-01 13:03:50 -0700629 const char* method_name = method_id->Name()->Data();
630 fprintf(out_file_, "Annotations on method #%u '%s' parameters\n", method_idx, method_name);
631 uint32_t j = 0;
Jeff Hao3ab96b42016-09-09 18:35:01 -0700632 for (dex_ir::AnnotationSetItem* annotation : *parameter->GetAnnotations()->GetItems()) {
David Sehr853a8e12016-09-01 13:03:50 -0700633 fprintf(out_file_, "#%u\n", j);
Jeff Hao3ab96b42016-09-09 18:35:01 -0700634 DumpAnnotationSetItem(annotation);
David Sehr853a8e12016-09-01 13:03:50 -0700635 ++j;
636 }
David Sehr7629f602016-08-07 16:01:51 -0700637 }
638 }
639
640 fputc('\n', out_file_);
641}
642
643/*
644 * Dumps an interface that a class declares to implement.
645 */
David Sehr853a8e12016-09-01 13:03:50 -0700646static void DumpInterface(const dex_ir::TypeId* type_item, int i) {
David Sehr7629f602016-08-07 16:01:51 -0700647 const char* interface_name = type_item->GetStringId()->Data();
648 if (options_.output_format_ == kOutputPlain) {
649 fprintf(out_file_, " #%d : '%s'\n", i, interface_name);
650 } else {
Jeff Haoc3acfc52016-08-29 14:18:26 -0700651 std::string dot(DescriptorToDotWrapper(interface_name));
David Sehr7629f602016-08-07 16:01:51 -0700652 fprintf(out_file_, "<implements name=\"%s\">\n</implements>\n", dot.c_str());
653 }
654}
655
656/*
657 * Dumps the catches table associated with the code.
658 */
659static void DumpCatches(const dex_ir::CodeItem* code) {
660 const uint16_t tries_size = code->TriesSize();
661
662 // No catch table.
663 if (tries_size == 0) {
664 fprintf(out_file_, " catches : (none)\n");
665 return;
666 }
667
668 // Dump all table entries.
669 fprintf(out_file_, " catches : %d\n", tries_size);
670 std::vector<std::unique_ptr<const dex_ir::TryItem>>* tries = code->Tries();
671 for (uint32_t i = 0; i < tries_size; i++) {
672 const dex_ir::TryItem* try_item = (*tries)[i].get();
673 const uint32_t start = try_item->StartAddr();
674 const uint32_t end = start + try_item->InsnCount();
675 fprintf(out_file_, " 0x%04x - 0x%04x\n", start, end);
Nicolas Geoffrayfd1a6c22016-10-04 11:01:17 +0000676 for (auto& handler : try_item->GetHandlers()) {
David Sehr7629f602016-08-07 16:01:51 -0700677 const dex_ir::TypeId* type_id = handler->GetTypeId();
678 const char* descriptor = (type_id == nullptr) ? "<any>" : type_id->GetStringId()->Data();
679 fprintf(out_file_, " %s -> 0x%04x\n", descriptor, handler->GetAddress());
680 } // for
681 } // for
682}
683
684/*
685 * Dumps all positions table entries associated with the code.
686 */
687static void DumpPositionInfo(const dex_ir::CodeItem* code) {
688 dex_ir::DebugInfoItem* debug_info = code->DebugInfo();
689 if (debug_info == nullptr) {
690 return;
691 }
692 std::vector<std::unique_ptr<dex_ir::PositionInfo>>& positions = debug_info->GetPositionInfo();
693 for (size_t i = 0; i < positions.size(); ++i) {
694 fprintf(out_file_, " 0x%04x line=%d\n", positions[i]->address_, positions[i]->line_);
695 }
696}
697
698/*
699 * Dumps all locals table entries associated with the code.
700 */
701static void DumpLocalInfo(const dex_ir::CodeItem* code) {
702 dex_ir::DebugInfoItem* debug_info = code->DebugInfo();
703 if (debug_info == nullptr) {
704 return;
705 }
706 std::vector<std::unique_ptr<dex_ir::LocalInfo>>& locals = debug_info->GetLocalInfo();
707 for (size_t i = 0; i < locals.size(); ++i) {
708 dex_ir::LocalInfo* entry = locals[i].get();
709 fprintf(out_file_, " 0x%04x - 0x%04x reg=%d %s %s %s\n",
710 entry->start_address_, entry->end_address_, entry->reg_,
711 entry->name_.c_str(), entry->descriptor_.c_str(), entry->signature_.c_str());
712 }
713}
714
715/*
716 * Helper for dumpInstruction(), which builds the string
717 * representation for the index in the given instruction.
718 * Returns a pointer to a buffer of sufficient size.
719 */
720static std::unique_ptr<char[]> IndexString(dex_ir::Header* header,
721 const Instruction* dec_insn,
722 size_t buf_size) {
723 std::unique_ptr<char[]> buf(new char[buf_size]);
724 // Determine index and width of the string.
725 uint32_t index = 0;
726 uint32_t width = 4;
727 switch (Instruction::FormatOf(dec_insn->Opcode())) {
728 // SOME NOT SUPPORTED:
729 // case Instruction::k20bc:
730 case Instruction::k21c:
731 case Instruction::k35c:
732 // case Instruction::k35ms:
733 case Instruction::k3rc:
734 // case Instruction::k3rms:
735 // case Instruction::k35mi:
736 // case Instruction::k3rmi:
737 index = dec_insn->VRegB();
738 width = 4;
739 break;
740 case Instruction::k31c:
741 index = dec_insn->VRegB();
742 width = 8;
743 break;
744 case Instruction::k22c:
745 // case Instruction::k22cs:
746 index = dec_insn->VRegC();
747 width = 4;
748 break;
749 default:
750 break;
751 } // switch
752
753 // Determine index type.
754 size_t outSize = 0;
755 switch (Instruction::IndexTypeOf(dec_insn->Opcode())) {
756 case Instruction::kIndexUnknown:
757 // This function should never get called for this type, but do
758 // something sensible here, just to help with debugging.
759 outSize = snprintf(buf.get(), buf_size, "<unknown-index>");
760 break;
761 case Instruction::kIndexNone:
762 // This function should never get called for this type, but do
763 // something sensible here, just to help with debugging.
764 outSize = snprintf(buf.get(), buf_size, "<no-index>");
765 break;
766 case Instruction::kIndexTypeRef:
Jeff Hao3ab96b42016-09-09 18:35:01 -0700767 if (index < header->GetCollections().TypeIdsSize()) {
768 const char* tp = header->GetCollections().GetTypeId(index)->GetStringId()->Data();
David Sehr7629f602016-08-07 16:01:51 -0700769 outSize = snprintf(buf.get(), buf_size, "%s // type@%0*x", tp, width, index);
770 } else {
771 outSize = snprintf(buf.get(), buf_size, "<type?> // type@%0*x", width, index);
772 }
773 break;
774 case Instruction::kIndexStringRef:
Jeff Hao3ab96b42016-09-09 18:35:01 -0700775 if (index < header->GetCollections().StringIdsSize()) {
776 const char* st = header->GetCollections().GetStringId(index)->Data();
David Sehr7629f602016-08-07 16:01:51 -0700777 outSize = snprintf(buf.get(), buf_size, "\"%s\" // string@%0*x", st, width, index);
778 } else {
779 outSize = snprintf(buf.get(), buf_size, "<string?> // string@%0*x", width, index);
780 }
781 break;
782 case Instruction::kIndexMethodRef:
Jeff Hao3ab96b42016-09-09 18:35:01 -0700783 if (index < header->GetCollections().MethodIdsSize()) {
784 dex_ir::MethodId* method_id = header->GetCollections().GetMethodId(index);
David Sehr7629f602016-08-07 16:01:51 -0700785 const char* name = method_id->Name()->Data();
David Sehr72359222016-09-07 13:04:01 -0700786 std::string type_descriptor = GetSignatureForProtoId(method_id->Proto());
David Sehr7629f602016-08-07 16:01:51 -0700787 const char* back_descriptor = method_id->Class()->GetStringId()->Data();
788 outSize = snprintf(buf.get(), buf_size, "%s.%s:%s // method@%0*x",
David Sehr72359222016-09-07 13:04:01 -0700789 back_descriptor, name, type_descriptor.c_str(), width, index);
David Sehr7629f602016-08-07 16:01:51 -0700790 } else {
791 outSize = snprintf(buf.get(), buf_size, "<method?> // method@%0*x", width, index);
792 }
793 break;
794 case Instruction::kIndexFieldRef:
Jeff Hao3ab96b42016-09-09 18:35:01 -0700795 if (index < header->GetCollections().FieldIdsSize()) {
796 dex_ir::FieldId* field_id = header->GetCollections().GetFieldId(index);
David Sehr7629f602016-08-07 16:01:51 -0700797 const char* name = field_id->Name()->Data();
798 const char* type_descriptor = field_id->Type()->GetStringId()->Data();
799 const char* back_descriptor = field_id->Class()->GetStringId()->Data();
800 outSize = snprintf(buf.get(), buf_size, "%s.%s:%s // field@%0*x",
801 back_descriptor, name, type_descriptor, width, index);
802 } else {
803 outSize = snprintf(buf.get(), buf_size, "<field?> // field@%0*x", width, index);
804 }
805 break;
806 case Instruction::kIndexVtableOffset:
807 outSize = snprintf(buf.get(), buf_size, "[%0*x] // vtable #%0*x",
808 width, index, width, index);
809 break;
810 case Instruction::kIndexFieldOffset:
811 outSize = snprintf(buf.get(), buf_size, "[obj+%0*x]", width, index);
812 break;
813 // SOME NOT SUPPORTED:
814 // case Instruction::kIndexVaries:
815 // case Instruction::kIndexInlineMethod:
816 default:
817 outSize = snprintf(buf.get(), buf_size, "<?>");
818 break;
819 } // switch
820
821 // Determine success of string construction.
822 if (outSize >= buf_size) {
823 // The buffer wasn't big enough; retry with computed size. Note: snprintf()
824 // doesn't count/ the '\0' as part of its returned size, so we add explicit
825 // space for it here.
826 return IndexString(header, dec_insn, outSize + 1);
827 }
828 return buf;
829}
830
831/*
832 * Dumps a single instruction.
833 */
834static void DumpInstruction(dex_ir::Header* header, const dex_ir::CodeItem* code,
835 uint32_t code_offset, uint32_t insn_idx, uint32_t insn_width,
836 const Instruction* dec_insn) {
837 // Address of instruction (expressed as byte offset).
838 fprintf(out_file_, "%06x:", code_offset + 0x10 + insn_idx * 2);
839
840 // Dump (part of) raw bytes.
841 const uint16_t* insns = code->Insns();
842 for (uint32_t i = 0; i < 8; i++) {
843 if (i < insn_width) {
844 if (i == 7) {
845 fprintf(out_file_, " ... ");
846 } else {
847 // Print 16-bit value in little-endian order.
848 const uint8_t* bytePtr = (const uint8_t*) &insns[insn_idx + i];
849 fprintf(out_file_, " %02x%02x", bytePtr[0], bytePtr[1]);
850 }
851 } else {
852 fputs(" ", out_file_);
853 }
854 } // for
855
856 // Dump pseudo-instruction or opcode.
857 if (dec_insn->Opcode() == Instruction::NOP) {
858 const uint16_t instr = Get2LE((const uint8_t*) &insns[insn_idx]);
859 if (instr == Instruction::kPackedSwitchSignature) {
860 fprintf(out_file_, "|%04x: packed-switch-data (%d units)", insn_idx, insn_width);
861 } else if (instr == Instruction::kSparseSwitchSignature) {
862 fprintf(out_file_, "|%04x: sparse-switch-data (%d units)", insn_idx, insn_width);
863 } else if (instr == Instruction::kArrayDataSignature) {
864 fprintf(out_file_, "|%04x: array-data (%d units)", insn_idx, insn_width);
865 } else {
866 fprintf(out_file_, "|%04x: nop // spacer", insn_idx);
867 }
868 } else {
869 fprintf(out_file_, "|%04x: %s", insn_idx, dec_insn->Name());
870 }
871
872 // Set up additional argument.
873 std::unique_ptr<char[]> index_buf;
874 if (Instruction::IndexTypeOf(dec_insn->Opcode()) != Instruction::kIndexNone) {
875 index_buf = IndexString(header, dec_insn, 200);
876 }
877
878 // Dump the instruction.
879 //
880 // NOTE: pDecInsn->DumpString(pDexFile) differs too much from original.
881 //
882 switch (Instruction::FormatOf(dec_insn->Opcode())) {
883 case Instruction::k10x: // op
884 break;
885 case Instruction::k12x: // op vA, vB
886 fprintf(out_file_, " v%d, v%d", dec_insn->VRegA(), dec_insn->VRegB());
887 break;
888 case Instruction::k11n: // op vA, #+B
889 fprintf(out_file_, " v%d, #int %d // #%x",
890 dec_insn->VRegA(), (int32_t) dec_insn->VRegB(), (uint8_t)dec_insn->VRegB());
891 break;
892 case Instruction::k11x: // op vAA
893 fprintf(out_file_, " v%d", dec_insn->VRegA());
894 break;
895 case Instruction::k10t: // op +AA
896 case Instruction::k20t: { // op +AAAA
897 const int32_t targ = (int32_t) dec_insn->VRegA();
898 fprintf(out_file_, " %04x // %c%04x",
899 insn_idx + targ,
900 (targ < 0) ? '-' : '+',
901 (targ < 0) ? -targ : targ);
902 break;
903 }
904 case Instruction::k22x: // op vAA, vBBBB
905 fprintf(out_file_, " v%d, v%d", dec_insn->VRegA(), dec_insn->VRegB());
906 break;
907 case Instruction::k21t: { // op vAA, +BBBB
908 const int32_t targ = (int32_t) dec_insn->VRegB();
909 fprintf(out_file_, " v%d, %04x // %c%04x", dec_insn->VRegA(),
910 insn_idx + targ,
911 (targ < 0) ? '-' : '+',
912 (targ < 0) ? -targ : targ);
913 break;
914 }
915 case Instruction::k21s: // op vAA, #+BBBB
916 fprintf(out_file_, " v%d, #int %d // #%x",
917 dec_insn->VRegA(), (int32_t) dec_insn->VRegB(), (uint16_t)dec_insn->VRegB());
918 break;
919 case Instruction::k21h: // op vAA, #+BBBB0000[00000000]
920 // The printed format varies a bit based on the actual opcode.
921 if (dec_insn->Opcode() == Instruction::CONST_HIGH16) {
922 const int32_t value = dec_insn->VRegB() << 16;
923 fprintf(out_file_, " v%d, #int %d // #%x",
924 dec_insn->VRegA(), value, (uint16_t) dec_insn->VRegB());
925 } else {
926 const int64_t value = ((int64_t) dec_insn->VRegB()) << 48;
927 fprintf(out_file_, " v%d, #long %" PRId64 " // #%x",
928 dec_insn->VRegA(), value, (uint16_t) dec_insn->VRegB());
929 }
930 break;
931 case Instruction::k21c: // op vAA, thing@BBBB
932 case Instruction::k31c: // op vAA, thing@BBBBBBBB
933 fprintf(out_file_, " v%d, %s", dec_insn->VRegA(), index_buf.get());
934 break;
935 case Instruction::k23x: // op vAA, vBB, vCC
936 fprintf(out_file_, " v%d, v%d, v%d",
937 dec_insn->VRegA(), dec_insn->VRegB(), dec_insn->VRegC());
938 break;
939 case Instruction::k22b: // op vAA, vBB, #+CC
940 fprintf(out_file_, " v%d, v%d, #int %d // #%02x",
941 dec_insn->VRegA(), dec_insn->VRegB(),
942 (int32_t) dec_insn->VRegC(), (uint8_t) dec_insn->VRegC());
943 break;
944 case Instruction::k22t: { // op vA, vB, +CCCC
945 const int32_t targ = (int32_t) dec_insn->VRegC();
946 fprintf(out_file_, " v%d, v%d, %04x // %c%04x",
947 dec_insn->VRegA(), dec_insn->VRegB(),
948 insn_idx + targ,
949 (targ < 0) ? '-' : '+',
950 (targ < 0) ? -targ : targ);
951 break;
952 }
953 case Instruction::k22s: // op vA, vB, #+CCCC
954 fprintf(out_file_, " v%d, v%d, #int %d // #%04x",
955 dec_insn->VRegA(), dec_insn->VRegB(),
956 (int32_t) dec_insn->VRegC(), (uint16_t) dec_insn->VRegC());
957 break;
958 case Instruction::k22c: // op vA, vB, thing@CCCC
959 // NOT SUPPORTED:
960 // case Instruction::k22cs: // [opt] op vA, vB, field offset CCCC
961 fprintf(out_file_, " v%d, v%d, %s",
962 dec_insn->VRegA(), dec_insn->VRegB(), index_buf.get());
963 break;
964 case Instruction::k30t:
965 fprintf(out_file_, " #%08x", dec_insn->VRegA());
966 break;
967 case Instruction::k31i: { // op vAA, #+BBBBBBBB
968 // This is often, but not always, a float.
969 union {
970 float f;
971 uint32_t i;
972 } conv;
973 conv.i = dec_insn->VRegB();
974 fprintf(out_file_, " v%d, #float %g // #%08x",
975 dec_insn->VRegA(), conv.f, dec_insn->VRegB());
976 break;
977 }
978 case Instruction::k31t: // op vAA, offset +BBBBBBBB
979 fprintf(out_file_, " v%d, %08x // +%08x",
980 dec_insn->VRegA(), insn_idx + dec_insn->VRegB(), dec_insn->VRegB());
981 break;
982 case Instruction::k32x: // op vAAAA, vBBBB
983 fprintf(out_file_, " v%d, v%d", dec_insn->VRegA(), dec_insn->VRegB());
984 break;
985 case Instruction::k35c: { // op {vC, vD, vE, vF, vG}, thing@BBBB
986 // NOT SUPPORTED:
987 // case Instruction::k35ms: // [opt] invoke-virtual+super
988 // case Instruction::k35mi: // [opt] inline invoke
989 uint32_t arg[Instruction::kMaxVarArgRegs];
990 dec_insn->GetVarArgs(arg);
991 fputs(" {", out_file_);
992 for (int i = 0, n = dec_insn->VRegA(); i < n; i++) {
993 if (i == 0) {
994 fprintf(out_file_, "v%d", arg[i]);
995 } else {
996 fprintf(out_file_, ", v%d", arg[i]);
997 }
998 } // for
999 fprintf(out_file_, "}, %s", index_buf.get());
1000 break;
1001 }
1002 case Instruction::k3rc: // op {vCCCC .. v(CCCC+AA-1)}, thing@BBBB
1003 // NOT SUPPORTED:
1004 // case Instruction::k3rms: // [opt] invoke-virtual+super/range
1005 // case Instruction::k3rmi: // [opt] execute-inline/range
1006 {
1007 // This doesn't match the "dx" output when some of the args are
1008 // 64-bit values -- dx only shows the first register.
1009 fputs(" {", out_file_);
1010 for (int i = 0, n = dec_insn->VRegA(); i < n; i++) {
1011 if (i == 0) {
1012 fprintf(out_file_, "v%d", dec_insn->VRegC() + i);
1013 } else {
1014 fprintf(out_file_, ", v%d", dec_insn->VRegC() + i);
1015 }
1016 } // for
1017 fprintf(out_file_, "}, %s", index_buf.get());
1018 }
1019 break;
1020 case Instruction::k51l: { // op vAA, #+BBBBBBBBBBBBBBBB
1021 // This is often, but not always, a double.
1022 union {
1023 double d;
1024 uint64_t j;
1025 } conv;
1026 conv.j = dec_insn->WideVRegB();
1027 fprintf(out_file_, " v%d, #double %g // #%016" PRIx64,
1028 dec_insn->VRegA(), conv.d, dec_insn->WideVRegB());
1029 break;
1030 }
1031 // NOT SUPPORTED:
1032 // case Instruction::k00x: // unknown op or breakpoint
1033 // break;
1034 default:
1035 fprintf(out_file_, " ???");
1036 break;
1037 } // switch
1038
1039 fputc('\n', out_file_);
1040}
1041
1042/*
1043 * Dumps a bytecode disassembly.
1044 */
1045static void DumpBytecodes(dex_ir::Header* header, uint32_t idx,
1046 const dex_ir::CodeItem* code, uint32_t code_offset) {
Jeff Hao3ab96b42016-09-09 18:35:01 -07001047 dex_ir::MethodId* method_id = header->GetCollections().GetMethodId(idx);
David Sehr7629f602016-08-07 16:01:51 -07001048 const char* name = method_id->Name()->Data();
David Sehr72359222016-09-07 13:04:01 -07001049 std::string type_descriptor = GetSignatureForProtoId(method_id->Proto());
David Sehr7629f602016-08-07 16:01:51 -07001050 const char* back_descriptor = method_id->Class()->GetStringId()->Data();
1051
1052 // Generate header.
Jeff Haoc3acfc52016-08-29 14:18:26 -07001053 std::string dot(DescriptorToDotWrapper(back_descriptor));
David Sehr7629f602016-08-07 16:01:51 -07001054 fprintf(out_file_, "%06x: |[%06x] %s.%s:%s\n",
David Sehr72359222016-09-07 13:04:01 -07001055 code_offset, code_offset, dot.c_str(), name, type_descriptor.c_str());
David Sehr7629f602016-08-07 16:01:51 -07001056
1057 // Iterate over all instructions.
1058 const uint16_t* insns = code->Insns();
1059 for (uint32_t insn_idx = 0; insn_idx < code->InsnsSize();) {
1060 const Instruction* instruction = Instruction::At(&insns[insn_idx]);
1061 const uint32_t insn_width = instruction->SizeInCodeUnits();
1062 if (insn_width == 0) {
1063 fprintf(stderr, "GLITCH: zero-width instruction at idx=0x%04x\n", insn_idx);
1064 break;
1065 }
1066 DumpInstruction(header, code, code_offset, insn_idx, insn_width, instruction);
1067 insn_idx += insn_width;
1068 } // for
1069}
1070
1071/*
1072 * Dumps code of a method.
1073 */
1074static void DumpCode(dex_ir::Header* header, uint32_t idx, const dex_ir::CodeItem* code,
1075 uint32_t code_offset) {
1076 fprintf(out_file_, " registers : %d\n", code->RegistersSize());
1077 fprintf(out_file_, " ins : %d\n", code->InsSize());
1078 fprintf(out_file_, " outs : %d\n", code->OutsSize());
1079 fprintf(out_file_, " insns size : %d 16-bit code units\n",
1080 code->InsnsSize());
1081
1082 // Bytecode disassembly, if requested.
1083 if (options_.disassemble_) {
1084 DumpBytecodes(header, idx, code, code_offset);
1085 }
1086
1087 // Try-catch blocks.
1088 DumpCatches(code);
1089
1090 // Positions and locals table in the debug info.
1091 fprintf(out_file_, " positions : \n");
1092 DumpPositionInfo(code);
1093 fprintf(out_file_, " locals : \n");
1094 DumpLocalInfo(code);
1095}
1096
1097/*
1098 * Dumps a method.
1099 */
1100static void DumpMethod(dex_ir::Header* header, uint32_t idx, uint32_t flags,
1101 const dex_ir::CodeItem* code, int i) {
1102 // Bail for anything private if export only requested.
1103 if (options_.exports_only_ && (flags & (kAccPublic | kAccProtected)) == 0) {
1104 return;
1105 }
1106
Jeff Hao3ab96b42016-09-09 18:35:01 -07001107 dex_ir::MethodId* method_id = header->GetCollections().GetMethodId(idx);
David Sehr7629f602016-08-07 16:01:51 -07001108 const char* name = method_id->Name()->Data();
1109 char* type_descriptor = strdup(GetSignatureForProtoId(method_id->Proto()).c_str());
1110 const char* back_descriptor = method_id->Class()->GetStringId()->Data();
1111 char* access_str = CreateAccessFlagStr(flags, kAccessForMethod);
1112
1113 if (options_.output_format_ == kOutputPlain) {
1114 fprintf(out_file_, " #%d : (in %s)\n", i, back_descriptor);
1115 fprintf(out_file_, " name : '%s'\n", name);
1116 fprintf(out_file_, " type : '%s'\n", type_descriptor);
1117 fprintf(out_file_, " access : 0x%04x (%s)\n", flags, access_str);
1118 if (code == nullptr) {
1119 fprintf(out_file_, " code : (none)\n");
1120 } else {
1121 fprintf(out_file_, " code -\n");
1122 DumpCode(header, idx, code, code->GetOffset());
1123 }
1124 if (options_.disassemble_) {
1125 fputc('\n', out_file_);
1126 }
1127 } else if (options_.output_format_ == kOutputXml) {
1128 const bool constructor = (name[0] == '<');
1129
1130 // Method name and prototype.
1131 if (constructor) {
1132 std::string dot(DescriptorClassToDot(back_descriptor));
1133 fprintf(out_file_, "<constructor name=\"%s\"\n", dot.c_str());
Jeff Haoc3acfc52016-08-29 14:18:26 -07001134 dot = DescriptorToDotWrapper(back_descriptor);
David Sehr7629f602016-08-07 16:01:51 -07001135 fprintf(out_file_, " type=\"%s\"\n", dot.c_str());
1136 } else {
1137 fprintf(out_file_, "<method name=\"%s\"\n", name);
1138 const char* return_type = strrchr(type_descriptor, ')');
1139 if (return_type == nullptr) {
1140 fprintf(stderr, "bad method type descriptor '%s'\n", type_descriptor);
1141 goto bail;
1142 }
Jeff Haoc3acfc52016-08-29 14:18:26 -07001143 std::string dot(DescriptorToDotWrapper(return_type + 1));
David Sehr7629f602016-08-07 16:01:51 -07001144 fprintf(out_file_, " return=\"%s\"\n", dot.c_str());
1145 fprintf(out_file_, " abstract=%s\n", QuotedBool((flags & kAccAbstract) != 0));
1146 fprintf(out_file_, " native=%s\n", QuotedBool((flags & kAccNative) != 0));
1147 fprintf(out_file_, " synchronized=%s\n", QuotedBool(
1148 (flags & (kAccSynchronized | kAccDeclaredSynchronized)) != 0));
1149 }
1150
1151 // Additional method flags.
1152 fprintf(out_file_, " static=%s\n", QuotedBool((flags & kAccStatic) != 0));
1153 fprintf(out_file_, " final=%s\n", QuotedBool((flags & kAccFinal) != 0));
1154 // The "deprecated=" not knowable w/o parsing annotations.
1155 fprintf(out_file_, " visibility=%s\n>\n", QuotedVisibility(flags));
1156
1157 // Parameters.
1158 if (type_descriptor[0] != '(') {
1159 fprintf(stderr, "ERROR: bad descriptor '%s'\n", type_descriptor);
1160 goto bail;
1161 }
1162 char* tmp_buf = reinterpret_cast<char*>(malloc(strlen(type_descriptor) + 1));
1163 const char* base = type_descriptor + 1;
1164 int arg_num = 0;
1165 while (*base != ')') {
1166 char* cp = tmp_buf;
1167 while (*base == '[') {
1168 *cp++ = *base++;
1169 }
1170 if (*base == 'L') {
1171 // Copy through ';'.
1172 do {
1173 *cp = *base++;
1174 } while (*cp++ != ';');
1175 } else {
1176 // Primitive char, copy it.
1177 if (strchr("ZBCSIFJD", *base) == nullptr) {
1178 fprintf(stderr, "ERROR: bad method signature '%s'\n", base);
1179 break; // while
1180 }
1181 *cp++ = *base++;
1182 }
1183 // Null terminate and display.
1184 *cp++ = '\0';
Jeff Haoc3acfc52016-08-29 14:18:26 -07001185 std::string dot(DescriptorToDotWrapper(tmp_buf));
David Sehr7629f602016-08-07 16:01:51 -07001186 fprintf(out_file_, "<parameter name=\"arg%d\" type=\"%s\">\n"
1187 "</parameter>\n", arg_num++, dot.c_str());
1188 } // while
1189 free(tmp_buf);
1190 if (constructor) {
1191 fprintf(out_file_, "</constructor>\n");
1192 } else {
1193 fprintf(out_file_, "</method>\n");
1194 }
1195 }
1196
1197 bail:
1198 free(type_descriptor);
1199 free(access_str);
1200}
1201
1202/*
1203 * Dumps a static (class) field.
1204 */
1205static void DumpSField(dex_ir::Header* header, uint32_t idx, uint32_t flags,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001206 int i, dex_ir::EncodedValue* init) {
David Sehr7629f602016-08-07 16:01:51 -07001207 // Bail for anything private if export only requested.
1208 if (options_.exports_only_ && (flags & (kAccPublic | kAccProtected)) == 0) {
1209 return;
1210 }
1211
Jeff Hao3ab96b42016-09-09 18:35:01 -07001212 dex_ir::FieldId* field_id = header->GetCollections().GetFieldId(idx);
David Sehr7629f602016-08-07 16:01:51 -07001213 const char* name = field_id->Name()->Data();
1214 const char* type_descriptor = field_id->Type()->GetStringId()->Data();
1215 const char* back_descriptor = field_id->Class()->GetStringId()->Data();
1216 char* access_str = CreateAccessFlagStr(flags, kAccessForField);
1217
1218 if (options_.output_format_ == kOutputPlain) {
1219 fprintf(out_file_, " #%d : (in %s)\n", i, back_descriptor);
1220 fprintf(out_file_, " name : '%s'\n", name);
1221 fprintf(out_file_, " type : '%s'\n", type_descriptor);
1222 fprintf(out_file_, " access : 0x%04x (%s)\n", flags, access_str);
1223 if (init != nullptr) {
1224 fputs(" value : ", out_file_);
1225 DumpEncodedValue(init);
1226 fputs("\n", out_file_);
1227 }
1228 } else if (options_.output_format_ == kOutputXml) {
1229 fprintf(out_file_, "<field name=\"%s\"\n", name);
Jeff Haoc3acfc52016-08-29 14:18:26 -07001230 std::string dot(DescriptorToDotWrapper(type_descriptor));
David Sehr7629f602016-08-07 16:01:51 -07001231 fprintf(out_file_, " type=\"%s\"\n", dot.c_str());
1232 fprintf(out_file_, " transient=%s\n", QuotedBool((flags & kAccTransient) != 0));
1233 fprintf(out_file_, " volatile=%s\n", QuotedBool((flags & kAccVolatile) != 0));
1234 // The "value=" is not knowable w/o parsing annotations.
1235 fprintf(out_file_, " static=%s\n", QuotedBool((flags & kAccStatic) != 0));
1236 fprintf(out_file_, " final=%s\n", QuotedBool((flags & kAccFinal) != 0));
1237 // The "deprecated=" is not knowable w/o parsing annotations.
1238 fprintf(out_file_, " visibility=%s\n", QuotedVisibility(flags));
1239 if (init != nullptr) {
1240 fputs(" value=\"", out_file_);
1241 DumpEncodedValue(init);
1242 fputs("\"\n", out_file_);
1243 }
1244 fputs(">\n</field>\n", out_file_);
1245 }
1246
1247 free(access_str);
1248}
1249
1250/*
1251 * Dumps an instance field.
1252 */
1253static void DumpIField(dex_ir::Header* header, uint32_t idx, uint32_t flags, int i) {
1254 DumpSField(header, idx, flags, i, nullptr);
1255}
1256
1257/*
1258 * Dumping a CFG. Note that this will do duplicate work. utils.h doesn't expose the code-item
1259 * version, so the DumpMethodCFG code will have to iterate again to find it. But dexdump is a
1260 * tool, so this is not performance-critical.
1261 */
1262
1263static void DumpCFG(const DexFile* dex_file,
1264 uint32_t dex_method_idx,
1265 const DexFile::CodeItem* code) {
1266 if (code != nullptr) {
1267 std::ostringstream oss;
1268 DumpMethodCFG(dex_file, dex_method_idx, oss);
1269 fprintf(out_file_, "%s", oss.str().c_str());
1270 }
1271}
1272
1273static void DumpCFG(const DexFile* dex_file, int idx) {
1274 const DexFile::ClassDef& class_def = dex_file->GetClassDef(idx);
1275 const uint8_t* class_data = dex_file->GetClassData(class_def);
1276 if (class_data == nullptr) { // empty class such as a marker interface?
1277 return;
1278 }
1279 ClassDataItemIterator it(*dex_file, class_data);
1280 while (it.HasNextStaticField()) {
1281 it.Next();
1282 }
1283 while (it.HasNextInstanceField()) {
1284 it.Next();
1285 }
1286 while (it.HasNextDirectMethod()) {
1287 DumpCFG(dex_file,
1288 it.GetMemberIndex(),
1289 it.GetMethodCodeItem());
1290 it.Next();
1291 }
1292 while (it.HasNextVirtualMethod()) {
1293 DumpCFG(dex_file,
David Sehr853a8e12016-09-01 13:03:50 -07001294 it.GetMemberIndex(),
1295 it.GetMethodCodeItem());
David Sehr7629f602016-08-07 16:01:51 -07001296 it.Next();
1297 }
1298}
1299
1300/*
1301 * Dumps the class.
1302 *
1303 * Note "idx" is a DexClassDef index, not a DexTypeId index.
1304 *
1305 * If "*last_package" is nullptr or does not match the current class' package,
1306 * the value will be replaced with a newly-allocated string.
1307 */
David Sehr853a8e12016-09-01 13:03:50 -07001308static void DumpClass(const DexFile* dex_file,
1309 dex_ir::Header* header,
1310 int idx,
1311 char** last_package) {
Jeff Hao3ab96b42016-09-09 18:35:01 -07001312 dex_ir::ClassDef* class_def = header->GetCollections().GetClassDef(idx);
David Sehr7629f602016-08-07 16:01:51 -07001313 // Omitting non-public class.
1314 if (options_.exports_only_ && (class_def->GetAccessFlags() & kAccPublic) == 0) {
1315 return;
1316 }
1317
1318 if (options_.show_section_headers_) {
1319 DumpClassDef(header, idx);
1320 }
1321
1322 if (options_.show_annotations_) {
1323 DumpClassAnnotations(header, idx);
1324 }
1325
1326 if (options_.show_cfg_) {
David Sehr853a8e12016-09-01 13:03:50 -07001327 DumpCFG(dex_file, idx);
David Sehr7629f602016-08-07 16:01:51 -07001328 return;
1329 }
1330
1331 // For the XML output, show the package name. Ideally we'd gather
1332 // up the classes, sort them, and dump them alphabetically so the
1333 // package name wouldn't jump around, but that's not a great plan
1334 // for something that needs to run on the device.
Jeff Hao3ab96b42016-09-09 18:35:01 -07001335 const char* class_descriptor =
1336 header->GetCollections().GetClassDef(idx)->ClassType()->GetStringId()->Data();
David Sehr7629f602016-08-07 16:01:51 -07001337 if (!(class_descriptor[0] == 'L' &&
1338 class_descriptor[strlen(class_descriptor)-1] == ';')) {
1339 // Arrays and primitives should not be defined explicitly. Keep going?
1340 fprintf(stderr, "Malformed class name '%s'\n", class_descriptor);
1341 } else if (options_.output_format_ == kOutputXml) {
1342 char* mangle = strdup(class_descriptor + 1);
1343 mangle[strlen(mangle)-1] = '\0';
1344
1345 // Reduce to just the package name.
1346 char* last_slash = strrchr(mangle, '/');
1347 if (last_slash != nullptr) {
1348 *last_slash = '\0';
1349 } else {
1350 *mangle = '\0';
1351 }
1352
1353 for (char* cp = mangle; *cp != '\0'; cp++) {
1354 if (*cp == '/') {
1355 *cp = '.';
1356 }
1357 } // for
1358
1359 if (*last_package == nullptr || strcmp(mangle, *last_package) != 0) {
1360 // Start of a new package.
1361 if (*last_package != nullptr) {
1362 fprintf(out_file_, "</package>\n");
1363 }
1364 fprintf(out_file_, "<package name=\"%s\"\n>\n", mangle);
1365 free(*last_package);
1366 *last_package = mangle;
1367 } else {
1368 free(mangle);
1369 }
1370 }
1371
1372 // General class information.
1373 char* access_str = CreateAccessFlagStr(class_def->GetAccessFlags(), kAccessForClass);
1374 const char* superclass_descriptor = nullptr;
1375 if (class_def->Superclass() != nullptr) {
1376 superclass_descriptor = class_def->Superclass()->GetStringId()->Data();
1377 }
1378 if (options_.output_format_ == kOutputPlain) {
1379 fprintf(out_file_, "Class #%d -\n", idx);
1380 fprintf(out_file_, " Class descriptor : '%s'\n", class_descriptor);
1381 fprintf(out_file_, " Access flags : 0x%04x (%s)\n",
1382 class_def->GetAccessFlags(), access_str);
1383 if (superclass_descriptor != nullptr) {
1384 fprintf(out_file_, " Superclass : '%s'\n", superclass_descriptor);
1385 }
1386 fprintf(out_file_, " Interfaces -\n");
1387 } else {
1388 std::string dot(DescriptorClassToDot(class_descriptor));
1389 fprintf(out_file_, "<class name=\"%s\"\n", dot.c_str());
1390 if (superclass_descriptor != nullptr) {
Jeff Haoc3acfc52016-08-29 14:18:26 -07001391 dot = DescriptorToDotWrapper(superclass_descriptor);
David Sehr7629f602016-08-07 16:01:51 -07001392 fprintf(out_file_, " extends=\"%s\"\n", dot.c_str());
1393 }
1394 fprintf(out_file_, " interface=%s\n",
1395 QuotedBool((class_def->GetAccessFlags() & kAccInterface) != 0));
1396 fprintf(out_file_, " abstract=%s\n",
1397 QuotedBool((class_def->GetAccessFlags() & kAccAbstract) != 0));
1398 fprintf(out_file_, " static=%s\n", QuotedBool((class_def->GetAccessFlags() & kAccStatic) != 0));
1399 fprintf(out_file_, " final=%s\n", QuotedBool((class_def->GetAccessFlags() & kAccFinal) != 0));
1400 // The "deprecated=" not knowable w/o parsing annotations.
1401 fprintf(out_file_, " visibility=%s\n", QuotedVisibility(class_def->GetAccessFlags()));
1402 fprintf(out_file_, ">\n");
1403 }
1404
1405 // Interfaces.
Jeff Hao3ab96b42016-09-09 18:35:01 -07001406 const dex_ir::TypeIdVector* interfaces = class_def->Interfaces();
David Sehr853a8e12016-09-01 13:03:50 -07001407 if (interfaces != nullptr) {
1408 for (uint32_t i = 0; i < interfaces->size(); i++) {
1409 DumpInterface((*interfaces)[i], i);
1410 } // for
1411 }
David Sehr7629f602016-08-07 16:01:51 -07001412
1413 // Fields and methods.
1414 dex_ir::ClassData* class_data = class_def->GetClassData();
1415 // Prepare data for static fields.
Jeff Hao3ab96b42016-09-09 18:35:01 -07001416 dex_ir::EncodedArrayItem* static_values = class_def->StaticValues();
1417 dex_ir::EncodedValueVector* encoded_values =
1418 static_values == nullptr ? nullptr : static_values->GetEncodedValues();
1419 const uint32_t encoded_values_size = (encoded_values == nullptr) ? 0 : encoded_values->size();
David Sehr7629f602016-08-07 16:01:51 -07001420
1421 // Static fields.
1422 if (options_.output_format_ == kOutputPlain) {
1423 fprintf(out_file_, " Static fields -\n");
1424 }
David Sehr853a8e12016-09-01 13:03:50 -07001425 if (class_data != nullptr) {
1426 dex_ir::FieldItemVector* static_fields = class_data->StaticFields();
1427 if (static_fields != nullptr) {
1428 for (uint32_t i = 0; i < static_fields->size(); i++) {
1429 DumpSField(header,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001430 (*static_fields)[i]->GetFieldId()->GetIndex(),
David Sehr853a8e12016-09-01 13:03:50 -07001431 (*static_fields)[i]->GetAccessFlags(),
1432 i,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001433 i < encoded_values_size ? (*encoded_values)[i].get() : nullptr);
David Sehr853a8e12016-09-01 13:03:50 -07001434 } // for
1435 }
1436 }
David Sehr7629f602016-08-07 16:01:51 -07001437
1438 // Instance fields.
1439 if (options_.output_format_ == kOutputPlain) {
1440 fprintf(out_file_, " Instance fields -\n");
1441 }
David Sehr853a8e12016-09-01 13:03:50 -07001442 if (class_data != nullptr) {
1443 dex_ir::FieldItemVector* instance_fields = class_data->InstanceFields();
1444 if (instance_fields != nullptr) {
1445 for (uint32_t i = 0; i < instance_fields->size(); i++) {
1446 DumpIField(header,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001447 (*instance_fields)[i]->GetFieldId()->GetIndex(),
David Sehr853a8e12016-09-01 13:03:50 -07001448 (*instance_fields)[i]->GetAccessFlags(),
1449 i);
1450 } // for
1451 }
1452 }
David Sehr7629f602016-08-07 16:01:51 -07001453
1454 // Direct methods.
1455 if (options_.output_format_ == kOutputPlain) {
1456 fprintf(out_file_, " Direct methods -\n");
1457 }
David Sehr853a8e12016-09-01 13:03:50 -07001458 if (class_data != nullptr) {
1459 dex_ir::MethodItemVector* direct_methods = class_data->DirectMethods();
1460 if (direct_methods != nullptr) {
1461 for (uint32_t i = 0; i < direct_methods->size(); i++) {
1462 DumpMethod(header,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001463 (*direct_methods)[i]->GetMethodId()->GetIndex(),
David Sehr853a8e12016-09-01 13:03:50 -07001464 (*direct_methods)[i]->GetAccessFlags(),
1465 (*direct_methods)[i]->GetCodeItem(),
1466 i);
1467 } // for
1468 }
1469 }
David Sehr7629f602016-08-07 16:01:51 -07001470
1471 // Virtual methods.
1472 if (options_.output_format_ == kOutputPlain) {
1473 fprintf(out_file_, " Virtual methods -\n");
1474 }
David Sehr853a8e12016-09-01 13:03:50 -07001475 if (class_data != nullptr) {
1476 dex_ir::MethodItemVector* virtual_methods = class_data->VirtualMethods();
1477 if (virtual_methods != nullptr) {
1478 for (uint32_t i = 0; i < virtual_methods->size(); i++) {
1479 DumpMethod(header,
Jeff Hao3ab96b42016-09-09 18:35:01 -07001480 (*virtual_methods)[i]->GetMethodId()->GetIndex(),
David Sehr853a8e12016-09-01 13:03:50 -07001481 (*virtual_methods)[i]->GetAccessFlags(),
1482 (*virtual_methods)[i]->GetCodeItem(),
1483 i);
1484 } // for
1485 }
1486 }
David Sehr7629f602016-08-07 16:01:51 -07001487
1488 // End of class.
1489 if (options_.output_format_ == kOutputPlain) {
1490 const char* file_name = "unknown";
1491 if (class_def->SourceFile() != nullptr) {
1492 file_name = class_def->SourceFile()->Data();
1493 }
1494 const dex_ir::StringId* source_file = class_def->SourceFile();
1495 fprintf(out_file_, " source_file_idx : %d (%s)\n\n",
Jeff Hao3ab96b42016-09-09 18:35:01 -07001496 source_file == nullptr ? 0xffffffffU : source_file->GetIndex(), file_name);
David Sehr7629f602016-08-07 16:01:51 -07001497 } else if (options_.output_format_ == kOutputXml) {
1498 fprintf(out_file_, "</class>\n");
1499 }
1500
1501 free(access_str);
1502}
1503
1504/*
Nicolas Geoffrayfd1a6c22016-10-04 11:01:17 +00001505static uint32_t GetDataSectionOffset(dex_ir::Header& header) {
1506 return dex_ir::Header::ItemSize() +
1507 header.GetCollections().StringIdsSize() * dex_ir::StringId::ItemSize() +
1508 header.GetCollections().TypeIdsSize() * dex_ir::TypeId::ItemSize() +
1509 header.GetCollections().ProtoIdsSize() * dex_ir::ProtoId::ItemSize() +
1510 header.GetCollections().FieldIdsSize() * dex_ir::FieldId::ItemSize() +
1511 header.GetCollections().MethodIdsSize() * dex_ir::MethodId::ItemSize() +
1512 header.GetCollections().ClassDefsSize() * dex_ir::ClassDef::ItemSize();
1513}
1514
1515static bool Align(File* file, uint32_t& offset) {
1516 uint8_t zero_buffer[] = { 0, 0, 0 };
1517 uint32_t zeroes = (-offset) & 3;
1518 if (zeroes > 0) {
1519 if (!file->PwriteFully(zero_buffer, zeroes, offset)) {
1520 return false;
1521 }
1522 offset += zeroes;
1523 }
1524 return true;
1525}
1526
1527static bool WriteStrings(File* dex_file, dex_ir::Header& header,
1528 uint32_t& index_offset, uint32_t& data_offset) {
1529 uint32_t index = 0;
1530 uint32_t index_buffer[1];
1531 uint32_t string_length;
1532 uint32_t length_length;
1533 uint8_t length_buffer[8];
1534 for (std::unique_ptr<dex_ir::StringId>& string_id : header.GetCollections().StringIds()) {
1535 string_id->SetOffset(index);
1536 index_buffer[0] = data_offset;
1537 string_length = strlen(string_id->Data());
1538 length_length = UnsignedLeb128Size(string_length);
1539 EncodeUnsignedLeb128(length_buffer, string_length);
1540
1541 if (!dex_file->PwriteFully(index_buffer, 4, index_offset) ||
1542 !dex_file->PwriteFully(length_buffer, length_length, data_offset) ||
1543 !dex_file->PwriteFully(string_id->Data(), string_length, data_offset + length_length)) {
1544 return false;
1545 }
1546
1547 index++;
1548 index_offset += 4;
1549 data_offset += string_length + length_length;
1550 }
1551 return true;
1552}
1553
1554static bool WriteTypes(File* dex_file, dex_ir::Header& header, uint32_t& index_offset) {
1555 uint32_t index = 0;
1556 uint32_t index_buffer[1];
1557 for (std::unique_ptr<dex_ir::TypeId>& type_id : header.GetCollections().TypeIds()) {
1558 type_id->SetIndex(index);
1559 index_buffer[0] = type_id->GetStringId()->GetOffset();
1560
1561 if (!dex_file->PwriteFully(index_buffer, 4, index_offset)) {
1562 return false;
1563 }
1564
1565 index++;
1566 index_offset += 4;
1567 }
1568 return true;
1569}
1570
1571static bool WriteTypeLists(File* dex_file, dex_ir::Header& header, uint32_t& data_offset) {
1572 if (!Align(dex_file, data_offset)) {
1573 return false;
1574 }
1575
1576 return true;
1577}
1578
1579static void OutputDexFile(dex_ir::Header& header, const char* file_name) {
1580 LOG(INFO) << "FILE NAME: " << file_name;
1581 std::unique_ptr<File> dex_file(OS::CreateEmptyFileWriteOnly(file_name));
1582 if (dex_file == nullptr) {
1583 fprintf(stderr, "Can't open %s\n", file_name);
1584 return;
1585 }
1586
1587 uint32_t index_offset = dex_ir::Header::ItemSize();
1588 uint32_t data_offset = GetDataSectionOffset(header);
1589 WriteStrings(dex_file.get(), header, index_offset, data_offset);
1590 WriteTypes(dex_file.get(), header, index_offset);
1591}
1592*/
1593
1594/*
David Sehr7629f602016-08-07 16:01:51 -07001595 * Dumps the requested sections of the file.
1596 */
David Sehrcdcfde72016-09-26 07:44:04 -07001597static void ProcessDexFile(const char* file_name, const DexFile* dex_file, size_t dex_file_index) {
David Sehr7629f602016-08-07 16:01:51 -07001598 if (options_.verbose_) {
1599 fprintf(out_file_, "Opened '%s', DEX version '%.3s'\n",
1600 file_name, dex_file->GetHeader().magic_ + 4);
1601 }
David Sehr72359222016-09-07 13:04:01 -07001602 std::unique_ptr<dex_ir::Header> header(dex_ir::DexIrBuilder(*dex_file));
David Sehr7629f602016-08-07 16:01:51 -07001603
David Sehrcdcfde72016-09-26 07:44:04 -07001604 if (options_.visualize_pattern_) {
1605 VisualizeDexLayout(header.get(), dex_file, dex_file_index);
1606 return;
1607 }
1608
David Sehr7629f602016-08-07 16:01:51 -07001609 // Headers.
1610 if (options_.show_file_headers_) {
David Sehr72359222016-09-07 13:04:01 -07001611 DumpFileHeader(header.get());
David Sehr7629f602016-08-07 16:01:51 -07001612 }
1613
1614 // Open XML context.
1615 if (options_.output_format_ == kOutputXml) {
1616 fprintf(out_file_, "<api>\n");
1617 }
1618
1619 // Iterate over all classes.
1620 char* package = nullptr;
Jeff Hao3ab96b42016-09-09 18:35:01 -07001621 const uint32_t class_defs_size = header->GetCollections().ClassDefsSize();
David Sehr7629f602016-08-07 16:01:51 -07001622 for (uint32_t i = 0; i < class_defs_size; i++) {
David Sehr72359222016-09-07 13:04:01 -07001623 DumpClass(dex_file, header.get(), i, &package);
David Sehr7629f602016-08-07 16:01:51 -07001624 } // for
1625
1626 // Free the last package allocated.
1627 if (package != nullptr) {
1628 fprintf(out_file_, "</package>\n");
1629 free(package);
1630 }
1631
1632 // Close XML context.
1633 if (options_.output_format_ == kOutputXml) {
1634 fprintf(out_file_, "</api>\n");
1635 }
Jeff Hao3ab96b42016-09-09 18:35:01 -07001636
Nicolas Geoffrayfd1a6c22016-10-04 11:01:17 +00001637 /*
Jeff Hao3ab96b42016-09-09 18:35:01 -07001638 // Output dex file.
1639 if (options_.output_dex_files_) {
1640 std::string output_dex_filename = dex_file->GetLocation() + ".out";
Nicolas Geoffrayfd1a6c22016-10-04 11:01:17 +00001641 OutputDexFile(*header, output_dex_filename.c_str());
Jeff Hao3ab96b42016-09-09 18:35:01 -07001642 }
Nicolas Geoffrayfd1a6c22016-10-04 11:01:17 +00001643 */
David Sehr7629f602016-08-07 16:01:51 -07001644}
1645
1646/*
1647 * Processes a single file (either direct .dex or indirect .zip/.jar/.apk).
1648 */
1649int ProcessFile(const char* file_name) {
1650 if (options_.verbose_) {
1651 fprintf(out_file_, "Processing '%s'...\n", file_name);
1652 }
1653
1654 // If the file is not a .dex file, the function tries .zip/.jar/.apk files,
1655 // all of which are Zip archives with "classes.dex" inside.
1656 const bool verify_checksum = !options_.ignore_bad_checksum_;
1657 std::string error_msg;
1658 std::vector<std::unique_ptr<const DexFile>> dex_files;
1659 if (!DexFile::Open(file_name, file_name, verify_checksum, &error_msg, &dex_files)) {
1660 // Display returned error message to user. Note that this error behavior
1661 // differs from the error messages shown by the original Dalvik dexdump.
1662 fputs(error_msg.c_str(), stderr);
1663 fputc('\n', stderr);
1664 return -1;
1665 }
1666
1667 // Success. Either report checksum verification or process
1668 // all dex files found in given file.
1669 if (options_.checksum_only_) {
1670 fprintf(out_file_, "Checksum verified\n");
1671 } else {
1672 for (size_t i = 0; i < dex_files.size(); i++) {
David Sehrcdcfde72016-09-26 07:44:04 -07001673 ProcessDexFile(file_name, dex_files[i].get(), i);
David Sehr7629f602016-08-07 16:01:51 -07001674 }
1675 }
1676 return 0;
1677}
1678
1679} // namespace art