oatdump.cc revision 90ca5c0301651101de0e363842e5d08ae65233f7
1/*
2 * Copyright (C) 2011 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
17#include <stdio.h>
18#include <stdlib.h>
19
20#include <fstream>
21#include <iostream>
22#include <string>
23#include <vector>
24
25#include "base/stringpiece.h"
26#include "base/unix_file/fd_file.h"
27#include "class_linker.h"
28#include "class_linker-inl.h"
29#include "dex_file-inl.h"
30#include "dex_instruction.h"
31#include "disassembler.h"
32#include "field_helper.h"
33#include "gc_map.h"
34#include "gc/space/image_space.h"
35#include "gc/space/large_object_space.h"
36#include "gc/space/space-inl.h"
37#include "image.h"
38#include "indenter.h"
39#include "mapping_table.h"
40#include "mirror/art_field-inl.h"
41#include "mirror/art_method-inl.h"
42#include "mirror/array-inl.h"
43#include "mirror/class-inl.h"
44#include "mirror/object-inl.h"
45#include "mirror/object_array-inl.h"
46#include "noop_compiler_callbacks.h"
47#include "oat.h"
48#include "oat_file-inl.h"
49#include "os.h"
50#include "runtime.h"
51#include "safe_map.h"
52#include "scoped_thread_state_change.h"
53#include "thread_list.h"
54#include "verifier/dex_gc_map.h"
55#include "verifier/method_verifier.h"
56#include "vmap_table.h"
57
58namespace art {
59
60static void usage() {
61  fprintf(stderr,
62          "Usage: oatdump [options] ...\n"
63          "    Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
64          "    Example: adb shell oatdump --image=/system/framework/boot.art\n"
65          "\n");
66  fprintf(stderr,
67          "  --oat-file=<file.oat>: specifies an input oat filename.\n"
68          "      Example: --oat-file=/system/framework/boot.oat\n"
69          "\n");
70  fprintf(stderr,
71          "  --image=<file.art>: specifies an input image filename.\n"
72          "      Example: --image=/system/framework/boot.art\n"
73          "\n");
74  fprintf(stderr,
75          "  --boot-image=<file.art>: provide the image file for the boot class path.\n"
76          "      Example: --boot-image=/system/framework/boot.art\n"
77          "\n");
78  fprintf(stderr,
79          "  --instruction-set=(arm|arm64|mips|x86|x86_64): for locating the image\n"
80          "      file based on the image location set.\n"
81          "      Example: --instruction-set=x86\n"
82          "      Default: %s\n"
83          "\n",
84          GetInstructionSetString(kRuntimeISA));
85  fprintf(stderr,
86          "  --output=<file> may be used to send the output to a file.\n"
87          "      Example: --output=/tmp/oatdump.txt\n"
88          "\n");
89  fprintf(stderr,
90          "  --dump:raw_mapping_table enables dumping of the mapping table.\n"
91          "      Example: --dump:raw_mapping_table\n"
92          "\n");
93  fprintf(stderr,
94          "  --dump:raw_mapping_table enables dumping of the GC map.\n"
95          "      Example: --dump:raw_gc_map\n"
96          "\n");
97  fprintf(stderr,
98          "  --no-dump:vmap may be used to disable vmap dumping.\n"
99          "      Example: --no-dump:vmap\n"
100          "\n");
101  fprintf(stderr,
102          "  --no-disassemble may be used to disable disassembly.\n"
103          "      Example: --no-disassemble\n"
104          "\n");
105  exit(EXIT_FAILURE);
106}
107
108const char* image_roots_descriptions_[] = {
109  "kResolutionMethod",
110  "kImtConflictMethod",
111  "kImtUnimplementedMethod",
112  "kDefaultImt",
113  "kCalleeSaveMethod",
114  "kRefsOnlySaveMethod",
115  "kRefsAndArgsSaveMethod",
116  "kDexCaches",
117  "kClassRoots",
118};
119
120class OatDumperOptions {
121 public:
122  OatDumperOptions(bool dump_raw_mapping_table,
123                   bool dump_raw_gc_map,
124                   bool dump_vmap,
125                   bool disassemble_code,
126                   bool absolute_addresses)
127    : dump_raw_mapping_table_(dump_raw_mapping_table),
128      dump_raw_gc_map_(dump_raw_gc_map),
129      dump_vmap_(dump_vmap),
130      disassemble_code_(disassemble_code),
131      absolute_addresses_(absolute_addresses) {}
132
133  const bool dump_raw_mapping_table_;
134  const bool dump_raw_gc_map_;
135  const bool dump_vmap_;
136  const bool disassemble_code_;
137  const bool absolute_addresses_;
138};
139
140class OatDumper {
141 public:
142  explicit OatDumper(const OatFile& oat_file, OatDumperOptions* options)
143    : oat_file_(oat_file),
144      oat_dex_files_(oat_file.GetOatDexFiles()),
145      options_(options),
146      disassembler_(Disassembler::Create(oat_file_.GetOatHeader().GetInstructionSet(),
147                                         new DisassemblerOptions(options_->absolute_addresses_,
148                                                                 oat_file.Begin()))) {
149    AddAllOffsets();
150  }
151
152  ~OatDumper() {
153    delete options_;
154    delete disassembler_;
155  }
156
157  bool Dump(std::ostream& os) {
158    bool success = true;
159    const OatHeader& oat_header = oat_file_.GetOatHeader();
160
161    os << "MAGIC:\n";
162    os << oat_header.GetMagic() << "\n\n";
163
164    os << "CHECKSUM:\n";
165    os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
166
167    os << "INSTRUCTION SET:\n";
168    os << oat_header.GetInstructionSet() << "\n\n";
169
170    os << "INSTRUCTION SET FEATURES:\n";
171    os << oat_header.GetInstructionSetFeatures().GetFeatureString() << "\n\n";
172
173    os << "DEX FILE COUNT:\n";
174    os << oat_header.GetDexFileCount() << "\n\n";
175
176#define DUMP_OAT_HEADER_OFFSET(label, offset) \
177    os << label " OFFSET:\n"; \
178    os << StringPrintf("0x%08x", oat_header.offset()); \
179    if (oat_header.offset() != 0 && options_->absolute_addresses_) { \
180      os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
181    } \
182    os << StringPrintf("\n\n");
183
184    DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
185    DUMP_OAT_HEADER_OFFSET("INTERPRETER TO INTERPRETER BRIDGE",
186                           GetInterpreterToInterpreterBridgeOffset);
187    DUMP_OAT_HEADER_OFFSET("INTERPRETER TO COMPILED CODE BRIDGE",
188                           GetInterpreterToCompiledCodeBridgeOffset);
189    DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP",
190                           GetJniDlsymLookupOffset);
191    DUMP_OAT_HEADER_OFFSET("PORTABLE IMT CONFLICT TRAMPOLINE",
192                           GetPortableImtConflictTrampolineOffset);
193    DUMP_OAT_HEADER_OFFSET("PORTABLE RESOLUTION TRAMPOLINE",
194                           GetPortableResolutionTrampolineOffset);
195    DUMP_OAT_HEADER_OFFSET("PORTABLE TO INTERPRETER BRIDGE",
196                           GetPortableToInterpreterBridgeOffset);
197    DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
198                           GetQuickGenericJniTrampolineOffset);
199    DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
200                           GetQuickImtConflictTrampolineOffset);
201    DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
202                           GetQuickResolutionTrampolineOffset);
203    DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
204                           GetQuickToInterpreterBridgeOffset);
205#undef DUMP_OAT_HEADER_OFFSET
206
207    os << "IMAGE PATCH DELTA:\n";
208    os << StringPrintf("%d (0x%08x)\n\n",
209                       oat_header.GetImagePatchDelta(),
210                       oat_header.GetImagePatchDelta());
211
212    os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
213    os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
214
215    os << "IMAGE FILE LOCATION OAT BEGIN:\n";
216    os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
217
218    // Print the key-value store.
219    {
220      os << "KEY VALUE STORE:\n";
221      size_t index = 0;
222      const char* key;
223      const char* value;
224      while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
225        os << key << " = " << value << "\n";
226        index++;
227      }
228      os << "\n";
229    }
230
231    if (options_->absolute_addresses_) {
232      os << "BEGIN:\n";
233      os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
234
235      os << "END:\n";
236      os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
237    }
238
239    os << "SIZE:\n";
240    os << oat_file_.Size() << "\n\n";
241
242    os << std::flush;
243
244    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
245      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
246      CHECK(oat_dex_file != nullptr);
247      if (!DumpOatDexFile(os, *oat_dex_file)) {
248        success = false;
249      }
250    }
251    os << std::flush;
252    return success;
253  }
254
255  size_t ComputeSize(const void* oat_data) {
256    if (reinterpret_cast<const byte*>(oat_data) < oat_file_.Begin() ||
257        reinterpret_cast<const byte*>(oat_data) > oat_file_.End()) {
258      return 0;  // Address not in oat file
259    }
260    uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
261                             reinterpret_cast<uintptr_t>(oat_file_.Begin());
262    auto it = offsets_.upper_bound(begin_offset);
263    CHECK(it != offsets_.end());
264    uintptr_t end_offset = *it;
265    return end_offset - begin_offset;
266  }
267
268  InstructionSet GetInstructionSet() {
269    return oat_file_.GetOatHeader().GetInstructionSet();
270  }
271
272  const void* GetQuickOatCode(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
273    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
274      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
275      CHECK(oat_dex_file != nullptr);
276      std::string error_msg;
277      std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
278      if (dex_file.get() == nullptr) {
279        LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
280            << "': " << error_msg;
281      } else {
282        const DexFile::ClassDef* class_def =
283            dex_file->FindClassDef(m->GetDeclaringClassDescriptor());
284        if (class_def != nullptr) {
285          uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
286          const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
287          size_t method_index = m->GetMethodIndex();
288          return oat_class.GetOatMethod(method_index).GetQuickCode();
289        }
290      }
291    }
292    return nullptr;
293  }
294
295 private:
296  void AddAllOffsets() {
297    // We don't know the length of the code for each method, but we need to know where to stop
298    // when disassembling. What we do know is that a region of code will be followed by some other
299    // region, so if we keep a sorted sequence of the start of each region, we can infer the length
300    // of a piece of code by using upper_bound to find the start of the next region.
301    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
302      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
303      CHECK(oat_dex_file != nullptr);
304      std::string error_msg;
305      std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
306      if (dex_file.get() == nullptr) {
307        LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
308            << "': " << error_msg;
309        continue;
310      }
311      offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
312      for (size_t class_def_index = 0;
313           class_def_index < dex_file->NumClassDefs();
314           class_def_index++) {
315        const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
316        const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
317        const byte* class_data = dex_file->GetClassData(class_def);
318        if (class_data != nullptr) {
319          ClassDataItemIterator it(*dex_file, class_data);
320          SkipAllFields(it);
321          uint32_t class_method_index = 0;
322          while (it.HasNextDirectMethod()) {
323            AddOffsets(oat_class.GetOatMethod(class_method_index++));
324            it.Next();
325          }
326          while (it.HasNextVirtualMethod()) {
327            AddOffsets(oat_class.GetOatMethod(class_method_index++));
328            it.Next();
329          }
330        }
331      }
332    }
333
334    // If the last thing in the file is code for a method, there won't be an offset for the "next"
335    // thing. Instead of having a special case in the upper_bound code, let's just add an entry
336    // for the end of the file.
337    offsets_.insert(oat_file_.Size());
338  }
339
340  static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
341    return maybe_thumb_offset & ~0x1;  // TODO: Make this Thumb2 specific.
342  }
343
344  void AddOffsets(const OatFile::OatMethod& oat_method) {
345    uint32_t code_offset = oat_method.GetCodeOffset();
346    if (oat_file_.GetOatHeader().GetInstructionSet() == kThumb2) {
347      code_offset &= ~0x1;
348    }
349    offsets_.insert(code_offset);
350    offsets_.insert(oat_method.GetMappingTableOffset());
351    offsets_.insert(oat_method.GetVmapTableOffset());
352    offsets_.insert(oat_method.GetNativeGcMapOffset());
353  }
354
355  bool DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
356    bool success = true;
357    os << "OatDexFile:\n";
358    os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
359    os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
360
361    // Create the verifier early.
362
363    std::string error_msg;
364    std::unique_ptr<const DexFile> dex_file(oat_dex_file.OpenDexFile(&error_msg));
365    if (dex_file.get() == nullptr) {
366      os << "NOT FOUND: " << error_msg << "\n\n";
367      os << std::flush;
368      return false;
369    }
370    for (size_t class_def_index = 0;
371         class_def_index < dex_file->NumClassDefs();
372         class_def_index++) {
373      const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
374      const char* descriptor = dex_file->GetClassDescriptor(class_def);
375      uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
376      const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
377      os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
378                         class_def_index, descriptor, oat_class_offset, class_def.class_idx_)
379         << " (" << oat_class.GetStatus() << ")"
380         << " (" << oat_class.GetType() << ")\n";
381      // TODO: include bitmap here if type is kOatClassSomeCompiled?
382      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
383      std::ostream indented_os(&indent_filter);
384      if (!DumpOatClass(indented_os, oat_class, *(dex_file.get()), class_def)) {
385        success = false;
386      }
387    }
388
389    os << std::flush;
390    return success;
391  }
392
393  static void SkipAllFields(ClassDataItemIterator& it) {
394    while (it.HasNextStaticField()) {
395      it.Next();
396    }
397    while (it.HasNextInstanceField()) {
398      it.Next();
399    }
400  }
401
402  bool DumpOatClass(std::ostream& os, const OatFile::OatClass& oat_class, const DexFile& dex_file,
403                    const DexFile::ClassDef& class_def) {
404    bool success = true;
405    const byte* class_data = dex_file.GetClassData(class_def);
406    if (class_data == nullptr) {  // empty class such as a marker interface?
407      os << std::flush;
408      return success;
409    }
410    ClassDataItemIterator it(dex_file, class_data);
411    SkipAllFields(it);
412    uint32_t class_method_index = 0;
413    while (it.HasNextDirectMethod()) {
414      if (!DumpOatMethod(os, class_def, class_method_index, oat_class, dex_file,
415                         it.GetMemberIndex(), it.GetMethodCodeItem(),
416                         it.GetRawMemberAccessFlags())) {
417        success = false;
418      }
419      class_method_index++;
420      it.Next();
421    }
422    while (it.HasNextVirtualMethod()) {
423      if (!DumpOatMethod(os, class_def, class_method_index, oat_class, dex_file,
424                         it.GetMemberIndex(), it.GetMethodCodeItem(),
425                         it.GetRawMemberAccessFlags())) {
426        success = false;
427      }
428      class_method_index++;
429      it.Next();
430    }
431    DCHECK(!it.HasNext());
432    os << std::flush;
433    return success;
434  }
435
436  static constexpr uint32_t kPrologueBytes = 16;
437
438  // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
439  static constexpr uint32_t kMaxCodeSize = 100 * 1000;
440
441  bool DumpOatMethod(std::ostream& os, const DexFile::ClassDef& class_def,
442                     uint32_t class_method_index,
443                     const OatFile::OatClass& oat_class, const DexFile& dex_file,
444                     uint32_t dex_method_idx, const DexFile::CodeItem* code_item,
445                     uint32_t method_access_flags) {
446    bool success = true;
447    os << StringPrintf("%d: %s (dex_method_idx=%d)\n",
448                       class_method_index, PrettyMethod(dex_method_idx, dex_file, true).c_str(),
449                       dex_method_idx);
450    Indenter indent1_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
451    std::unique_ptr<std::ostream> indent1_os(new std::ostream(&indent1_filter));
452    Indenter indent2_filter(indent1_os->rdbuf(), kIndentChar, kIndentBy1Count);
453    std::unique_ptr<std::ostream> indent2_os(new std::ostream(&indent2_filter));
454    {
455      *indent1_os << "DEX CODE:\n";
456      DumpDexCode(*indent2_os, dex_file, code_item);
457    }
458
459    std::unique_ptr<verifier::MethodVerifier> verifier;
460    if (Runtime::Current() != nullptr) {
461      *indent1_os << "VERIFIER TYPE ANALYSIS:\n";
462      verifier.reset(DumpVerifier(*indent2_os, dex_method_idx, &dex_file, class_def, code_item,
463                                  method_access_flags));
464    }
465
466    uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
467    const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
468    const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
469    {
470      *indent1_os << "OatMethodOffsets ";
471      if (options_->absolute_addresses_) {
472        *indent1_os << StringPrintf("%p ", oat_method_offsets);
473      }
474      *indent1_os << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
475      if (oat_method_offsets_offset > oat_file_.Size()) {
476        *indent1_os << StringPrintf(
477            "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
478            oat_method_offsets_offset, oat_file_.Size());
479        // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
480        os << std::flush;
481        return false;
482      }
483
484      uint32_t code_offset = oat_method.GetCodeOffset();
485      *indent2_os << StringPrintf("code_offset: 0x%08x ", code_offset);
486      uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
487      if (aligned_code_begin > oat_file_.Size()) {
488        *indent2_os << StringPrintf("WARNING: "
489                                    "code offset 0x%08x is past end of file 0x%08zx.\n",
490                                    aligned_code_begin, oat_file_.Size());
491        success = false;
492      }
493      *indent2_os << "\n";
494
495      *indent2_os << "gc_map: ";
496      if (options_->absolute_addresses_) {
497        *indent2_os << StringPrintf("%p ", oat_method.GetNativeGcMap());
498      }
499      uint32_t gc_map_offset = oat_method.GetNativeGcMapOffset();
500      *indent2_os << StringPrintf("(offset=0x%08x)\n", gc_map_offset);
501      if (gc_map_offset > oat_file_.Size()) {
502        *indent2_os << StringPrintf("WARNING: "
503                                    "gc map table offset 0x%08x is past end of file 0x%08zx.\n",
504                                    gc_map_offset, oat_file_.Size());
505        success = false;
506      } else if (options_->dump_raw_gc_map_) {
507        Indenter indent3_filter(indent2_os->rdbuf(), kIndentChar, kIndentBy1Count);
508        std::ostream indent3_os(&indent3_filter);
509        DumpGcMap(indent3_os, oat_method, code_item);
510      }
511    }
512    {
513      *indent1_os << "OatQuickMethodHeader ";
514      uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
515      const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
516
517      if (options_->absolute_addresses_) {
518        *indent1_os << StringPrintf("%p ", method_header);
519      }
520      *indent1_os << StringPrintf("(offset=0x%08x)\n", method_header_offset);
521      if (method_header_offset > oat_file_.Size()) {
522        *indent1_os << StringPrintf(
523            "WARNING: oat quick method header offset 0x%08x is past end of file 0x%08zx.\n",
524            method_header_offset, oat_file_.Size());
525        // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
526        os << std::flush;
527        return false;
528      }
529
530      *indent2_os << "mapping_table: ";
531      if (options_->absolute_addresses_) {
532        *indent2_os << StringPrintf("%p ", oat_method.GetMappingTable());
533      }
534      uint32_t mapping_table_offset = oat_method.GetMappingTableOffset();
535      *indent2_os << StringPrintf("(offset=0x%08x)\n", oat_method.GetMappingTableOffset());
536      if (mapping_table_offset > oat_file_.Size()) {
537        *indent2_os << StringPrintf("WARNING: "
538                                    "mapping table offset 0x%08x is past end of file 0x%08zx. "
539                                    "mapping table offset was loaded from offset 0x%08x.\n",
540                                    mapping_table_offset, oat_file_.Size(),
541                                    oat_method.GetMappingTableOffsetOffset());
542        success = false;
543      } else if (options_->dump_raw_mapping_table_) {
544        Indenter indent3_filter(indent2_os->rdbuf(), kIndentChar, kIndentBy1Count);
545        std::ostream indent3_os(&indent3_filter);
546        DumpMappingTable(indent3_os, oat_method);
547      }
548
549      *indent2_os << "vmap_table: ";
550      if (options_->absolute_addresses_) {
551        *indent2_os << StringPrintf("%p ", oat_method.GetVmapTable());
552      }
553      uint32_t vmap_table_offset = oat_method.GetVmapTableOffset();
554      *indent2_os << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
555      if (vmap_table_offset > oat_file_.Size()) {
556        *indent2_os << StringPrintf("WARNING: "
557                                    "vmap table offset 0x%08x is past end of file 0x%08zx. "
558                                    "vmap table offset was loaded from offset 0x%08x.\n",
559                                    vmap_table_offset, oat_file_.Size(),
560                                    oat_method.GetVmapTableOffsetOffset());
561        success = false;
562      } else if (options_->dump_vmap_) {
563        DumpVmap(*indent2_os, oat_method);
564      }
565    }
566    {
567      *indent1_os << "QuickMethodFrameInfo\n";
568
569      *indent2_os << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
570      *indent2_os << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
571      DumpSpillMask(*indent2_os, oat_method.GetCoreSpillMask(), false);
572      *indent2_os << "\n";
573      *indent2_os << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
574      DumpSpillMask(*indent2_os, oat_method.GetFpSpillMask(), true);
575      *indent2_os << "\n";
576    }
577    {
578      *indent1_os << "CODE: ";
579      uint32_t code_size_offset = oat_method.GetQuickCodeSizeOffset();
580      if (code_size_offset > oat_file_.Size()) {
581        *indent2_os << StringPrintf("WARNING: "
582                                    "code size offset 0x%08x is past end of file 0x%08zx.",
583                                    code_size_offset, oat_file_.Size());
584        success = false;
585      } else {
586        const void* code = oat_method.GetQuickCode();
587        uint32_t code_size = oat_method.GetQuickCodeSize();
588        if (code == nullptr) {
589          code = oat_method.GetPortableCode();
590          code_size = oat_method.GetPortableCodeSize();
591          code_size_offset = 0;
592        }
593        uint32_t code_offset = oat_method.GetCodeOffset();
594        uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
595        uint64_t aligned_code_end = aligned_code_begin + code_size;
596
597        if (options_->absolute_addresses_) {
598          *indent1_os << StringPrintf("%p ", code);
599        }
600        *indent1_os << StringPrintf("(code_offset=0x%08x size_offset=0x%08x size=%u)%s\n",
601                                    code_offset,
602                                    code_size_offset,
603                                    code_size,
604                                    code != nullptr ? "..." : "");
605
606        if (aligned_code_begin > oat_file_.Size()) {
607          *indent2_os << StringPrintf("WARNING: "
608                                      "start of code at 0x%08x is past end of file 0x%08zx.",
609                                      aligned_code_begin, oat_file_.Size());
610          success = false;
611        } else if (aligned_code_end > oat_file_.Size()) {
612          *indent2_os << StringPrintf("WARNING: "
613                                      "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
614                                      "code size is 0x%08x loaded from offset 0x%08x.\n",
615                                      aligned_code_end, oat_file_.Size(),
616                                      code_size, code_size_offset);
617          success = false;
618          if (options_->disassemble_code_) {
619            if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
620              DumpCode(*indent2_os, verifier.get(), oat_method, code_item, true, kPrologueBytes);
621            }
622          }
623        } else if (code_size > kMaxCodeSize) {
624          *indent2_os << StringPrintf("WARNING: "
625                                      "code size %d is bigger than max expected threshold of %d. "
626                                      "code size is 0x%08x loaded from offset 0x%08x.\n",
627                                      code_size, kMaxCodeSize,
628                                      code_size, code_size_offset);
629          success = false;
630          if (options_->disassemble_code_) {
631            if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
632              DumpCode(*indent2_os, verifier.get(), oat_method, code_item, true, kPrologueBytes);
633            }
634          }
635        } else if (options_->disassemble_code_) {
636          DumpCode(*indent2_os, verifier.get(), oat_method, code_item, !success, 0);
637        }
638      }
639    }
640    os << std::flush;
641    return success;
642  }
643
644  void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
645    if (spill_mask == 0) {
646      return;
647    }
648    os << "(";
649    for (size_t i = 0; i < 32; i++) {
650      if ((spill_mask & (1 << i)) != 0) {
651        if (is_float) {
652          os << "fr" << i;
653        } else {
654          os << "r" << i;
655        }
656        spill_mask ^= 1 << i;  // clear bit
657        if (spill_mask != 0) {
658          os << ", ";
659        } else {
660          break;
661        }
662      }
663    }
664    os << ")";
665  }
666
667  void DumpVmap(std::ostream& os, const OatFile::OatMethod& oat_method) {
668    const uint8_t* raw_table = oat_method.GetVmapTable();
669    if (raw_table != nullptr) {
670      const VmapTable vmap_table(raw_table);
671      bool first = true;
672      bool processing_fp = false;
673      uint32_t spill_mask = oat_method.GetCoreSpillMask();
674      for (size_t i = 0; i < vmap_table.Size(); i++) {
675        uint16_t dex_reg = vmap_table[i];
676        uint32_t cpu_reg = vmap_table.ComputeRegister(spill_mask, i,
677                                                      processing_fp ? kFloatVReg : kIntVReg);
678        os << (first ? "v" : ", v")  << dex_reg;
679        if (!processing_fp) {
680          os << "/r" << cpu_reg;
681        } else {
682          os << "/fr" << cpu_reg;
683        }
684        first = false;
685        if (!processing_fp && dex_reg == 0xFFFF) {
686          processing_fp = true;
687          spill_mask = oat_method.GetFpSpillMask();
688        }
689      }
690      os << "\n";
691    }
692  }
693
694  void DescribeVReg(std::ostream& os, const OatFile::OatMethod& oat_method,
695                    const DexFile::CodeItem* code_item, size_t reg, VRegKind kind) {
696    const uint8_t* raw_table = oat_method.GetVmapTable();
697    if (raw_table != nullptr) {
698      const VmapTable vmap_table(raw_table);
699      uint32_t vmap_offset;
700      if (vmap_table.IsInContext(reg, kind, &vmap_offset)) {
701        bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
702        uint32_t spill_mask = is_float ? oat_method.GetFpSpillMask()
703                                       : oat_method.GetCoreSpillMask();
704        os << (is_float ? "fr" : "r") << vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
705      } else {
706        uint32_t offset = StackVisitor::GetVRegOffset(code_item, oat_method.GetCoreSpillMask(),
707                                                      oat_method.GetFpSpillMask(),
708                                                      oat_method.GetFrameSizeInBytes(), reg,
709                                                      GetInstructionSet());
710        os << "[sp + #" << offset << "]";
711      }
712    }
713  }
714
715  void DumpGcMapRegisters(std::ostream& os, const OatFile::OatMethod& oat_method,
716                          const DexFile::CodeItem* code_item,
717                          size_t num_regs, const uint8_t* reg_bitmap) {
718    bool first = true;
719    for (size_t reg = 0; reg < num_regs; reg++) {
720      if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
721        if (first) {
722          os << "  v" << reg << " (";
723          DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
724          os << ")";
725          first = false;
726        } else {
727          os << ", v" << reg << " (";
728          DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
729          os << ")";
730        }
731      }
732    }
733    if (first) {
734      os << "No registers in GC map\n";
735    } else {
736      os << "\n";
737    }
738  }
739  void DumpGcMap(std::ostream& os, const OatFile::OatMethod& oat_method,
740                 const DexFile::CodeItem* code_item) {
741    const uint8_t* gc_map_raw = oat_method.GetNativeGcMap();
742    if (gc_map_raw == nullptr) {
743      return;  // No GC map.
744    }
745    const void* quick_code = oat_method.GetQuickCode();
746    if (quick_code != nullptr) {
747      NativePcOffsetToReferenceMap map(gc_map_raw);
748      for (size_t entry = 0; entry < map.NumEntries(); entry++) {
749        const uint8_t* native_pc = reinterpret_cast<const uint8_t*>(quick_code) +
750            map.GetNativePcOffset(entry);
751        os << StringPrintf("%p", native_pc);
752        DumpGcMapRegisters(os, oat_method, code_item, map.RegWidth() * 8, map.GetBitMap(entry));
753      }
754    } else {
755      const void* portable_code = oat_method.GetPortableCode();
756      CHECK(portable_code != nullptr);
757      verifier::DexPcToReferenceMap map(gc_map_raw);
758      for (size_t entry = 0; entry < map.NumEntries(); entry++) {
759        uint32_t dex_pc = map.GetDexPc(entry);
760        os << StringPrintf("0x%08x", dex_pc);
761        DumpGcMapRegisters(os, oat_method, code_item, map.RegWidth() * 8, map.GetBitMap(entry));
762      }
763    }
764  }
765
766  void DumpMappingTable(std::ostream& os, const OatFile::OatMethod& oat_method) {
767    const void* quick_code = oat_method.GetQuickCode();
768    if (quick_code == nullptr) {
769      return;
770    }
771    MappingTable table(oat_method.GetMappingTable());
772    if (table.TotalSize() != 0) {
773      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
774      std::ostream indent_os(&indent_filter);
775      if (table.PcToDexSize() != 0) {
776        typedef MappingTable::PcToDexIterator It;
777        os << "suspend point mappings {\n";
778        for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
779          indent_os << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
780        }
781        os << "}\n";
782      }
783      if (table.DexToPcSize() != 0) {
784        typedef MappingTable::DexToPcIterator It;
785        os << "catch entry mappings {\n";
786        for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
787          indent_os << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
788        }
789        os << "}\n";
790      }
791    }
792  }
793
794  uint32_t DumpMappingAtOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
795                               size_t offset, bool suspend_point_mapping) {
796    MappingTable table(oat_method.GetMappingTable());
797    if (suspend_point_mapping && table.PcToDexSize() > 0) {
798      typedef MappingTable::PcToDexIterator It;
799      for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
800        if (offset == cur.NativePcOffset()) {
801          os << StringPrintf("suspend point dex PC: 0x%04x\n", cur.DexPc());
802          return cur.DexPc();
803        }
804      }
805    } else if (!suspend_point_mapping && table.DexToPcSize() > 0) {
806      typedef MappingTable::DexToPcIterator It;
807      for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
808        if (offset == cur.NativePcOffset()) {
809          os << StringPrintf("catch entry dex PC: 0x%04x\n", cur.DexPc());
810          return cur.DexPc();
811        }
812      }
813    }
814    return DexFile::kDexNoIndex;
815  }
816
817  void DumpGcMapAtNativePcOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
818                                 const DexFile::CodeItem* code_item, size_t native_pc_offset) {
819    const uint8_t* gc_map_raw = oat_method.GetNativeGcMap();
820    if (gc_map_raw != nullptr) {
821      NativePcOffsetToReferenceMap map(gc_map_raw);
822      if (map.HasEntry(native_pc_offset)) {
823        size_t num_regs = map.RegWidth() * 8;
824        const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset);
825        bool first = true;
826        for (size_t reg = 0; reg < num_regs; reg++) {
827          if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
828            if (first) {
829              os << "GC map objects:  v" << reg << " (";
830              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
831              os << ")";
832              first = false;
833            } else {
834              os << ", v" << reg << " (";
835              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
836              os << ")";
837            }
838          }
839        }
840        if (!first) {
841          os << "\n";
842        }
843      }
844    }
845  }
846
847  void DumpVRegsAtDexPc(std::ostream& os, verifier::MethodVerifier* verifier,
848                        const OatFile::OatMethod& oat_method,
849                        const DexFile::CodeItem* code_item, uint32_t dex_pc) {
850    DCHECK(verifier != nullptr);
851    std::vector<int32_t> kinds = verifier->DescribeVRegs(dex_pc);
852    bool first = true;
853    for (size_t reg = 0; reg < code_item->registers_size_; reg++) {
854      VRegKind kind = static_cast<VRegKind>(kinds.at(reg * 2));
855      if (kind != kUndefined) {
856        if (first) {
857          os << "VRegs:  v";
858          first = false;
859        } else {
860          os << ", v";
861        }
862        os << reg << " (";
863        switch (kind) {
864          case kImpreciseConstant:
865            os << "Imprecise Constant: " << kinds.at((reg * 2) + 1) << ", ";
866            DescribeVReg(os, oat_method, code_item, reg, kind);
867            break;
868          case kConstant:
869            os << "Constant: " << kinds.at((reg * 2) + 1);
870            break;
871          default:
872            DescribeVReg(os, oat_method, code_item, reg, kind);
873            break;
874        }
875        os << ")";
876      }
877    }
878    if (!first) {
879      os << "\n";
880    }
881  }
882
883
884  void DumpDexCode(std::ostream& os, const DexFile& dex_file, const DexFile::CodeItem* code_item) {
885    if (code_item != nullptr) {
886      size_t i = 0;
887      while (i < code_item->insns_size_in_code_units_) {
888        const Instruction* instruction = Instruction::At(&code_item->insns_[i]);
889        os << StringPrintf("0x%04zx: %s\n", i, instruction->DumpString(&dex_file).c_str());
890        i += instruction->SizeInCodeUnits();
891      }
892    }
893  }
894
895  verifier::MethodVerifier* DumpVerifier(std::ostream& os, uint32_t dex_method_idx,
896                                         const DexFile* dex_file,
897                                         const DexFile::ClassDef& class_def,
898                                         const DexFile::CodeItem* code_item,
899                                         uint32_t method_access_flags) {
900    if ((method_access_flags & kAccNative) == 0) {
901      ScopedObjectAccess soa(Thread::Current());
902      StackHandleScope<2> hs(soa.Self());
903      Handle<mirror::DexCache> dex_cache(
904          hs.NewHandle(Runtime::Current()->GetClassLinker()->FindDexCache(*dex_file)));
905      auto class_loader(hs.NewHandle<mirror::ClassLoader>(nullptr));
906      return verifier::MethodVerifier::VerifyMethodAndDump(os, dex_method_idx, dex_file, dex_cache,
907                                                           class_loader, &class_def, code_item,
908                                                           nullptr, method_access_flags);
909    }
910
911    return nullptr;
912  }
913
914  void DumpCode(std::ostream& os, verifier::MethodVerifier* verifier,
915                const OatFile::OatMethod& oat_method, const DexFile::CodeItem* code_item,
916                bool bad_input, size_t code_size) {
917    const void* portable_code = oat_method.GetPortableCode();
918    const void* quick_code = oat_method.GetQuickCode();
919
920    if (code_size == 0) {
921      code_size = oat_method.GetQuickCodeSize();
922    }
923    if ((code_size == 0) || ((portable_code == nullptr) && (quick_code == nullptr))) {
924      os << "NO CODE!\n";
925      return;
926    } else if (quick_code != nullptr) {
927      const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
928      size_t offset = 0;
929      while (offset < code_size) {
930        if (!bad_input) {
931          DumpMappingAtOffset(os, oat_method, offset, false);
932        }
933        offset += disassembler_->Dump(os, quick_native_pc + offset);
934        if (!bad_input) {
935          uint32_t dex_pc = DumpMappingAtOffset(os, oat_method, offset, true);
936          if (dex_pc != DexFile::kDexNoIndex) {
937            DumpGcMapAtNativePcOffset(os, oat_method, code_item, offset);
938            if (verifier != nullptr) {
939              DumpVRegsAtDexPc(os, verifier, oat_method, code_item, dex_pc);
940            }
941          }
942        }
943      }
944    } else {
945      CHECK(portable_code != nullptr);
946      CHECK_EQ(code_size, 0U);  // TODO: disassembly of portable is currently not supported.
947    }
948  }
949
950  const OatFile& oat_file_;
951  const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
952  const OatDumperOptions* options_;
953  std::set<uintptr_t> offsets_;
954  Disassembler* disassembler_;
955};
956
957class ImageDumper {
958 public:
959  explicit ImageDumper(std::ostream* os, gc::space::ImageSpace& image_space,
960                       const ImageHeader& image_header, OatDumperOptions* oat_dumper_options)
961      : os_(os),
962        image_space_(image_space),
963        image_header_(image_header),
964        oat_dumper_options_(oat_dumper_options) {}
965
966  bool Dump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
967    std::ostream& os = *os_;
968    os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
969
970    os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
971
972    os << "IMAGE BITMAP OFFSET: " << reinterpret_cast<void*>(image_header_.GetImageBitmapOffset())
973       << " SIZE: " << reinterpret_cast<void*>(image_header_.GetImageBitmapSize()) << "\n\n";
974
975    os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
976
977    os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
978
979    os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
980
981    os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
982
983    os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
984
985    os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
986
987    os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
988
989    {
990      os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
991      Indenter indent1_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
992      std::ostream indent1_os(&indent1_filter);
993      CHECK_EQ(arraysize(image_roots_descriptions_), size_t(ImageHeader::kImageRootsMax));
994      for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
995        ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
996        const char* image_root_description = image_roots_descriptions_[i];
997        mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
998        indent1_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
999        if (image_root_object->IsObjectArray()) {
1000          Indenter indent2_filter(indent1_os.rdbuf(), kIndentChar, kIndentBy1Count);
1001          std::ostream indent2_os(&indent2_filter);
1002          mirror::ObjectArray<mirror::Object>* image_root_object_array
1003              = image_root_object->AsObjectArray<mirror::Object>();
1004          for (int i = 0; i < image_root_object_array->GetLength(); i++) {
1005            mirror::Object* value = image_root_object_array->Get(i);
1006            size_t run = 0;
1007            for (int32_t j = i + 1; j < image_root_object_array->GetLength(); j++) {
1008              if (value == image_root_object_array->Get(j)) {
1009                run++;
1010              } else {
1011                break;
1012              }
1013            }
1014            if (run == 0) {
1015              indent2_os << StringPrintf("%d: ", i);
1016            } else {
1017              indent2_os << StringPrintf("%d to %zd: ", i, i + run);
1018              i = i + run;
1019            }
1020            if (value != nullptr) {
1021              PrettyObjectValue(indent2_os, value->GetClass(), value);
1022            } else {
1023              indent2_os << i << ": null\n";
1024            }
1025          }
1026        }
1027      }
1028    }
1029    os << "\n";
1030
1031    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1032    std::string image_filename = image_space_.GetImageFilename();
1033    std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
1034    os << "OAT LOCATION: " << oat_location;
1035    os << "\n";
1036    std::string error_msg;
1037    const OatFile* oat_file = class_linker->FindOpenedOatFileFromOatLocation(oat_location);
1038    if (oat_file == nullptr) {
1039      oat_file = OatFile::Open(oat_location, oat_location, nullptr, nullptr, false, &error_msg);
1040      if (oat_file == nullptr) {
1041        os << "NOT FOUND: " << error_msg << "\n";
1042        return false;
1043      }
1044    }
1045    os << "\n";
1046
1047    stats_.oat_file_bytes = oat_file->Size();
1048
1049    oat_dumper_.reset(new OatDumper(*oat_file, oat_dumper_options_.release()));
1050
1051    for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1052      CHECK(oat_dex_file != nullptr);
1053      stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
1054                                                         oat_dex_file->FileSize()));
1055    }
1056
1057    os << "OBJECTS:\n" << std::flush;
1058
1059    // Loop through all the image spaces and dump their objects.
1060    gc::Heap* heap = Runtime::Current()->GetHeap();
1061    const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
1062    Thread* self = Thread::Current();
1063    {
1064      {
1065        WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1066        heap->FlushAllocStack();
1067      }
1068      // Since FlushAllocStack() above resets the (active) allocation
1069      // stack. Need to revoke the thread-local allocation stacks that
1070      // point into it.
1071      {
1072        self->TransitionFromRunnableToSuspended(kNative);
1073        ThreadList* thread_list = Runtime::Current()->GetThreadList();
1074        thread_list->SuspendAll();
1075        heap->RevokeAllThreadLocalAllocationStacks(self);
1076        thread_list->ResumeAll();
1077        self->TransitionFromSuspendedToRunnable();
1078      }
1079    }
1080    {
1081      std::ostream* saved_os = os_;
1082      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1083      std::ostream indent_os(&indent_filter);
1084      os_ = &indent_os;
1085      ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1086      for (const auto& space : spaces) {
1087        if (space->IsImageSpace()) {
1088          gc::space::ImageSpace* image_space = space->AsImageSpace();
1089          image_space->GetLiveBitmap()->Walk(ImageDumper::Callback, this);
1090          indent_os << "\n";
1091        }
1092      }
1093      // Dump the large objects separately.
1094      heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(ImageDumper::Callback, this);
1095      indent_os << "\n";
1096      os_ = saved_os;
1097    }
1098    os << "STATS:\n" << std::flush;
1099    std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
1100    if (file.get() == nullptr) {
1101      LOG(WARNING) << "Failed to find image in " << image_filename;
1102    }
1103    if (file.get() != nullptr) {
1104      stats_.file_bytes = file->GetLength();
1105    }
1106    size_t header_bytes = sizeof(ImageHeader);
1107    stats_.header_bytes = header_bytes;
1108    size_t alignment_bytes = RoundUp(header_bytes, kObjectAlignment) - header_bytes;
1109    stats_.alignment_bytes += alignment_bytes;
1110    stats_.alignment_bytes += image_header_.GetImageBitmapOffset() - image_header_.GetImageSize();
1111    stats_.bitmap_bytes += image_header_.GetImageBitmapSize();
1112    stats_.Dump(os);
1113    os << "\n";
1114
1115    os << std::flush;
1116
1117    return oat_dumper_->Dump(os);
1118  }
1119
1120 private:
1121  static void PrettyObjectValue(std::ostream& os, mirror::Class* type, mirror::Object* value)
1122      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1123    CHECK(type != nullptr);
1124    if (value == nullptr) {
1125      os << StringPrintf("null   %s\n", PrettyDescriptor(type).c_str());
1126    } else if (type->IsStringClass()) {
1127      mirror::String* string = value->AsString();
1128      os << StringPrintf("%p   String: %s\n", string,
1129                         PrintableString(string->ToModifiedUtf8().c_str()).c_str());
1130    } else if (type->IsClassClass()) {
1131      mirror::Class* klass = value->AsClass();
1132      os << StringPrintf("%p   Class: %s\n", klass, PrettyDescriptor(klass).c_str());
1133    } else if (type->IsArtFieldClass()) {
1134      mirror::ArtField* field = value->AsArtField();
1135      os << StringPrintf("%p   Field: %s\n", field, PrettyField(field).c_str());
1136    } else if (type->IsArtMethodClass()) {
1137      mirror::ArtMethod* method = value->AsArtMethod();
1138      os << StringPrintf("%p   Method: %s\n", method, PrettyMethod(method).c_str());
1139    } else {
1140      os << StringPrintf("%p   %s\n", value, PrettyDescriptor(type).c_str());
1141    }
1142  }
1143
1144  static void PrintField(std::ostream& os, mirror::ArtField* field, mirror::Object* obj)
1145      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1146    const char* descriptor = field->GetTypeDescriptor();
1147    os << StringPrintf("%s: ", field->GetName());
1148    if (descriptor[0] != 'L' && descriptor[0] != '[') {
1149      StackHandleScope<1> hs(Thread::Current());
1150      FieldHelper fh(hs.NewHandle(field));
1151      mirror::Class* type = fh.GetType();
1152      if (type->IsPrimitiveLong()) {
1153        os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
1154      } else if (type->IsPrimitiveDouble()) {
1155        os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
1156      } else if (type->IsPrimitiveFloat()) {
1157        os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
1158      } else {
1159        DCHECK(type->IsPrimitive());
1160        os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
1161      }
1162    } else {
1163      // Get the value, don't compute the type unless it is non-null as we don't want
1164      // to cause class loading.
1165      mirror::Object* value = field->GetObj(obj);
1166      if (value == nullptr) {
1167        os << StringPrintf("null   %s\n", PrettyDescriptor(descriptor).c_str());
1168      } else {
1169        // Grab the field type without causing resolution.
1170        StackHandleScope<1> hs(Thread::Current());
1171        FieldHelper fh(hs.NewHandle(field));
1172        mirror::Class* field_type = fh.GetType(false);
1173        if (field_type != nullptr) {
1174          PrettyObjectValue(os, field_type, value);
1175        } else {
1176          os << StringPrintf("%p   %s\n", value, PrettyDescriptor(descriptor).c_str());
1177        }
1178      }
1179    }
1180  }
1181
1182  static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
1183      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1184    mirror::Class* super = klass->GetSuperClass();
1185    if (super != nullptr) {
1186      DumpFields(os, obj, super);
1187    }
1188    mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
1189    if (fields != nullptr) {
1190      for (int32_t i = 0; i < fields->GetLength(); i++) {
1191        mirror::ArtField* field = fields->Get(i);
1192        PrintField(os, field, obj);
1193      }
1194    }
1195  }
1196
1197  bool InDumpSpace(const mirror::Object* object) {
1198    return image_space_.Contains(object);
1199  }
1200
1201  const void* GetQuickOatCodeBegin(mirror::ArtMethod* m)
1202      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1203    const void* quick_code = m->GetEntryPointFromQuickCompiledCode();
1204    if (quick_code == Runtime::Current()->GetClassLinker()->GetQuickResolutionTrampoline()) {
1205      quick_code = oat_dumper_->GetQuickOatCode(m);
1206    }
1207    if (oat_dumper_->GetInstructionSet() == kThumb2) {
1208      quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
1209    }
1210    return quick_code;
1211  }
1212
1213  uint32_t GetQuickOatCodeSize(mirror::ArtMethod* m)
1214      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1215    const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
1216    if (oat_code_begin == nullptr) {
1217      return 0;
1218    }
1219    return oat_code_begin[-1];
1220  }
1221
1222  const void* GetQuickOatCodeEnd(mirror::ArtMethod* m)
1223      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1224    const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
1225    if (oat_code_begin == nullptr) {
1226      return nullptr;
1227    }
1228    return oat_code_begin + GetQuickOatCodeSize(m);
1229  }
1230
1231  static void Callback(mirror::Object* obj, void* arg)
1232      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1233    DCHECK(obj != nullptr);
1234    DCHECK(arg != nullptr);
1235    ImageDumper* state = reinterpret_cast<ImageDumper*>(arg);
1236    if (!state->InDumpSpace(obj)) {
1237      return;
1238    }
1239
1240    size_t object_bytes = obj->SizeOf();
1241    size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
1242    state->stats_.object_bytes += object_bytes;
1243    state->stats_.alignment_bytes += alignment_bytes;
1244
1245    std::ostream& os = *state->os_;
1246    mirror::Class* obj_class = obj->GetClass();
1247    if (obj_class->IsArrayClass()) {
1248      os << StringPrintf("%p: %s length:%d\n", obj, PrettyDescriptor(obj_class).c_str(),
1249                         obj->AsArray()->GetLength());
1250    } else if (obj->IsClass()) {
1251      mirror::Class* klass = obj->AsClass();
1252      os << StringPrintf("%p: java.lang.Class \"%s\" (", obj, PrettyDescriptor(klass).c_str())
1253         << klass->GetStatus() << ")\n";
1254    } else if (obj->IsArtField()) {
1255      os << StringPrintf("%p: java.lang.reflect.ArtField %s\n", obj,
1256                         PrettyField(obj->AsArtField()).c_str());
1257    } else if (obj->IsArtMethod()) {
1258      os << StringPrintf("%p: java.lang.reflect.ArtMethod %s\n", obj,
1259                         PrettyMethod(obj->AsArtMethod()).c_str());
1260    } else if (obj_class->IsStringClass()) {
1261      os << StringPrintf("%p: java.lang.String %s\n", obj,
1262                         PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
1263    } else {
1264      os << StringPrintf("%p: %s\n", obj, PrettyDescriptor(obj_class).c_str());
1265    }
1266    Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1267    std::ostream indent_os(&indent_filter);
1268    DumpFields(indent_os, obj, obj_class);
1269    if (obj->IsObjectArray()) {
1270      mirror::ObjectArray<mirror::Object>* obj_array = obj->AsObjectArray<mirror::Object>();
1271      int32_t length = obj_array->GetLength();
1272      for (int32_t i = 0; i < length; i++) {
1273        mirror::Object* value = obj_array->Get(i);
1274        size_t run = 0;
1275        for (int32_t j = i + 1; j < length; j++) {
1276          if (value == obj_array->Get(j)) {
1277            run++;
1278          } else {
1279            break;
1280          }
1281        }
1282        if (run == 0) {
1283          indent_os << StringPrintf("%d: ", i);
1284        } else {
1285          indent_os << StringPrintf("%d to %zd: ", i, i + run);
1286          i = i + run;
1287        }
1288        mirror::Class* value_class =
1289            (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
1290        PrettyObjectValue(indent_os, value_class, value);
1291      }
1292    } else if (obj->IsClass()) {
1293      mirror::ObjectArray<mirror::ArtField>* sfields = obj->AsClass()->GetSFields();
1294      if (sfields != nullptr) {
1295        indent_os << "STATICS:\n";
1296        Indenter indent2_filter(indent_os.rdbuf(), kIndentChar, kIndentBy1Count);
1297        std::ostream indent2_os(&indent2_filter);
1298        for (int32_t i = 0; i < sfields->GetLength(); i++) {
1299          mirror::ArtField* field = sfields->Get(i);
1300          PrintField(indent2_os, field, field->GetDeclaringClass());
1301        }
1302      }
1303    } else if (obj->IsArtMethod()) {
1304      mirror::ArtMethod* method = obj->AsArtMethod();
1305      if (method->IsNative()) {
1306        // TODO: portable dumping.
1307        DCHECK(method->GetNativeGcMap() == nullptr) << PrettyMethod(method);
1308        DCHECK(method->GetMappingTable() == nullptr) << PrettyMethod(method);
1309        bool first_occurrence;
1310        const void* quick_oat_code = state->GetQuickOatCodeBegin(method);
1311        uint32_t quick_oat_code_size = state->GetQuickOatCodeSize(method);
1312        state->ComputeOatSize(quick_oat_code, &first_occurrence);
1313        if (first_occurrence) {
1314          state->stats_.native_to_managed_code_bytes += quick_oat_code_size;
1315        }
1316        if (quick_oat_code != method->GetEntryPointFromQuickCompiledCode()) {
1317          indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code);
1318        }
1319      } else if (method->IsAbstract() || method->IsCalleeSaveMethod() ||
1320          method->IsResolutionMethod() || method->IsImtConflictMethod() ||
1321          method->IsImtUnimplementedMethod() || method->IsClassInitializer()) {
1322        DCHECK(method->GetNativeGcMap() == nullptr) << PrettyMethod(method);
1323        DCHECK(method->GetMappingTable() == nullptr) << PrettyMethod(method);
1324      } else {
1325        const DexFile::CodeItem* code_item = method->GetCodeItem();
1326        size_t dex_instruction_bytes = code_item->insns_size_in_code_units_ * 2;
1327        state->stats_.dex_instruction_bytes += dex_instruction_bytes;
1328
1329        bool first_occurrence;
1330        size_t gc_map_bytes = state->ComputeOatSize(method->GetNativeGcMap(), &first_occurrence);
1331        if (first_occurrence) {
1332          state->stats_.gc_map_bytes += gc_map_bytes;
1333        }
1334
1335        size_t pc_mapping_table_bytes =
1336            state->ComputeOatSize(method->GetMappingTable(), &first_occurrence);
1337        if (first_occurrence) {
1338          state->stats_.pc_mapping_table_bytes += pc_mapping_table_bytes;
1339        }
1340
1341        size_t vmap_table_bytes =
1342            state->ComputeOatSize(method->GetVmapTable(), &first_occurrence);
1343        if (first_occurrence) {
1344          state->stats_.vmap_table_bytes += vmap_table_bytes;
1345        }
1346
1347        // TODO: portable dumping.
1348        const void* quick_oat_code_begin = state->GetQuickOatCodeBegin(method);
1349        const void* quick_oat_code_end = state->GetQuickOatCodeEnd(method);
1350        uint32_t quick_oat_code_size = state->GetQuickOatCodeSize(method);
1351        state->ComputeOatSize(quick_oat_code_begin, &first_occurrence);
1352        if (first_occurrence) {
1353          state->stats_.managed_code_bytes += quick_oat_code_size;
1354          if (method->IsConstructor()) {
1355            if (method->IsStatic()) {
1356              state->stats_.class_initializer_code_bytes += quick_oat_code_size;
1357            } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
1358              state->stats_.large_initializer_code_bytes += quick_oat_code_size;
1359            }
1360          } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
1361            state->stats_.large_method_code_bytes += quick_oat_code_size;
1362          }
1363        }
1364        state->stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
1365
1366        indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
1367        indent_os << StringPrintf("SIZE: Dex Instructions=%zd GC=%zd Mapping=%zd\n",
1368                                  dex_instruction_bytes, gc_map_bytes, pc_mapping_table_bytes);
1369
1370        size_t total_size = dex_instruction_bytes + gc_map_bytes + pc_mapping_table_bytes +
1371            vmap_table_bytes + quick_oat_code_size + object_bytes;
1372
1373        double expansion =
1374            static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
1375        state->stats_.ComputeOutliers(total_size, expansion, method);
1376      }
1377    }
1378    std::string temp;
1379    state->stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
1380  }
1381
1382  std::set<const void*> already_seen_;
1383  // Compute the size of the given data within the oat file and whether this is the first time
1384  // this data has been requested
1385  size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
1386    if (already_seen_.count(oat_data) == 0) {
1387      *first_occurrence = true;
1388      already_seen_.insert(oat_data);
1389    } else {
1390      *first_occurrence = false;
1391    }
1392    return oat_dumper_->ComputeSize(oat_data);
1393  }
1394
1395 public:
1396  struct Stats {
1397    size_t oat_file_bytes;
1398    size_t file_bytes;
1399
1400    size_t header_bytes;
1401    size_t object_bytes;
1402    size_t bitmap_bytes;
1403    size_t alignment_bytes;
1404
1405    size_t managed_code_bytes;
1406    size_t managed_code_bytes_ignoring_deduplication;
1407    size_t managed_to_native_code_bytes;
1408    size_t native_to_managed_code_bytes;
1409    size_t class_initializer_code_bytes;
1410    size_t large_initializer_code_bytes;
1411    size_t large_method_code_bytes;
1412
1413    size_t gc_map_bytes;
1414    size_t pc_mapping_table_bytes;
1415    size_t vmap_table_bytes;
1416
1417    size_t dex_instruction_bytes;
1418
1419    std::vector<mirror::ArtMethod*> method_outlier;
1420    std::vector<size_t> method_outlier_size;
1421    std::vector<double> method_outlier_expansion;
1422    std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
1423
1424    explicit Stats()
1425        : oat_file_bytes(0),
1426          file_bytes(0),
1427          header_bytes(0),
1428          object_bytes(0),
1429          bitmap_bytes(0),
1430          alignment_bytes(0),
1431          managed_code_bytes(0),
1432          managed_code_bytes_ignoring_deduplication(0),
1433          managed_to_native_code_bytes(0),
1434          native_to_managed_code_bytes(0),
1435          class_initializer_code_bytes(0),
1436          large_initializer_code_bytes(0),
1437          large_method_code_bytes(0),
1438          gc_map_bytes(0),
1439          pc_mapping_table_bytes(0),
1440          vmap_table_bytes(0),
1441          dex_instruction_bytes(0) {}
1442
1443    struct SizeAndCount {
1444      SizeAndCount(size_t bytes, size_t count) : bytes(bytes), count(count) {}
1445      size_t bytes;
1446      size_t count;
1447    };
1448    typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
1449    SizeAndCountTable sizes_and_counts;
1450
1451    void Update(const char* descriptor, size_t object_bytes) {
1452      SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
1453      if (it != sizes_and_counts.end()) {
1454        it->second.bytes += object_bytes;
1455        it->second.count += 1;
1456      } else {
1457        sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes, 1));
1458      }
1459    }
1460
1461    double PercentOfOatBytes(size_t size) {
1462      return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
1463    }
1464
1465    double PercentOfFileBytes(size_t size) {
1466      return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
1467    }
1468
1469    double PercentOfObjectBytes(size_t size) {
1470      return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
1471    }
1472
1473    void ComputeOutliers(size_t total_size, double expansion, mirror::ArtMethod* method) {
1474      method_outlier_size.push_back(total_size);
1475      method_outlier_expansion.push_back(expansion);
1476      method_outlier.push_back(method);
1477    }
1478
1479    void DumpOutliers(std::ostream& os)
1480        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1481      size_t sum_of_sizes = 0;
1482      size_t sum_of_sizes_squared = 0;
1483      size_t sum_of_expansion = 0;
1484      size_t sum_of_expansion_squared = 0;
1485      size_t n = method_outlier_size.size();
1486      for (size_t i = 0; i < n; i++) {
1487        size_t cur_size = method_outlier_size[i];
1488        sum_of_sizes += cur_size;
1489        sum_of_sizes_squared += cur_size * cur_size;
1490        double cur_expansion = method_outlier_expansion[i];
1491        sum_of_expansion += cur_expansion;
1492        sum_of_expansion_squared += cur_expansion * cur_expansion;
1493      }
1494      size_t size_mean = sum_of_sizes / n;
1495      size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
1496      double expansion_mean = sum_of_expansion / n;
1497      double expansion_variance =
1498          (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
1499
1500      // Dump methods whose size is a certain number of standard deviations from the mean
1501      size_t dumped_values = 0;
1502      size_t skipped_values = 0;
1503      for (size_t i = 100; i > 0; i--) {  // i is the current number of standard deviations
1504        size_t cur_size_variance = i * i * size_variance;
1505        bool first = true;
1506        for (size_t j = 0; j < n; j++) {
1507          size_t cur_size = method_outlier_size[j];
1508          if (cur_size > size_mean) {
1509            size_t cur_var = cur_size - size_mean;
1510            cur_var = cur_var * cur_var;
1511            if (cur_var > cur_size_variance) {
1512              if (dumped_values > 20) {
1513                if (i == 1) {
1514                  skipped_values++;
1515                } else {
1516                  i = 2;  // jump to counting for 1 standard deviation
1517                  break;
1518                }
1519              } else {
1520                if (first) {
1521                  os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
1522                  first = false;
1523                }
1524                os << PrettyMethod(method_outlier[j]) << " requires storage of "
1525                    << PrettySize(cur_size) << "\n";
1526                method_outlier_size[j] = 0;  // don't consider this method again
1527                dumped_values++;
1528              }
1529            }
1530          }
1531        }
1532      }
1533      if (skipped_values > 0) {
1534        os << "... skipped " << skipped_values
1535           << " methods with size > 1 standard deviation from the norm\n";
1536      }
1537      os << std::flush;
1538
1539      // Dump methods whose expansion is a certain number of standard deviations from the mean
1540      dumped_values = 0;
1541      skipped_values = 0;
1542      for (size_t i = 10; i > 0; i--) {  // i is the current number of standard deviations
1543        double cur_expansion_variance = i * i * expansion_variance;
1544        bool first = true;
1545        for (size_t j = 0; j < n; j++) {
1546          double cur_expansion = method_outlier_expansion[j];
1547          if (cur_expansion > expansion_mean) {
1548            size_t cur_var = cur_expansion - expansion_mean;
1549            cur_var = cur_var * cur_var;
1550            if (cur_var > cur_expansion_variance) {
1551              if (dumped_values > 20) {
1552                if (i == 1) {
1553                  skipped_values++;
1554                } else {
1555                  i = 2;  // jump to counting for 1 standard deviation
1556                  break;
1557                }
1558              } else {
1559                if (first) {
1560                  os << "\nLarge expansion methods (size > " << i
1561                      << " standard deviations the norm):\n";
1562                  first = false;
1563                }
1564                os << PrettyMethod(method_outlier[j]) << " expanded code by "
1565                   << cur_expansion << "\n";
1566                method_outlier_expansion[j] = 0.0;  // don't consider this method again
1567                dumped_values++;
1568              }
1569            }
1570          }
1571        }
1572      }
1573      if (skipped_values > 0) {
1574        os << "... skipped " << skipped_values
1575           << " methods with expansion > 1 standard deviation from the norm\n";
1576      }
1577      os << "\n" << std::flush;
1578    }
1579
1580    void Dump(std::ostream& os) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1581      {
1582        os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
1583           << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
1584        Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1585        std::ostream indent_os(&indent_filter);
1586        indent_os << StringPrintf("header_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
1587                                  "object_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
1588                                  "bitmap_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
1589                                  "alignment_bytes =  %8zd (%2.0f%% of art file bytes)\n\n",
1590                                  header_bytes, PercentOfFileBytes(header_bytes),
1591                                  object_bytes, PercentOfFileBytes(object_bytes),
1592                                  bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
1593                                  alignment_bytes, PercentOfFileBytes(alignment_bytes))
1594            << std::flush;
1595        CHECK_EQ(file_bytes, bitmap_bytes + header_bytes + object_bytes + alignment_bytes);
1596      }
1597
1598      os << "object_bytes breakdown:\n";
1599      size_t object_bytes_total = 0;
1600      for (const auto& sizes_and_count : sizes_and_counts) {
1601        const std::string& descriptor(sizes_and_count.first);
1602        double average = static_cast<double>(sizes_and_count.second.bytes) /
1603            static_cast<double>(sizes_and_count.second.count);
1604        double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
1605        os << StringPrintf("%32s %8zd bytes %6zd instances "
1606                           "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
1607                           descriptor.c_str(), sizes_and_count.second.bytes,
1608                           sizes_and_count.second.count, average, percent);
1609        object_bytes_total += sizes_and_count.second.bytes;
1610      }
1611      os << "\n" << std::flush;
1612      CHECK_EQ(object_bytes, object_bytes_total);
1613
1614      os << StringPrintf("oat_file_bytes               = %8zd\n"
1615                         "managed_code_bytes           = %8zd (%2.0f%% of oat file bytes)\n"
1616                         "managed_to_native_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
1617                         "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
1618                         "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
1619                         "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
1620                         "large_method_code_bytes      = %8zd (%2.0f%% of oat file bytes)\n\n",
1621                         oat_file_bytes,
1622                         managed_code_bytes,
1623                         PercentOfOatBytes(managed_code_bytes),
1624                         managed_to_native_code_bytes,
1625                         PercentOfOatBytes(managed_to_native_code_bytes),
1626                         native_to_managed_code_bytes,
1627                         PercentOfOatBytes(native_to_managed_code_bytes),
1628                         class_initializer_code_bytes,
1629                         PercentOfOatBytes(class_initializer_code_bytes),
1630                         large_initializer_code_bytes,
1631                         PercentOfOatBytes(large_initializer_code_bytes),
1632                         large_method_code_bytes,
1633                         PercentOfOatBytes(large_method_code_bytes))
1634            << "DexFile sizes:\n";
1635      for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
1636        os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
1637                           oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
1638                           PercentOfOatBytes(oat_dex_file_size.second));
1639      }
1640
1641      os << "\n" << StringPrintf("gc_map_bytes           = %7zd (%2.0f%% of oat file bytes)\n"
1642                                 "pc_mapping_table_bytes = %7zd (%2.0f%% of oat file bytes)\n"
1643                                 "vmap_table_bytes       = %7zd (%2.0f%% of oat file bytes)\n\n",
1644                                 gc_map_bytes, PercentOfOatBytes(gc_map_bytes),
1645                                 pc_mapping_table_bytes, PercentOfOatBytes(pc_mapping_table_bytes),
1646                                 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
1647         << std::flush;
1648
1649      os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
1650         << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
1651                         static_cast<double>(managed_code_bytes) /
1652                             static_cast<double>(dex_instruction_bytes),
1653                         static_cast<double>(managed_code_bytes_ignoring_deduplication) /
1654                             static_cast<double>(dex_instruction_bytes))
1655         << std::flush;
1656
1657      DumpOutliers(os);
1658    }
1659  } stats_;
1660
1661 private:
1662  enum {
1663    // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
1664    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
1665    kLargeConstructorDexBytes = 4000,
1666    // Number of bytes for a method to be considered large. Based on the 4000 basic block
1667    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
1668    kLargeMethodDexBytes = 16000
1669  };
1670  std::ostream* os_;
1671  gc::space::ImageSpace& image_space_;
1672  const ImageHeader& image_header_;
1673  std::unique_ptr<OatDumper> oat_dumper_;
1674  std::unique_ptr<OatDumperOptions> oat_dumper_options_;
1675
1676  DISALLOW_COPY_AND_ASSIGN(ImageDumper);
1677};
1678
1679static int oatdump(int argc, char** argv) {
1680  InitLogging(argv);
1681
1682  // Skip over argv[0].
1683  argv++;
1684  argc--;
1685
1686  if (argc == 0) {
1687    fprintf(stderr, "No arguments specified\n");
1688    usage();
1689  }
1690
1691  const char* oat_filename = nullptr;
1692  const char* image_location = nullptr;
1693  const char* boot_image_location = nullptr;
1694  InstructionSet instruction_set = kRuntimeISA;
1695  std::string elf_filename_prefix;
1696  std::ostream* os = &std::cout;
1697  std::unique_ptr<std::ofstream> out;
1698  bool dump_raw_mapping_table = false;
1699  bool dump_raw_gc_map = false;
1700  bool dump_vmap = true;
1701  bool disassemble_code = true;
1702
1703  for (int i = 0; i < argc; i++) {
1704    const StringPiece option(argv[i]);
1705    if (option.starts_with("--oat-file=")) {
1706      oat_filename = option.substr(strlen("--oat-file=")).data();
1707    } else if (option.starts_with("--image=")) {
1708      image_location = option.substr(strlen("--image=")).data();
1709    } else if (option.starts_with("--boot-image=")) {
1710      boot_image_location = option.substr(strlen("--boot-image=")).data();
1711    } else if (option.starts_with("--instruction-set=")) {
1712      StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
1713      if (instruction_set_str == "arm") {
1714        instruction_set = kThumb2;
1715      } else if (instruction_set_str == "arm64") {
1716        instruction_set = kArm64;
1717      } else if (instruction_set_str == "mips") {
1718        instruction_set = kMips;
1719      } else if (instruction_set_str == "x86") {
1720        instruction_set = kX86;
1721      } else if (instruction_set_str == "x86_64") {
1722        instruction_set = kX86_64;
1723      }
1724    } else if (option =="--dump:raw_mapping_table") {
1725      dump_raw_mapping_table = true;
1726    } else if (option == "--dump:raw_gc_map") {
1727      dump_raw_gc_map = true;
1728    } else if (option == "--no-dump:vmap") {
1729      dump_vmap = false;
1730    } else if (option == "--no-disassemble") {
1731      disassemble_code = false;
1732    } else if (option.starts_with("--output=")) {
1733      const char* filename = option.substr(strlen("--output=")).data();
1734      out.reset(new std::ofstream(filename));
1735      if (!out->good()) {
1736        fprintf(stderr, "Failed to open output filename %s\n", filename);
1737        usage();
1738      }
1739      os = out.get();
1740    } else {
1741      fprintf(stderr, "Unknown argument %s\n", option.data());
1742      usage();
1743    }
1744  }
1745
1746  if (image_location == nullptr && oat_filename == nullptr) {
1747    fprintf(stderr, "Either --image or --oat must be specified\n");
1748    return EXIT_FAILURE;
1749  }
1750
1751  if (image_location != nullptr && oat_filename != nullptr) {
1752    fprintf(stderr, "Either --image or --oat must be specified but not both\n");
1753    return EXIT_FAILURE;
1754  }
1755
1756  // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
1757  bool absolute_addresses = (oat_filename == nullptr);
1758  std::unique_ptr<OatDumperOptions> oat_dumper_options(new OatDumperOptions(dump_raw_mapping_table,
1759                                                                            dump_raw_gc_map,
1760                                                                            dump_vmap,
1761                                                                            disassemble_code,
1762                                                                            absolute_addresses));
1763  MemMap::Init();
1764  if (oat_filename != nullptr) {
1765    std::string error_msg;
1766    OatFile* oat_file =
1767        OatFile::Open(oat_filename, oat_filename, nullptr, nullptr, false, &error_msg);
1768    if (oat_file == nullptr) {
1769      fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
1770      return EXIT_FAILURE;
1771    }
1772    OatDumper oat_dumper(*oat_file, oat_dumper_options.release());
1773    bool success = oat_dumper.Dump(*os);
1774    return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
1775  }
1776
1777  RuntimeOptions options;
1778  std::string image_option;
1779  std::string oat_option;
1780  std::string boot_image_option;
1781  std::string boot_oat_option;
1782
1783  // We are more like a compiler than a run-time. We don't want to execute code.
1784  NoopCompilerCallbacks callbacks;
1785  options.push_back(std::make_pair("compilercallbacks", &callbacks));
1786
1787  if (boot_image_location != nullptr) {
1788    boot_image_option += "-Ximage:";
1789    boot_image_option += boot_image_location;
1790    options.push_back(std::make_pair(boot_image_option.c_str(), nullptr));
1791  }
1792  if (image_location != nullptr) {
1793    image_option += "-Ximage:";
1794    image_option += image_location;
1795    options.push_back(std::make_pair(image_option.c_str(), nullptr));
1796  }
1797  options.push_back(
1798      std::make_pair("imageinstructionset",
1799                     reinterpret_cast<const void*>(GetInstructionSetString(instruction_set))));
1800
1801  if (!Runtime::Create(options, false)) {
1802    fprintf(stderr, "Failed to create runtime\n");
1803    return EXIT_FAILURE;
1804  }
1805  std::unique_ptr<Runtime> runtime(Runtime::Current());
1806  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
1807  // give it away now and then switch to a more manageable ScopedObjectAccess.
1808  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
1809  ScopedObjectAccess soa(Thread::Current());
1810  gc::Heap* heap = Runtime::Current()->GetHeap();
1811  gc::space::ImageSpace* image_space = heap->GetImageSpace();
1812  CHECK(image_space != nullptr);
1813  const ImageHeader& image_header = image_space->GetImageHeader();
1814  if (!image_header.IsValid()) {
1815    fprintf(stderr, "Invalid image header %s\n", image_location);
1816    return EXIT_FAILURE;
1817  }
1818  ImageDumper image_dumper(os, *image_space, image_header, oat_dumper_options.release());
1819  bool success = image_dumper.Dump();
1820  return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
1821}
1822
1823}  // namespace art
1824
1825int main(int argc, char** argv) {
1826  return art::oatdump(argc, argv);
1827}
1828