oatdump.cc revision 5d8112029d0e085c5a0099257daa4c7e29c12310
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 <map>
23#include <set>
24#include <string>
25#include <unordered_map>
26#include <vector>
27
28#include "arch/instruction_set_features.h"
29#include "art_field-inl.h"
30#include "art_method-inl.h"
31#include "base/stl_util.h"
32#include "base/unix_file/fd_file.h"
33#include "class_linker.h"
34#include "class_linker-inl.h"
35#include "dex_file-inl.h"
36#include "dex_instruction.h"
37#include "disassembler.h"
38#include "elf_builder.h"
39#include "gc_map.h"
40#include "gc/space/image_space.h"
41#include "gc/space/large_object_space.h"
42#include "gc/space/space-inl.h"
43#include "image-inl.h"
44#include "indenter.h"
45#include "linker/buffered_output_stream.h"
46#include "linker/file_output_stream.h"
47#include "mapping_table.h"
48#include "mirror/array-inl.h"
49#include "mirror/class-inl.h"
50#include "mirror/dex_cache-inl.h"
51#include "mirror/object-inl.h"
52#include "mirror/object_array-inl.h"
53#include "oat.h"
54#include "oat_file-inl.h"
55#include "oat_file_manager.h"
56#include "os.h"
57#include "safe_map.h"
58#include "scoped_thread_state_change.h"
59#include "stack_map.h"
60#include "ScopedLocalRef.h"
61#include "thread_list.h"
62#include "verifier/dex_gc_map.h"
63#include "verifier/method_verifier.h"
64#include "vmap_table.h"
65#include "well_known_classes.h"
66
67#include <sys/stat.h>
68#include "cmdline.h"
69
70namespace art {
71
72const char* image_methods_descriptions_[] = {
73  "kResolutionMethod",
74  "kImtConflictMethod",
75  "kImtUnimplementedMethod",
76  "kCalleeSaveMethod",
77  "kRefsOnlySaveMethod",
78  "kRefsAndArgsSaveMethod",
79};
80
81const char* image_roots_descriptions_[] = {
82  "kDexCaches",
83  "kClassRoots",
84};
85
86// Map is so that we don't allocate multiple dex files for the same OatDexFile.
87static std::map<const OatFile::OatDexFile*,
88                std::unique_ptr<const DexFile>> opened_dex_files;
89
90const DexFile* OpenDexFile(const OatFile::OatDexFile* oat_dex_file, std::string* error_msg) {
91  DCHECK(oat_dex_file != nullptr);
92  auto it = opened_dex_files.find(oat_dex_file);
93  if (it != opened_dex_files.end()) {
94    return it->second.get();
95  }
96  const DexFile* ret = oat_dex_file->OpenDexFile(error_msg).release();
97  opened_dex_files.emplace(oat_dex_file, std::unique_ptr<const DexFile>(ret));
98  return ret;
99}
100
101class OatSymbolizer FINAL {
102 public:
103  OatSymbolizer(const OatFile* oat_file, const std::string& output_name) :
104      oat_file_(oat_file), builder_(nullptr),
105      output_name_(output_name.empty() ? "symbolized.oat" : output_name) {
106  }
107
108  typedef void (OatSymbolizer::*Callback)(const DexFile::ClassDef&,
109                                          uint32_t,
110                                          const OatFile::OatMethod&,
111                                          const DexFile&,
112                                          uint32_t,
113                                          const DexFile::CodeItem*,
114                                          uint32_t);
115
116  bool Symbolize() {
117    const InstructionSet isa = oat_file_->GetOatHeader().GetInstructionSet();
118    const InstructionSetFeatures* features = InstructionSetFeatures::FromBitmap(
119        isa, oat_file_->GetOatHeader().GetInstructionSetFeaturesBitmap());
120
121    File* elf_file = OS::CreateEmptyFile(output_name_.c_str());
122    std::unique_ptr<BufferedOutputStream> output_stream(
123        MakeUnique<BufferedOutputStream>(MakeUnique<FileOutputStream>(elf_file)));
124    builder_.reset(new ElfBuilder<ElfTypes32>(isa, features, output_stream.get()));
125
126    builder_->Start();
127
128    auto* rodata = builder_->GetRoData();
129    auto* text = builder_->GetText();
130    auto* bss = builder_->GetBss();
131    auto* strtab = builder_->GetStrTab();
132    auto* symtab = builder_->GetSymTab();
133
134    rodata->Start();
135    const uint8_t* rodata_begin = oat_file_->Begin();
136    const size_t rodata_size = oat_file_->GetOatHeader().GetExecutableOffset();
137    rodata->WriteFully(rodata_begin, rodata_size);
138    rodata->End();
139
140    text->Start();
141    const uint8_t* text_begin = oat_file_->Begin() + rodata_size;
142    const size_t text_size = oat_file_->End() - text_begin;
143    text->WriteFully(text_begin, text_size);
144    text->End();
145
146    if (oat_file_->BssSize() != 0) {
147      bss->WriteNoBitsSection(oat_file_->BssSize());
148    }
149
150    builder_->PrepareDynamicSection(
151        elf_file->GetPath(), rodata_size, text_size, oat_file_->BssSize());
152    builder_->WriteDynamicSection();
153
154    Walk(&art::OatSymbolizer::RegisterForDedup);
155
156    NormalizeState();
157
158    strtab->Start();
159    strtab->Write("");  // strtab should start with empty string.
160    AddTrampolineSymbols();
161    Walk(&art::OatSymbolizer::AddSymbol);
162    strtab->End();
163
164    symtab->Start();
165    symtab->Write();
166    symtab->End();
167
168    builder_->End();
169
170    return builder_->Good();
171  }
172
173  void AddTrampolineSymbol(const char* name, uint32_t code_offset) {
174    if (code_offset != 0) {
175      uint32_t name_offset = builder_->GetStrTab()->Write(name);
176      uint64_t symbol_value = code_offset - oat_file_->GetOatHeader().GetExecutableOffset();
177      // Specifying 0 as the symbol size means that the symbol lasts until the next symbol or until
178      // the end of the section in case of the last symbol.
179      builder_->GetSymTab()->Add(name_offset, builder_->GetText(), symbol_value,
180          /* is_relative */ true, /* size */ 0, STB_GLOBAL, STT_FUNC);
181    }
182  }
183
184  void AddTrampolineSymbols() {
185    const OatHeader& oat_header = oat_file_->GetOatHeader();
186    AddTrampolineSymbol("interpreterToInterpreterBridge",
187                        oat_header.GetInterpreterToInterpreterBridgeOffset());
188    AddTrampolineSymbol("interpreterToCompiledCodeBridge",
189                        oat_header.GetInterpreterToCompiledCodeBridgeOffset());
190    AddTrampolineSymbol("jniDlsymLookup",
191                        oat_header.GetJniDlsymLookupOffset());
192    AddTrampolineSymbol("quickGenericJniTrampoline",
193                        oat_header.GetQuickGenericJniTrampolineOffset());
194    AddTrampolineSymbol("quickImtConflictTrampoline",
195                        oat_header.GetQuickImtConflictTrampolineOffset());
196    AddTrampolineSymbol("quickResolutionTrampoline",
197                        oat_header.GetQuickResolutionTrampolineOffset());
198    AddTrampolineSymbol("quickToInterpreterBridge",
199                        oat_header.GetQuickToInterpreterBridgeOffset());
200  }
201
202  void Walk(Callback callback) {
203    std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
204    for (size_t i = 0; i < oat_dex_files.size(); i++) {
205      const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
206      CHECK(oat_dex_file != nullptr);
207      WalkOatDexFile(oat_dex_file, callback);
208    }
209  }
210
211  void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file, Callback callback) {
212    std::string error_msg;
213    const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
214    if (dex_file == nullptr) {
215      return;
216    }
217    for (size_t class_def_index = 0;
218        class_def_index < dex_file->NumClassDefs();
219        class_def_index++) {
220      const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
221      const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
222      OatClassType type = oat_class.GetType();
223      switch (type) {
224        case kOatClassAllCompiled:
225        case kOatClassSomeCompiled:
226          WalkOatClass(oat_class, *dex_file, class_def, callback);
227          break;
228
229        case kOatClassNoneCompiled:
230        case kOatClassMax:
231          // Ignore.
232          break;
233      }
234    }
235  }
236
237  void WalkOatClass(const OatFile::OatClass& oat_class, const DexFile& dex_file,
238                    const DexFile::ClassDef& class_def, Callback callback) {
239    const uint8_t* class_data = dex_file.GetClassData(class_def);
240    if (class_data == nullptr) {  // empty class such as a marker interface?
241      return;
242    }
243    // Note: even if this is an interface or a native class, we still have to walk it, as there
244    //       might be a static initializer.
245    ClassDataItemIterator it(dex_file, class_data);
246    SkipAllFields(&it);
247    uint32_t class_method_idx = 0;
248    while (it.HasNextDirectMethod()) {
249      const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_idx);
250      WalkOatMethod(class_def, class_method_idx, oat_method, dex_file, it.GetMemberIndex(),
251                    it.GetMethodCodeItem(), it.GetMethodAccessFlags(), callback);
252      class_method_idx++;
253      it.Next();
254    }
255    while (it.HasNextVirtualMethod()) {
256      const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_idx);
257      WalkOatMethod(class_def, class_method_idx, oat_method, dex_file, it.GetMemberIndex(),
258                    it.GetMethodCodeItem(), it.GetMethodAccessFlags(), callback);
259      class_method_idx++;
260      it.Next();
261    }
262    DCHECK(!it.HasNext());
263  }
264
265  void WalkOatMethod(const DexFile::ClassDef& class_def, uint32_t class_method_index,
266                     const OatFile::OatMethod& oat_method, const DexFile& dex_file,
267                     uint32_t dex_method_idx, const DexFile::CodeItem* code_item,
268                     uint32_t method_access_flags, Callback callback) {
269    if ((method_access_flags & kAccAbstract) != 0) {
270      // Abstract method, no code.
271      return;
272    }
273    if (oat_method.GetCodeOffset() == 0) {
274      // No code.
275      return;
276    }
277
278    (this->*callback)(class_def, class_method_index, oat_method, dex_file, dex_method_idx, code_item,
279                      method_access_flags);
280  }
281
282  void RegisterForDedup(const DexFile::ClassDef& class_def ATTRIBUTE_UNUSED,
283                        uint32_t class_method_index ATTRIBUTE_UNUSED,
284                        const OatFile::OatMethod& oat_method,
285                        const DexFile& dex_file ATTRIBUTE_UNUSED,
286                        uint32_t dex_method_idx ATTRIBUTE_UNUSED,
287                        const DexFile::CodeItem* code_item ATTRIBUTE_UNUSED,
288                        uint32_t method_access_flags ATTRIBUTE_UNUSED) {
289    state_[oat_method.GetCodeOffset()]++;
290  }
291
292  void NormalizeState() {
293    for (auto& x : state_) {
294      if (x.second == 1) {
295        state_[x.first] = 0;
296      }
297    }
298  }
299
300  enum class DedupState {  // private
301    kNotDeduplicated,
302    kDeduplicatedFirst,
303    kDeduplicatedOther
304  };
305  DedupState IsDuplicated(uint32_t offset) {
306    if (state_[offset] == 0) {
307      return DedupState::kNotDeduplicated;
308    }
309    if (state_[offset] == 1) {
310      return DedupState::kDeduplicatedOther;
311    }
312    state_[offset] = 1;
313    return DedupState::kDeduplicatedFirst;
314  }
315
316  void AddSymbol(const DexFile::ClassDef& class_def ATTRIBUTE_UNUSED,
317                 uint32_t class_method_index ATTRIBUTE_UNUSED,
318                 const OatFile::OatMethod& oat_method,
319                 const DexFile& dex_file,
320                 uint32_t dex_method_idx,
321                 const DexFile::CodeItem* code_item ATTRIBUTE_UNUSED,
322                 uint32_t method_access_flags ATTRIBUTE_UNUSED) {
323    DedupState dedup = IsDuplicated(oat_method.GetCodeOffset());
324    if (dedup != DedupState::kDeduplicatedOther) {
325      std::string pretty_name = PrettyMethod(dex_method_idx, dex_file, true);
326
327      if (dedup == DedupState::kDeduplicatedFirst) {
328        pretty_name = "[Dedup]" + pretty_name;
329      }
330
331      int name_offset = builder_->GetStrTab()->Write(pretty_name);
332      builder_->GetSymTab()->Add(name_offset, builder_->GetText(),
333          oat_method.GetCodeOffset() - oat_file_->GetOatHeader().GetExecutableOffset(),
334          true, oat_method.GetQuickCodeSize(), STB_GLOBAL, STT_FUNC);
335    }
336  }
337
338 private:
339  static void SkipAllFields(ClassDataItemIterator* it) {
340    while (it->HasNextStaticField()) {
341      it->Next();
342    }
343    while (it->HasNextInstanceField()) {
344      it->Next();
345    }
346  }
347
348  const OatFile* oat_file_;
349  std::unique_ptr<ElfBuilder<ElfTypes32> > builder_;
350  std::unordered_map<uint32_t, uint32_t> state_;
351  const std::string output_name_;
352};
353
354class OatDumperOptions {
355 public:
356  OatDumperOptions(bool dump_raw_mapping_table,
357                   bool dump_raw_gc_map,
358                   bool dump_vmap,
359                   bool dump_code_info_stack_maps,
360                   bool disassemble_code,
361                   bool absolute_addresses,
362                   const char* class_filter,
363                   const char* method_filter,
364                   bool list_classes,
365                   bool list_methods,
366                   bool dump_header_only,
367                   const char* export_dex_location,
368                   uint32_t addr2instr)
369    : dump_raw_mapping_table_(dump_raw_mapping_table),
370      dump_raw_gc_map_(dump_raw_gc_map),
371      dump_vmap_(dump_vmap),
372      dump_code_info_stack_maps_(dump_code_info_stack_maps),
373      disassemble_code_(disassemble_code),
374      absolute_addresses_(absolute_addresses),
375      class_filter_(class_filter),
376      method_filter_(method_filter),
377      list_classes_(list_classes),
378      list_methods_(list_methods),
379      dump_header_only_(dump_header_only),
380      export_dex_location_(export_dex_location),
381      addr2instr_(addr2instr),
382      class_loader_(nullptr) {}
383
384  const bool dump_raw_mapping_table_;
385  const bool dump_raw_gc_map_;
386  const bool dump_vmap_;
387  const bool dump_code_info_stack_maps_;
388  const bool disassemble_code_;
389  const bool absolute_addresses_;
390  const char* const class_filter_;
391  const char* const method_filter_;
392  const bool list_classes_;
393  const bool list_methods_;
394  const bool dump_header_only_;
395  const char* const export_dex_location_;
396  uint32_t addr2instr_;
397  Handle<mirror::ClassLoader>* class_loader_;
398};
399
400class OatDumper {
401 public:
402  OatDumper(const OatFile& oat_file, const OatDumperOptions& options)
403    : oat_file_(oat_file),
404      oat_dex_files_(oat_file.GetOatDexFiles()),
405      options_(options),
406      resolved_addr2instr_(0),
407      instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
408      disassembler_(Disassembler::Create(instruction_set_,
409                                         new DisassemblerOptions(options_.absolute_addresses_,
410                                                                 oat_file.Begin(),
411                                                                 true /* can_read_literals_ */))) {
412    CHECK(options_.class_loader_ != nullptr);
413    CHECK(options_.class_filter_ != nullptr);
414    CHECK(options_.method_filter_ != nullptr);
415    AddAllOffsets();
416  }
417
418  ~OatDumper() {
419    delete disassembler_;
420  }
421
422  InstructionSet GetInstructionSet() {
423    return instruction_set_;
424  }
425
426  bool Dump(std::ostream& os) {
427    bool success = true;
428    const OatHeader& oat_header = oat_file_.GetOatHeader();
429
430    os << "MAGIC:\n";
431    os << oat_header.GetMagic() << "\n\n";
432
433    os << "LOCATION:\n";
434    os << oat_file_.GetLocation() << "\n\n";
435
436    os << "CHECKSUM:\n";
437    os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
438
439    os << "INSTRUCTION SET:\n";
440    os << oat_header.GetInstructionSet() << "\n\n";
441
442    {
443      std::unique_ptr<const InstructionSetFeatures> features(
444          InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
445                                             oat_header.GetInstructionSetFeaturesBitmap()));
446      os << "INSTRUCTION SET FEATURES:\n";
447      os << features->GetFeatureString() << "\n\n";
448    }
449
450    os << "DEX FILE COUNT:\n";
451    os << oat_header.GetDexFileCount() << "\n\n";
452
453#define DUMP_OAT_HEADER_OFFSET(label, offset) \
454    os << label " OFFSET:\n"; \
455    os << StringPrintf("0x%08x", oat_header.offset()); \
456    if (oat_header.offset() != 0 && options_.absolute_addresses_) { \
457      os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
458    } \
459    os << StringPrintf("\n\n");
460
461    DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
462    DUMP_OAT_HEADER_OFFSET("INTERPRETER TO INTERPRETER BRIDGE",
463                           GetInterpreterToInterpreterBridgeOffset);
464    DUMP_OAT_HEADER_OFFSET("INTERPRETER TO COMPILED CODE BRIDGE",
465                           GetInterpreterToCompiledCodeBridgeOffset);
466    DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP",
467                           GetJniDlsymLookupOffset);
468    DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
469                           GetQuickGenericJniTrampolineOffset);
470    DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
471                           GetQuickImtConflictTrampolineOffset);
472    DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
473                           GetQuickResolutionTrampolineOffset);
474    DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
475                           GetQuickToInterpreterBridgeOffset);
476#undef DUMP_OAT_HEADER_OFFSET
477
478    os << "IMAGE PATCH DELTA:\n";
479    os << StringPrintf("%d (0x%08x)\n\n",
480                       oat_header.GetImagePatchDelta(),
481                       oat_header.GetImagePatchDelta());
482
483    os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
484    os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
485
486    os << "IMAGE FILE LOCATION OAT BEGIN:\n";
487    os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
488
489    // Print the key-value store.
490    {
491      os << "KEY VALUE STORE:\n";
492      size_t index = 0;
493      const char* key;
494      const char* value;
495      while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
496        os << key << " = " << value << "\n";
497        index++;
498      }
499      os << "\n";
500    }
501
502    if (options_.absolute_addresses_) {
503      os << "BEGIN:\n";
504      os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
505
506      os << "END:\n";
507      os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
508    }
509
510    os << "SIZE:\n";
511    os << oat_file_.Size() << "\n\n";
512
513    os << std::flush;
514
515    // If set, adjust relative address to be searched
516    if (options_.addr2instr_ != 0) {
517      resolved_addr2instr_ = options_.addr2instr_ + oat_header.GetExecutableOffset();
518      os << "SEARCH ADDRESS (executable offset + input):\n";
519      os << StringPrintf("0x%08x\n\n", resolved_addr2instr_);
520    }
521
522    if (!options_.dump_header_only_) {
523      for (size_t i = 0; i < oat_dex_files_.size(); i++) {
524        const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
525        CHECK(oat_dex_file != nullptr);
526
527        // If file export selected skip file analysis
528        if (options_.export_dex_location_) {
529          if (!ExportDexFile(os, *oat_dex_file)) {
530            success = false;
531          }
532        } else {
533          if (!DumpOatDexFile(os, *oat_dex_file)) {
534            success = false;
535          }
536        }
537      }
538    }
539
540    os << std::flush;
541    return success;
542  }
543
544  size_t ComputeSize(const void* oat_data) {
545    if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
546        reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
547      return 0;  // Address not in oat file
548    }
549    uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
550                             reinterpret_cast<uintptr_t>(oat_file_.Begin());
551    auto it = offsets_.upper_bound(begin_offset);
552    CHECK(it != offsets_.end());
553    uintptr_t end_offset = *it;
554    return end_offset - begin_offset;
555  }
556
557  InstructionSet GetOatInstructionSet() {
558    return oat_file_.GetOatHeader().GetInstructionSet();
559  }
560
561  const void* GetQuickOatCode(ArtMethod* m) SHARED_REQUIRES(Locks::mutator_lock_) {
562    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
563      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
564      CHECK(oat_dex_file != nullptr);
565      std::string error_msg;
566      const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
567      if (dex_file == nullptr) {
568        LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
569            << "': " << error_msg;
570      } else {
571        const char* descriptor = m->GetDeclaringClassDescriptor();
572        const DexFile::ClassDef* class_def =
573            dex_file->FindClassDef(descriptor, ComputeModifiedUtf8Hash(descriptor));
574        if (class_def != nullptr) {
575          uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
576          const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
577          size_t method_index = m->GetMethodIndex();
578          return oat_class.GetOatMethod(method_index).GetQuickCode();
579        }
580      }
581    }
582    return nullptr;
583  }
584
585 private:
586  void AddAllOffsets() {
587    // We don't know the length of the code for each method, but we need to know where to stop
588    // when disassembling. What we do know is that a region of code will be followed by some other
589    // region, so if we keep a sorted sequence of the start of each region, we can infer the length
590    // of a piece of code by using upper_bound to find the start of the next region.
591    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
592      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
593      CHECK(oat_dex_file != nullptr);
594      std::string error_msg;
595      const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
596      if (dex_file == nullptr) {
597        LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
598            << "': " << error_msg;
599        continue;
600      }
601      offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
602      for (size_t class_def_index = 0;
603           class_def_index < dex_file->NumClassDefs();
604           class_def_index++) {
605        const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
606        const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
607        const uint8_t* class_data = dex_file->GetClassData(class_def);
608        if (class_data != nullptr) {
609          ClassDataItemIterator it(*dex_file, class_data);
610          SkipAllFields(it);
611          uint32_t class_method_index = 0;
612          while (it.HasNextDirectMethod()) {
613            AddOffsets(oat_class.GetOatMethod(class_method_index++));
614            it.Next();
615          }
616          while (it.HasNextVirtualMethod()) {
617            AddOffsets(oat_class.GetOatMethod(class_method_index++));
618            it.Next();
619          }
620        }
621      }
622    }
623
624    // If the last thing in the file is code for a method, there won't be an offset for the "next"
625    // thing. Instead of having a special case in the upper_bound code, let's just add an entry
626    // for the end of the file.
627    offsets_.insert(oat_file_.Size());
628  }
629
630  static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
631    return maybe_thumb_offset & ~0x1;  // TODO: Make this Thumb2 specific.
632  }
633
634  void AddOffsets(const OatFile::OatMethod& oat_method) {
635    uint32_t code_offset = oat_method.GetCodeOffset();
636    if (oat_file_.GetOatHeader().GetInstructionSet() == kThumb2) {
637      code_offset &= ~0x1;
638    }
639    offsets_.insert(code_offset);
640    offsets_.insert(oat_method.GetMappingTableOffset());
641    offsets_.insert(oat_method.GetVmapTableOffset());
642    offsets_.insert(oat_method.GetGcMapOffset());
643  }
644
645  bool DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
646    bool success = true;
647    bool stop_analysis = false;
648    os << "OatDexFile:\n";
649    os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
650    os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
651
652    // Create the verifier early.
653
654    std::string error_msg;
655    const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
656    if (dex_file == nullptr) {
657      os << "NOT FOUND: " << error_msg << "\n\n";
658      os << std::flush;
659      return false;
660    }
661
662    VariableIndentationOutputStream vios(&os);
663    ScopedIndentation indent1(&vios);
664    for (size_t class_def_index = 0;
665         class_def_index < dex_file->NumClassDefs();
666         class_def_index++) {
667      const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
668      const char* descriptor = dex_file->GetClassDescriptor(class_def);
669
670      // TODO: Support regex
671      if (DescriptorToDot(descriptor).find(options_.class_filter_) == std::string::npos) {
672        continue;
673      }
674
675      uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
676      const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
677      os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
678                         class_def_index, descriptor, oat_class_offset, class_def.class_idx_)
679         << " (" << oat_class.GetStatus() << ")"
680         << " (" << oat_class.GetType() << ")\n";
681      // TODO: include bitmap here if type is kOatClassSomeCompiled?
682      if (options_.list_classes_) continue;
683      if (!DumpOatClass(&vios, oat_class, *dex_file, class_def, &stop_analysis)) {
684        success = false;
685      }
686      if (stop_analysis) {
687        os << std::flush;
688        return success;
689      }
690    }
691
692    os << std::flush;
693    return success;
694  }
695
696  bool ExportDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
697    std::string error_msg;
698    std::string dex_file_location = oat_dex_file.GetDexFileLocation();
699
700    const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
701    if (dex_file == nullptr) {
702      os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
703      return false;
704    }
705    size_t fsize = oat_dex_file.FileSize();
706
707    // Some quick checks just in case
708    if (fsize == 0 || fsize < sizeof(DexFile::Header)) {
709      os << "Invalid dex file\n";
710      return false;
711    }
712
713    // Verify output directory exists
714    if (!OS::DirectoryExists(options_.export_dex_location_)) {
715      // TODO: Extend OS::DirectoryExists if symlink support is required
716      os << options_.export_dex_location_ << " output directory not found or symlink\n";
717      return false;
718    }
719
720    // Beautify path names
721    if (dex_file_location.size() > PATH_MAX || dex_file_location.size() <= 0) {
722      return false;
723    }
724
725    std::string dex_orig_name;
726    size_t dex_orig_pos = dex_file_location.rfind('/');
727    if (dex_orig_pos == std::string::npos)
728      dex_orig_name = dex_file_location;
729    else
730      dex_orig_name = dex_file_location.substr(dex_orig_pos + 1);
731
732    // A more elegant approach to efficiently name user installed apps is welcome
733    if (dex_orig_name.size() == 8 && !dex_orig_name.compare("base.apk")) {
734      dex_file_location.erase(dex_orig_pos, strlen("base.apk") + 1);
735      size_t apk_orig_pos = dex_file_location.rfind('/');
736      if (apk_orig_pos != std::string::npos) {
737        dex_orig_name = dex_file_location.substr(++apk_orig_pos);
738      }
739    }
740
741    std::string out_dex_path(options_.export_dex_location_);
742    if (out_dex_path.back() != '/') {
743      out_dex_path.append("/");
744    }
745    out_dex_path.append(dex_orig_name);
746    out_dex_path.append("_export.dex");
747    if (out_dex_path.length() > PATH_MAX) {
748      return false;
749    }
750
751    std::unique_ptr<File> file(OS::CreateEmptyFile(out_dex_path.c_str()));
752    if (file.get() == nullptr) {
753      os << "Failed to open output dex file " << out_dex_path;
754      return false;
755    }
756
757    if (!file->WriteFully(dex_file->Begin(), fsize)) {
758      os << "Failed to write dex file";
759      file->Erase();
760      return false;
761    }
762
763    if (file->FlushCloseOrErase() != 0) {
764      os << "Flush and close failed";
765      return false;
766    }
767
768    os << StringPrintf("Dex file exported at %s (%zd bytes)\n", out_dex_path.c_str(), fsize);
769    os << std::flush;
770
771    return true;
772  }
773
774  static void SkipAllFields(ClassDataItemIterator& it) {
775    while (it.HasNextStaticField()) {
776      it.Next();
777    }
778    while (it.HasNextInstanceField()) {
779      it.Next();
780    }
781  }
782
783  bool DumpOatClass(VariableIndentationOutputStream* vios,
784                    const OatFile::OatClass& oat_class, const DexFile& dex_file,
785                    const DexFile::ClassDef& class_def, bool* stop_analysis) {
786    bool success = true;
787    bool addr_found = false;
788    const uint8_t* class_data = dex_file.GetClassData(class_def);
789    if (class_data == nullptr) {  // empty class such as a marker interface?
790      vios->Stream() << std::flush;
791      return success;
792    }
793    ClassDataItemIterator it(dex_file, class_data);
794    SkipAllFields(it);
795    uint32_t class_method_index = 0;
796    while (it.HasNextDirectMethod()) {
797      if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
798                         it.GetMemberIndex(), it.GetMethodCodeItem(),
799                         it.GetRawMemberAccessFlags(), &addr_found)) {
800        success = false;
801      }
802      if (addr_found) {
803        *stop_analysis = true;
804        return success;
805      }
806      class_method_index++;
807      it.Next();
808    }
809    while (it.HasNextVirtualMethod()) {
810      if (!DumpOatMethod(vios, class_def, class_method_index, oat_class, dex_file,
811                         it.GetMemberIndex(), it.GetMethodCodeItem(),
812                         it.GetRawMemberAccessFlags(), &addr_found)) {
813        success = false;
814      }
815      if (addr_found) {
816        *stop_analysis = true;
817        return success;
818      }
819      class_method_index++;
820      it.Next();
821    }
822    DCHECK(!it.HasNext());
823    vios->Stream() << std::flush;
824    return success;
825  }
826
827  static constexpr uint32_t kPrologueBytes = 16;
828
829  // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
830  static constexpr uint32_t kMaxCodeSize = 100 * 1000;
831
832  bool DumpOatMethod(VariableIndentationOutputStream* vios,
833                     const DexFile::ClassDef& class_def,
834                     uint32_t class_method_index,
835                     const OatFile::OatClass& oat_class, const DexFile& dex_file,
836                     uint32_t dex_method_idx, const DexFile::CodeItem* code_item,
837                     uint32_t method_access_flags, bool* addr_found) {
838    bool success = true;
839
840    // TODO: Support regex
841    std::string method_name = dex_file.GetMethodName(dex_file.GetMethodId(dex_method_idx));
842    if (method_name.find(options_.method_filter_) == std::string::npos) {
843      return success;
844    }
845
846    std::string pretty_method = PrettyMethod(dex_method_idx, dex_file, true);
847    vios->Stream() << StringPrintf("%d: %s (dex_method_idx=%d)\n",
848                                   class_method_index, pretty_method.c_str(),
849                                   dex_method_idx);
850    if (options_.list_methods_) return success;
851
852    uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
853    const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
854    const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
855    uint32_t code_offset = oat_method.GetCodeOffset();
856    uint32_t code_size = oat_method.GetQuickCodeSize();
857    if (resolved_addr2instr_ != 0) {
858      if (resolved_addr2instr_ > code_offset + code_size) {
859        return success;
860      } else {
861        *addr_found = true;  // stop analyzing file at next iteration
862      }
863    }
864
865    // Everything below is indented at least once.
866    ScopedIndentation indent1(vios);
867
868    {
869      vios->Stream() << "DEX CODE:\n";
870      ScopedIndentation indent2(vios);
871      DumpDexCode(vios->Stream(), dex_file, code_item);
872    }
873
874    std::unique_ptr<StackHandleScope<1>> hs;
875    std::unique_ptr<verifier::MethodVerifier> verifier;
876    if (Runtime::Current() != nullptr) {
877      // We need to have the handle scope stay live until after the verifier since the verifier has
878      // a handle to the dex cache from hs.
879      hs.reset(new StackHandleScope<1>(Thread::Current()));
880      vios->Stream() << "VERIFIER TYPE ANALYSIS:\n";
881      ScopedIndentation indent2(vios);
882      verifier.reset(DumpVerifier(vios, hs.get(),
883                                  dex_method_idx, &dex_file, class_def, code_item,
884                                  method_access_flags));
885    }
886    {
887      vios->Stream() << "OatMethodOffsets ";
888      if (options_.absolute_addresses_) {
889        vios->Stream() << StringPrintf("%p ", oat_method_offsets);
890      }
891      vios->Stream() << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
892      if (oat_method_offsets_offset > oat_file_.Size()) {
893        vios->Stream() << StringPrintf(
894            "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
895            oat_method_offsets_offset, oat_file_.Size());
896        // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
897        vios->Stream() << std::flush;
898        return false;
899      }
900
901      ScopedIndentation indent2(vios);
902      vios->Stream() << StringPrintf("code_offset: 0x%08x ", code_offset);
903      uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
904      if (aligned_code_begin > oat_file_.Size()) {
905        vios->Stream() << StringPrintf("WARNING: "
906                                       "code offset 0x%08x is past end of file 0x%08zx.\n",
907                                       aligned_code_begin, oat_file_.Size());
908        success = false;
909      }
910      vios->Stream() << "\n";
911
912      vios->Stream() << "gc_map: ";
913      if (options_.absolute_addresses_) {
914        vios->Stream() << StringPrintf("%p ", oat_method.GetGcMap());
915      }
916      uint32_t gc_map_offset = oat_method.GetGcMapOffset();
917      vios->Stream() << StringPrintf("(offset=0x%08x)\n", gc_map_offset);
918      if (gc_map_offset > oat_file_.Size()) {
919        vios->Stream() << StringPrintf("WARNING: "
920                           "gc map table offset 0x%08x is past end of file 0x%08zx.\n",
921                           gc_map_offset, oat_file_.Size());
922        success = false;
923      } else if (options_.dump_raw_gc_map_) {
924        ScopedIndentation indent3(vios);
925        DumpGcMap(vios->Stream(), oat_method, code_item);
926      }
927    }
928    {
929      vios->Stream() << "OatQuickMethodHeader ";
930      uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
931      const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
932
933      if (options_.absolute_addresses_) {
934        vios->Stream() << StringPrintf("%p ", method_header);
935      }
936      vios->Stream() << StringPrintf("(offset=0x%08x)\n", method_header_offset);
937      if (method_header_offset > oat_file_.Size()) {
938        vios->Stream() << StringPrintf(
939            "WARNING: oat quick method header offset 0x%08x is past end of file 0x%08zx.\n",
940            method_header_offset, oat_file_.Size());
941        // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
942        vios->Stream() << std::flush;
943        return false;
944      }
945
946      ScopedIndentation indent2(vios);
947      vios->Stream() << "mapping_table: ";
948      if (options_.absolute_addresses_) {
949        vios->Stream() << StringPrintf("%p ", oat_method.GetMappingTable());
950      }
951      uint32_t mapping_table_offset = oat_method.GetMappingTableOffset();
952      vios->Stream() << StringPrintf("(offset=0x%08x)\n", oat_method.GetMappingTableOffset());
953      if (mapping_table_offset > oat_file_.Size()) {
954        vios->Stream() << StringPrintf("WARNING: "
955                                       "mapping table offset 0x%08x is past end of file 0x%08zx. "
956                                       "mapping table offset was loaded from offset 0x%08x.\n",
957                                       mapping_table_offset, oat_file_.Size(),
958                                       oat_method.GetMappingTableOffsetOffset());
959        success = false;
960      } else if (options_.dump_raw_mapping_table_) {
961        ScopedIndentation indent3(vios);
962        DumpMappingTable(vios, oat_method);
963      }
964
965      vios->Stream() << "vmap_table: ";
966      if (options_.absolute_addresses_) {
967        vios->Stream() << StringPrintf("%p ", oat_method.GetVmapTable());
968      }
969      uint32_t vmap_table_offset = oat_method.GetVmapTableOffset();
970      vios->Stream() << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
971      if (vmap_table_offset > oat_file_.Size()) {
972        vios->Stream() << StringPrintf("WARNING: "
973                                       "vmap table offset 0x%08x is past end of file 0x%08zx. "
974                                       "vmap table offset was loaded from offset 0x%08x.\n",
975                                       vmap_table_offset, oat_file_.Size(),
976                                       oat_method.GetVmapTableOffsetOffset());
977        success = false;
978      } else if (options_.dump_vmap_) {
979        DumpVmapData(vios, oat_method, code_item);
980      }
981    }
982    {
983      vios->Stream() << "QuickMethodFrameInfo\n";
984
985      ScopedIndentation indent2(vios);
986      vios->Stream()
987          << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
988      vios->Stream() << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
989      DumpSpillMask(vios->Stream(), oat_method.GetCoreSpillMask(), false);
990      vios->Stream() << "\n";
991      vios->Stream() << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
992      DumpSpillMask(vios->Stream(), oat_method.GetFpSpillMask(), true);
993      vios->Stream() << "\n";
994    }
995    {
996      // Based on spill masks from QuickMethodFrameInfo so placed
997      // after it is dumped, but useful for understanding quick
998      // code, so dumped here.
999      ScopedIndentation indent2(vios);
1000      DumpVregLocations(vios->Stream(), oat_method, code_item);
1001    }
1002    {
1003      vios->Stream() << "CODE: ";
1004      uint32_t code_size_offset = oat_method.GetQuickCodeSizeOffset();
1005      if (code_size_offset > oat_file_.Size()) {
1006        ScopedIndentation indent2(vios);
1007        vios->Stream() << StringPrintf("WARNING: "
1008                                       "code size offset 0x%08x is past end of file 0x%08zx.",
1009                                       code_size_offset, oat_file_.Size());
1010        success = false;
1011      } else {
1012        const void* code = oat_method.GetQuickCode();
1013        uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
1014        uint64_t aligned_code_end = aligned_code_begin + code_size;
1015
1016        if (options_.absolute_addresses_) {
1017          vios->Stream() << StringPrintf("%p ", code);
1018        }
1019        vios->Stream() << StringPrintf("(code_offset=0x%08x size_offset=0x%08x size=%u)%s\n",
1020                                       code_offset,
1021                                       code_size_offset,
1022                                       code_size,
1023                                       code != nullptr ? "..." : "");
1024
1025        ScopedIndentation indent2(vios);
1026        if (aligned_code_begin > oat_file_.Size()) {
1027          vios->Stream() << StringPrintf("WARNING: "
1028                                         "start of code at 0x%08x is past end of file 0x%08zx.",
1029                                         aligned_code_begin, oat_file_.Size());
1030          success = false;
1031        } else if (aligned_code_end > oat_file_.Size()) {
1032          vios->Stream() << StringPrintf(
1033              "WARNING: "
1034              "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
1035              "code size is 0x%08x loaded from offset 0x%08x.\n",
1036              aligned_code_end, oat_file_.Size(),
1037              code_size, code_size_offset);
1038          success = false;
1039          if (options_.disassemble_code_) {
1040            if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
1041              DumpCode(vios, verifier.get(), oat_method, code_item, true, kPrologueBytes);
1042            }
1043          }
1044        } else if (code_size > kMaxCodeSize) {
1045          vios->Stream() << StringPrintf(
1046              "WARNING: "
1047              "code size %d is bigger than max expected threshold of %d. "
1048              "code size is 0x%08x loaded from offset 0x%08x.\n",
1049              code_size, kMaxCodeSize,
1050              code_size, code_size_offset);
1051          success = false;
1052          if (options_.disassemble_code_) {
1053            if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
1054              DumpCode(vios, verifier.get(), oat_method, code_item, true, kPrologueBytes);
1055            }
1056          }
1057        } else if (options_.disassemble_code_) {
1058          DumpCode(vios, verifier.get(), oat_method, code_item, !success, 0);
1059        }
1060      }
1061    }
1062    vios->Stream() << std::flush;
1063    return success;
1064  }
1065
1066  void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
1067    if (spill_mask == 0) {
1068      return;
1069    }
1070    os << "(";
1071    for (size_t i = 0; i < 32; i++) {
1072      if ((spill_mask & (1 << i)) != 0) {
1073        if (is_float) {
1074          os << "fr" << i;
1075        } else {
1076          os << "r" << i;
1077        }
1078        spill_mask ^= 1 << i;  // clear bit
1079        if (spill_mask != 0) {
1080          os << ", ";
1081        } else {
1082          break;
1083        }
1084      }
1085    }
1086    os << ")";
1087  }
1088
1089  // Display data stored at the the vmap offset of an oat method.
1090  void DumpVmapData(VariableIndentationOutputStream* vios,
1091                    const OatFile::OatMethod& oat_method,
1092                    const DexFile::CodeItem* code_item) {
1093    if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item)) {
1094      // The optimizing compiler outputs its CodeInfo data in the vmap table.
1095      const void* raw_code_info = oat_method.GetVmapTable();
1096      if (raw_code_info != nullptr) {
1097        CodeInfo code_info(raw_code_info);
1098        DCHECK(code_item != nullptr);
1099        ScopedIndentation indent1(vios);
1100        DumpCodeInfo(vios, code_info, oat_method, *code_item);
1101      }
1102    } else if (IsMethodGeneratedByDexToDexCompiler(oat_method, code_item)) {
1103      // We don't encode the size in the table, so just emit that we have quickened
1104      // information.
1105      ScopedIndentation indent(vios);
1106      vios->Stream() << "quickened data\n";
1107    } else {
1108      // Otherwise, display the vmap table.
1109      const uint8_t* raw_table = oat_method.GetVmapTable();
1110      if (raw_table != nullptr) {
1111        VmapTable vmap_table(raw_table);
1112        DumpVmapTable(vios->Stream(), oat_method, vmap_table);
1113      }
1114    }
1115  }
1116
1117  // Display a CodeInfo object emitted by the optimizing compiler.
1118  void DumpCodeInfo(VariableIndentationOutputStream* vios,
1119                    const CodeInfo& code_info,
1120                    const OatFile::OatMethod& oat_method,
1121                    const DexFile::CodeItem& code_item) {
1122    code_info.Dump(vios,
1123                   oat_method.GetCodeOffset(),
1124                   code_item.registers_size_,
1125                   options_.dump_code_info_stack_maps_);
1126  }
1127
1128  // Display a vmap table.
1129  void DumpVmapTable(std::ostream& os,
1130                     const OatFile::OatMethod& oat_method,
1131                     const VmapTable& vmap_table) {
1132    bool first = true;
1133    bool processing_fp = false;
1134    uint32_t spill_mask = oat_method.GetCoreSpillMask();
1135    for (size_t i = 0; i < vmap_table.Size(); i++) {
1136      uint16_t dex_reg = vmap_table[i];
1137      uint32_t cpu_reg = vmap_table.ComputeRegister(spill_mask, i,
1138                                                    processing_fp ? kFloatVReg : kIntVReg);
1139      os << (first ? "v" : ", v")  << dex_reg;
1140      if (!processing_fp) {
1141        os << "/r" << cpu_reg;
1142      } else {
1143        os << "/fr" << cpu_reg;
1144      }
1145      first = false;
1146      if (!processing_fp && dex_reg == 0xFFFF) {
1147        processing_fp = true;
1148        spill_mask = oat_method.GetFpSpillMask();
1149      }
1150    }
1151    os << "\n";
1152  }
1153
1154  void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
1155                         const DexFile::CodeItem* code_item) {
1156    if (code_item != nullptr) {
1157      size_t num_locals_ins = code_item->registers_size_;
1158      size_t num_ins = code_item->ins_size_;
1159      size_t num_locals = num_locals_ins - num_ins;
1160      size_t num_outs = code_item->outs_size_;
1161
1162      os << "vr_stack_locations:";
1163      for (size_t reg = 0; reg <= num_locals_ins; reg++) {
1164        // For readability, delimit the different kinds of VRs.
1165        if (reg == num_locals_ins) {
1166          os << "\n\tmethod*:";
1167        } else if (reg == num_locals && num_ins > 0) {
1168          os << "\n\tins:";
1169        } else if (reg == 0 && num_locals > 0) {
1170          os << "\n\tlocals:";
1171        }
1172
1173        uint32_t offset = StackVisitor::GetVRegOffsetFromQuickCode(
1174            code_item,
1175            oat_method.GetCoreSpillMask(),
1176            oat_method.GetFpSpillMask(),
1177            oat_method.GetFrameSizeInBytes(),
1178            reg,
1179            GetInstructionSet());
1180        os << " v" << reg << "[sp + #" << offset << "]";
1181      }
1182
1183      for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
1184        if (out_reg == 0) {
1185          os << "\n\touts:";
1186        }
1187
1188        uint32_t offset = StackVisitor::GetOutVROffset(out_reg, GetInstructionSet());
1189        os << " v" << out_reg << "[sp + #" << offset << "]";
1190      }
1191
1192      os << "\n";
1193    }
1194  }
1195
1196  void DescribeVReg(std::ostream& os, const OatFile::OatMethod& oat_method,
1197                    const DexFile::CodeItem* code_item, size_t reg, VRegKind kind) {
1198    const uint8_t* raw_table = oat_method.GetVmapTable();
1199    if (raw_table != nullptr) {
1200      const VmapTable vmap_table(raw_table);
1201      uint32_t vmap_offset;
1202      if (vmap_table.IsInContext(reg, kind, &vmap_offset)) {
1203        bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
1204        uint32_t spill_mask = is_float ? oat_method.GetFpSpillMask()
1205                                       : oat_method.GetCoreSpillMask();
1206        os << (is_float ? "fr" : "r") << vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
1207      } else {
1208        uint32_t offset = StackVisitor::GetVRegOffsetFromQuickCode(
1209            code_item,
1210            oat_method.GetCoreSpillMask(),
1211            oat_method.GetFpSpillMask(),
1212            oat_method.GetFrameSizeInBytes(),
1213            reg,
1214            GetInstructionSet());
1215        os << "[sp + #" << offset << "]";
1216      }
1217    }
1218  }
1219
1220  void DumpGcMapRegisters(std::ostream& os, const OatFile::OatMethod& oat_method,
1221                          const DexFile::CodeItem* code_item,
1222                          size_t num_regs, const uint8_t* reg_bitmap) {
1223    bool first = true;
1224    for (size_t reg = 0; reg < num_regs; reg++) {
1225      if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
1226        if (first) {
1227          os << "  v" << reg << " (";
1228          DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1229          os << ")";
1230          first = false;
1231        } else {
1232          os << ", v" << reg << " (";
1233          DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1234          os << ")";
1235        }
1236      }
1237    }
1238    if (first) {
1239      os << "No registers in GC map\n";
1240    } else {
1241      os << "\n";
1242    }
1243  }
1244  void DumpGcMap(std::ostream& os, const OatFile::OatMethod& oat_method,
1245                 const DexFile::CodeItem* code_item) {
1246    const uint8_t* gc_map_raw = oat_method.GetGcMap();
1247    if (gc_map_raw == nullptr) {
1248      return;  // No GC map.
1249    }
1250    const void* quick_code = oat_method.GetQuickCode();
1251    NativePcOffsetToReferenceMap map(gc_map_raw);
1252    for (size_t entry = 0; entry < map.NumEntries(); entry++) {
1253      const uint8_t* native_pc = reinterpret_cast<const uint8_t*>(quick_code) +
1254          map.GetNativePcOffset(entry);
1255      os << StringPrintf("%p", native_pc);
1256      DumpGcMapRegisters(os, oat_method, code_item, map.RegWidth() * 8, map.GetBitMap(entry));
1257    }
1258  }
1259
1260  void DumpMappingTable(VariableIndentationOutputStream* vios,
1261                        const OatFile::OatMethod& oat_method) {
1262    const void* quick_code = oat_method.GetQuickCode();
1263    if (quick_code == nullptr) {
1264      return;
1265    }
1266    MappingTable table(oat_method.GetMappingTable());
1267    if (table.TotalSize() != 0) {
1268      if (table.PcToDexSize() != 0) {
1269        typedef MappingTable::PcToDexIterator It;
1270        vios->Stream() << "suspend point mappings {\n";
1271        for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
1272          ScopedIndentation indent1(vios);
1273          vios->Stream() << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
1274        }
1275        vios->Stream() << "}\n";
1276      }
1277      if (table.DexToPcSize() != 0) {
1278        typedef MappingTable::DexToPcIterator It;
1279        vios->Stream() << "catch entry mappings {\n";
1280        for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
1281          ScopedIndentation indent1(vios);
1282          vios->Stream() << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
1283        }
1284        vios->Stream() << "}\n";
1285      }
1286    }
1287  }
1288
1289  uint32_t DumpInformationAtOffset(VariableIndentationOutputStream* vios,
1290                                   const OatFile::OatMethod& oat_method,
1291                                   const DexFile::CodeItem* code_item,
1292                                   size_t offset,
1293                                   bool suspend_point_mapping) {
1294    if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item)) {
1295      if (suspend_point_mapping) {
1296        ScopedIndentation indent1(vios);
1297        DumpDexRegisterMapAtOffset(vios, oat_method, code_item, offset);
1298      }
1299      // The return value is not used in the case of a method compiled
1300      // with the optimizing compiler.
1301      return DexFile::kDexNoIndex;
1302    } else {
1303      return DumpMappingAtOffset(vios->Stream(), oat_method, offset, suspend_point_mapping);
1304    }
1305  }
1306
1307  uint32_t DumpMappingAtOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
1308                               size_t offset, bool suspend_point_mapping) {
1309    MappingTable table(oat_method.GetMappingTable());
1310    if (suspend_point_mapping && table.PcToDexSize() > 0) {
1311      typedef MappingTable::PcToDexIterator It;
1312      for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
1313        if (offset == cur.NativePcOffset()) {
1314          os << StringPrintf("suspend point dex PC: 0x%04x\n", cur.DexPc());
1315          return cur.DexPc();
1316        }
1317      }
1318    } else if (!suspend_point_mapping && table.DexToPcSize() > 0) {
1319      typedef MappingTable::DexToPcIterator It;
1320      for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
1321        if (offset == cur.NativePcOffset()) {
1322          os << StringPrintf("catch entry dex PC: 0x%04x\n", cur.DexPc());
1323          return cur.DexPc();
1324        }
1325      }
1326    }
1327    return DexFile::kDexNoIndex;
1328  }
1329
1330  void DumpGcMapAtNativePcOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
1331                                 const DexFile::CodeItem* code_item, size_t native_pc_offset) {
1332    const uint8_t* gc_map_raw = oat_method.GetGcMap();
1333    if (gc_map_raw != nullptr) {
1334      NativePcOffsetToReferenceMap map(gc_map_raw);
1335      if (map.HasEntry(native_pc_offset)) {
1336        size_t num_regs = map.RegWidth() * 8;
1337        const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset);
1338        bool first = true;
1339        for (size_t reg = 0; reg < num_regs; reg++) {
1340          if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
1341            if (first) {
1342              os << "GC map objects:  v" << reg << " (";
1343              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1344              os << ")";
1345              first = false;
1346            } else {
1347              os << ", v" << reg << " (";
1348              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1349              os << ")";
1350            }
1351          }
1352        }
1353        if (!first) {
1354          os << "\n";
1355        }
1356      }
1357    }
1358  }
1359
1360  void DumpVRegsAtDexPc(std::ostream& os, verifier::MethodVerifier* verifier,
1361                        const OatFile::OatMethod& oat_method,
1362                        const DexFile::CodeItem* code_item, uint32_t dex_pc) {
1363    DCHECK(verifier != nullptr);
1364    std::vector<int32_t> kinds = verifier->DescribeVRegs(dex_pc);
1365    bool first = true;
1366    for (size_t reg = 0; reg < code_item->registers_size_; reg++) {
1367      VRegKind kind = static_cast<VRegKind>(kinds.at(reg * 2));
1368      if (kind != kUndefined) {
1369        if (first) {
1370          os << "VRegs:  v";
1371          first = false;
1372        } else {
1373          os << ", v";
1374        }
1375        os << reg << " (";
1376        switch (kind) {
1377          case kImpreciseConstant:
1378            os << "Imprecise Constant: " << kinds.at((reg * 2) + 1) << ", ";
1379            DescribeVReg(os, oat_method, code_item, reg, kind);
1380            break;
1381          case kConstant:
1382            os << "Constant: " << kinds.at((reg * 2) + 1);
1383            break;
1384          default:
1385            DescribeVReg(os, oat_method, code_item, reg, kind);
1386            break;
1387        }
1388        os << ")";
1389      }
1390    }
1391    if (!first) {
1392      os << "\n";
1393    }
1394  }
1395
1396
1397  void DumpDexCode(std::ostream& os, const DexFile& dex_file, const DexFile::CodeItem* code_item) {
1398    if (code_item != nullptr) {
1399      size_t i = 0;
1400      while (i < code_item->insns_size_in_code_units_) {
1401        const Instruction* instruction = Instruction::At(&code_item->insns_[i]);
1402        os << StringPrintf("0x%04zx: ", i) << instruction->DumpHexLE(5)
1403           << StringPrintf("\t| %s\n", instruction->DumpString(&dex_file).c_str());
1404        i += instruction->SizeInCodeUnits();
1405      }
1406    }
1407  }
1408
1409  // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1410  // the optimizing compiler?
1411  static bool IsMethodGeneratedByOptimizingCompiler(const OatFile::OatMethod& oat_method,
1412                                                    const DexFile::CodeItem* code_item) {
1413    // If the native GC map is null and the Dex `code_item` is not
1414    // null, then this method has been compiled with the optimizing
1415    // compiler.
1416    return oat_method.GetQuickCode() != nullptr &&
1417           oat_method.GetGcMap() == nullptr &&
1418           code_item != nullptr;
1419  }
1420
1421  // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1422  // the dextodex compiler?
1423  static bool IsMethodGeneratedByDexToDexCompiler(const OatFile::OatMethod& oat_method,
1424                                                  const DexFile::CodeItem* code_item) {
1425    // If the quick code is null, the Dex `code_item` is not
1426    // null, and the vmap table is not null, then this method has been compiled
1427    // with the dextodex compiler.
1428    return oat_method.GetQuickCode() == nullptr &&
1429           oat_method.GetVmapTable() != nullptr &&
1430           code_item != nullptr;
1431  }
1432
1433  void DumpDexRegisterMapAtOffset(VariableIndentationOutputStream* vios,
1434                                  const OatFile::OatMethod& oat_method,
1435                                  const DexFile::CodeItem* code_item,
1436                                  size_t offset) {
1437    // This method is only relevant for oat methods compiled with the
1438    // optimizing compiler.
1439    DCHECK(IsMethodGeneratedByOptimizingCompiler(oat_method, code_item));
1440
1441    // The optimizing compiler outputs its CodeInfo data in the vmap table.
1442    const void* raw_code_info = oat_method.GetVmapTable();
1443    if (raw_code_info != nullptr) {
1444      CodeInfo code_info(raw_code_info);
1445      StackMapEncoding encoding = code_info.ExtractEncoding();
1446      StackMap stack_map = code_info.GetStackMapForNativePcOffset(offset, encoding);
1447      if (stack_map.IsValid()) {
1448        stack_map.Dump(vios, code_info, encoding, oat_method.GetCodeOffset(),
1449                       code_item->registers_size_);
1450      }
1451    }
1452  }
1453
1454  verifier::MethodVerifier* DumpVerifier(VariableIndentationOutputStream* vios,
1455                                         StackHandleScope<1>* hs,
1456                                         uint32_t dex_method_idx,
1457                                         const DexFile* dex_file,
1458                                         const DexFile::ClassDef& class_def,
1459                                         const DexFile::CodeItem* code_item,
1460                                         uint32_t method_access_flags) {
1461    if ((method_access_flags & kAccNative) == 0) {
1462      ScopedObjectAccess soa(Thread::Current());
1463      Runtime* const runtime = Runtime::Current();
1464      Handle<mirror::DexCache> dex_cache(
1465          hs->NewHandle(runtime->GetClassLinker()->RegisterDexFile(*dex_file,
1466                                                                   runtime->GetLinearAlloc())));
1467      DCHECK(options_.class_loader_ != nullptr);
1468      return verifier::MethodVerifier::VerifyMethodAndDump(
1469          soa.Self(), vios, dex_method_idx, dex_file, dex_cache, *options_.class_loader_,
1470          &class_def, code_item, nullptr, method_access_flags);
1471    }
1472
1473    return nullptr;
1474  }
1475
1476  void DumpCode(VariableIndentationOutputStream* vios,
1477                verifier::MethodVerifier* verifier,
1478                const OatFile::OatMethod& oat_method, const DexFile::CodeItem* code_item,
1479                bool bad_input, size_t code_size) {
1480    const void* quick_code = oat_method.GetQuickCode();
1481
1482    if (code_size == 0) {
1483      code_size = oat_method.GetQuickCodeSize();
1484    }
1485    if (code_size == 0 || quick_code == nullptr) {
1486      vios->Stream() << "NO CODE!\n";
1487      return;
1488    } else {
1489      const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1490      size_t offset = 0;
1491      while (offset < code_size) {
1492        if (!bad_input) {
1493          DumpInformationAtOffset(vios, oat_method, code_item, offset, false);
1494        }
1495        offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
1496        if (!bad_input) {
1497          uint32_t dex_pc =
1498              DumpInformationAtOffset(vios, oat_method, code_item, offset, true);
1499          if (dex_pc != DexFile::kDexNoIndex) {
1500            DumpGcMapAtNativePcOffset(vios->Stream(), oat_method, code_item, offset);
1501            if (verifier != nullptr) {
1502              DumpVRegsAtDexPc(vios->Stream(), verifier, oat_method, code_item, dex_pc);
1503            }
1504          }
1505        }
1506      }
1507    }
1508  }
1509
1510  const OatFile& oat_file_;
1511  const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
1512  const OatDumperOptions& options_;
1513  uint32_t resolved_addr2instr_;
1514  InstructionSet instruction_set_;
1515  std::set<uintptr_t> offsets_;
1516  Disassembler* disassembler_;
1517};
1518
1519class ImageDumper {
1520 public:
1521  ImageDumper(std::ostream* os, gc::space::ImageSpace& image_space,
1522              const ImageHeader& image_header, OatDumperOptions* oat_dumper_options)
1523      : os_(os),
1524        vios_(os),
1525        indent1_(&vios_),
1526        image_space_(image_space),
1527        image_header_(image_header),
1528        oat_dumper_options_(oat_dumper_options) {}
1529
1530  bool Dump() SHARED_REQUIRES(Locks::mutator_lock_) {
1531    std::ostream& os = *os_;
1532    std::ostream& indent_os = vios_.Stream();
1533
1534    os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
1535
1536    os << "IMAGE LOCATION: " << image_space_.GetImageLocation() << "\n\n";
1537
1538    os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
1539
1540    os << "IMAGE SIZE: " << image_header_.GetImageSize() << "\n\n";
1541
1542    for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1543      auto section = static_cast<ImageHeader::ImageSections>(i);
1544      os << "IMAGE SECTION " << section << ": " << image_header_.GetImageSection(section) << "\n\n";
1545    }
1546
1547    os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
1548
1549    os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
1550
1551    os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
1552
1553    os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
1554
1555    os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
1556
1557    os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
1558
1559    os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
1560
1561    {
1562      os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
1563      static_assert(arraysize(image_roots_descriptions_) ==
1564          static_cast<size_t>(ImageHeader::kImageRootsMax), "sizes must match");
1565      for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
1566        ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
1567        const char* image_root_description = image_roots_descriptions_[i];
1568        mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
1569        indent_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
1570        if (image_root_object->IsObjectArray()) {
1571          mirror::ObjectArray<mirror::Object>* image_root_object_array
1572              = image_root_object->AsObjectArray<mirror::Object>();
1573          ScopedIndentation indent2(&vios_);
1574          for (int j = 0; j < image_root_object_array->GetLength(); j++) {
1575            mirror::Object* value = image_root_object_array->Get(j);
1576            size_t run = 0;
1577            for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
1578              if (value == image_root_object_array->Get(k)) {
1579                run++;
1580              } else {
1581                break;
1582              }
1583            }
1584            if (run == 0) {
1585              indent_os << StringPrintf("%d: ", j);
1586            } else {
1587              indent_os << StringPrintf("%d to %zd: ", j, j + run);
1588              j = j + run;
1589            }
1590            if (value != nullptr) {
1591              PrettyObjectValue(indent_os, value->GetClass(), value);
1592            } else {
1593              indent_os << j << ": null\n";
1594            }
1595          }
1596        }
1597      }
1598    }
1599
1600    {
1601      os << "METHOD ROOTS\n";
1602      static_assert(arraysize(image_methods_descriptions_) ==
1603          static_cast<size_t>(ImageHeader::kImageMethodsCount), "sizes must match");
1604      for (int i = 0; i < ImageHeader::kImageMethodsCount; i++) {
1605        auto image_root = static_cast<ImageHeader::ImageMethod>(i);
1606        const char* description = image_methods_descriptions_[i];
1607        auto* image_method = image_header_.GetImageMethod(image_root);
1608        indent_os << StringPrintf("%s: %p\n", description, image_method);
1609      }
1610    }
1611    os << "\n";
1612
1613    Runtime* const runtime = Runtime::Current();
1614    ClassLinker* class_linker = runtime->GetClassLinker();
1615    std::string image_filename = image_space_.GetImageFilename();
1616    std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
1617    os << "OAT LOCATION: " << oat_location;
1618    os << "\n";
1619    std::string error_msg;
1620    const OatFile* oat_file = runtime->GetOatFileManager().FindOpenedOatFileFromOatLocation(
1621        oat_location);
1622    if (oat_file == nullptr) {
1623      oat_file = OatFile::Open(oat_location, oat_location,
1624                               nullptr, nullptr, false, nullptr,
1625                               &error_msg);
1626      if (oat_file == nullptr) {
1627        os << "NOT FOUND: " << error_msg << "\n";
1628        return false;
1629      }
1630    }
1631    os << "\n";
1632
1633    stats_.oat_file_bytes = oat_file->Size();
1634
1635    oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
1636
1637    for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1638      CHECK(oat_dex_file != nullptr);
1639      stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
1640                                                         oat_dex_file->FileSize()));
1641    }
1642
1643    os << "OBJECTS:\n" << std::flush;
1644
1645    // Loop through the image space and dump its objects.
1646    gc::Heap* heap = runtime->GetHeap();
1647    Thread* self = Thread::Current();
1648    {
1649      {
1650        WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1651        heap->FlushAllocStack();
1652      }
1653      // Since FlushAllocStack() above resets the (active) allocation
1654      // stack. Need to revoke the thread-local allocation stacks that
1655      // point into it.
1656      ScopedThreadSuspension sts(self, kNative);
1657      ScopedSuspendAll ssa(__FUNCTION__);
1658      heap->RevokeAllThreadLocalAllocationStacks(self);
1659    }
1660    {
1661      // Mark dex caches.
1662      dex_caches_.clear();
1663      {
1664        ReaderMutexLock mu(self, *class_linker->DexLock());
1665        for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1666          mirror::DexCache* dex_cache =
1667              down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
1668          if (dex_cache != nullptr) {
1669            dex_caches_.insert(dex_cache);
1670          }
1671        }
1672      }
1673      ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1674      // Dump the normal objects before ArtMethods.
1675      image_space_.GetLiveBitmap()->Walk(ImageDumper::Callback, this);
1676      indent_os << "\n";
1677      // TODO: Dump fields.
1678      // Dump methods after.
1679      const auto& methods_section = image_header_.GetMethodsSection();
1680      const size_t pointer_size =
1681          InstructionSetPointerSize(oat_dumper_->GetOatInstructionSet());
1682      DumpArtMethodVisitor visitor(this);
1683      methods_section.VisitPackedArtMethods(&visitor, image_space_.Begin(), pointer_size);
1684      // Dump the large objects separately.
1685      heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(ImageDumper::Callback, this);
1686      indent_os << "\n";
1687    }
1688    os << "STATS:\n" << std::flush;
1689    std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
1690    if (file.get() == nullptr) {
1691      LOG(WARNING) << "Failed to find image in " << image_filename;
1692    }
1693    if (file.get() != nullptr) {
1694      stats_.file_bytes = file->GetLength();
1695    }
1696    size_t header_bytes = sizeof(ImageHeader);
1697    const auto& object_section = image_header_.GetImageSection(ImageHeader::kSectionObjects);
1698    const auto& field_section = image_header_.GetImageSection(ImageHeader::kSectionArtFields);
1699    const auto& method_section = image_header_.GetMethodsSection();
1700    const auto& dex_cache_arrays_section = image_header_.GetImageSection(
1701        ImageHeader::kSectionDexCacheArrays);
1702    const auto& intern_section = image_header_.GetImageSection(
1703        ImageHeader::kSectionInternedStrings);
1704    const auto& class_table_section = image_header_.GetImageSection(
1705        ImageHeader::kSectionClassTable);
1706    const auto& bitmap_section = image_header_.GetImageSection(ImageHeader::kSectionImageBitmap);
1707
1708    stats_.header_bytes = header_bytes;
1709
1710    // Objects are kObjectAlignment-aligned.
1711    // CHECK_EQ(RoundUp(header_bytes, kObjectAlignment), object_section.Offset());
1712    if (object_section.Offset() > header_bytes) {
1713      stats_.alignment_bytes += object_section.Offset() - header_bytes;
1714    }
1715
1716    // Field section is 4-byte aligned.
1717    constexpr size_t kFieldSectionAlignment = 4U;
1718    uint32_t end_objects = object_section.Offset() + object_section.Size();
1719    CHECK_EQ(RoundUp(end_objects, kFieldSectionAlignment), field_section.Offset());
1720    stats_.alignment_bytes += field_section.Offset() - end_objects;
1721
1722    // Method section is 4/8 byte aligned depending on target. Just check for 4-byte alignment.
1723    uint32_t end_fields = field_section.Offset() + field_section.Size();
1724    CHECK_ALIGNED(method_section.Offset(), 4);
1725    stats_.alignment_bytes += method_section.Offset() - end_fields;
1726
1727    // Dex cache arrays section is aligned depending on the target. Just check for 4-byte alignment.
1728    uint32_t end_methods = method_section.Offset() + method_section.Size();
1729    CHECK_ALIGNED(dex_cache_arrays_section.Offset(), 4);
1730    stats_.alignment_bytes += dex_cache_arrays_section.Offset() - end_methods;
1731
1732    // Intern table is 8-byte aligned.
1733    uint32_t end_caches = dex_cache_arrays_section.Offset() + dex_cache_arrays_section.Size();
1734    CHECK_EQ(RoundUp(end_caches, 8U), intern_section.Offset());
1735    stats_.alignment_bytes += intern_section.Offset() - end_caches;
1736
1737    // Add space between intern table and class table.
1738    uint32_t end_intern = intern_section.Offset() + intern_section.Size();
1739    stats_.alignment_bytes += class_table_section.Offset() - end_intern;
1740
1741    // Add space between class table and bitmap. Expect the bitmap to be page-aligned.
1742    uint32_t end_ctable = class_table_section.Offset() + class_table_section.Size();
1743    CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
1744    stats_.alignment_bytes += bitmap_section.Offset() - end_ctable;
1745
1746    stats_.bitmap_bytes += bitmap_section.Size();
1747    stats_.art_field_bytes += field_section.Size();
1748    stats_.art_method_bytes += method_section.Size();
1749    stats_.dex_cache_arrays_bytes += dex_cache_arrays_section.Size();
1750    stats_.interned_strings_bytes += intern_section.Size();
1751    stats_.class_table_bytes += class_table_section.Size();
1752    stats_.Dump(os, indent_os);
1753    os << "\n";
1754
1755    os << std::flush;
1756
1757    return oat_dumper_->Dump(os);
1758  }
1759
1760 private:
1761  class DumpArtMethodVisitor : public ArtMethodVisitor {
1762   public:
1763    explicit DumpArtMethodVisitor(ImageDumper* image_dumper) : image_dumper_(image_dumper) {}
1764
1765    virtual void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
1766      std::ostream& indent_os = image_dumper_->vios_.Stream();
1767      indent_os << method << " " << " ArtMethod: " << PrettyMethod(method) << "\n";
1768      image_dumper_->DumpMethod(method, image_dumper_, indent_os);
1769      indent_os << "\n";
1770    }
1771
1772   private:
1773    ImageDumper* const image_dumper_;
1774  };
1775
1776  static void PrettyObjectValue(std::ostream& os, mirror::Class* type, mirror::Object* value)
1777      SHARED_REQUIRES(Locks::mutator_lock_) {
1778    CHECK(type != nullptr);
1779    if (value == nullptr) {
1780      os << StringPrintf("null   %s\n", PrettyDescriptor(type).c_str());
1781    } else if (type->IsStringClass()) {
1782      mirror::String* string = value->AsString();
1783      os << StringPrintf("%p   String: %s\n", string,
1784                         PrintableString(string->ToModifiedUtf8().c_str()).c_str());
1785    } else if (type->IsClassClass()) {
1786      mirror::Class* klass = value->AsClass();
1787      os << StringPrintf("%p   Class: %s\n", klass, PrettyDescriptor(klass).c_str());
1788    } else {
1789      os << StringPrintf("%p   %s\n", value, PrettyDescriptor(type).c_str());
1790    }
1791  }
1792
1793  static void PrintField(std::ostream& os, ArtField* field, mirror::Object* obj)
1794      SHARED_REQUIRES(Locks::mutator_lock_) {
1795    os << StringPrintf("%s: ", field->GetName());
1796    switch (field->GetTypeAsPrimitiveType()) {
1797      case Primitive::kPrimLong:
1798        os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
1799        break;
1800      case Primitive::kPrimDouble:
1801        os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
1802        break;
1803      case Primitive::kPrimFloat:
1804        os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
1805        break;
1806      case Primitive::kPrimInt:
1807        os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
1808        break;
1809      case Primitive::kPrimChar:
1810        os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
1811        break;
1812      case Primitive::kPrimShort:
1813        os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
1814        break;
1815      case Primitive::kPrimBoolean:
1816        os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj)? "true" : "false",
1817            field->GetBoolean(obj));
1818        break;
1819      case Primitive::kPrimByte:
1820        os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
1821        break;
1822      case Primitive::kPrimNot: {
1823        // Get the value, don't compute the type unless it is non-null as we don't want
1824        // to cause class loading.
1825        mirror::Object* value = field->GetObj(obj);
1826        if (value == nullptr) {
1827          os << StringPrintf("null   %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
1828        } else {
1829          // Grab the field type without causing resolution.
1830          mirror::Class* field_type = field->GetType<false>();
1831          if (field_type != nullptr) {
1832            PrettyObjectValue(os, field_type, value);
1833          } else {
1834            os << StringPrintf("%p   %s\n", value,
1835                               PrettyDescriptor(field->GetTypeDescriptor()).c_str());
1836          }
1837        }
1838        break;
1839      }
1840      default:
1841        os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
1842        break;
1843    }
1844  }
1845
1846  static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
1847      SHARED_REQUIRES(Locks::mutator_lock_) {
1848    mirror::Class* super = klass->GetSuperClass();
1849    if (super != nullptr) {
1850      DumpFields(os, obj, super);
1851    }
1852    for (ArtField& field : klass->GetIFields()) {
1853      PrintField(os, &field, obj);
1854    }
1855  }
1856
1857  bool InDumpSpace(const mirror::Object* object) {
1858    return image_space_.Contains(object);
1859  }
1860
1861  const void* GetQuickOatCodeBegin(ArtMethod* m)
1862      SHARED_REQUIRES(Locks::mutator_lock_) {
1863    const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
1864        InstructionSetPointerSize(oat_dumper_->GetOatInstructionSet()));
1865    if (Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(quick_code)) {
1866      quick_code = oat_dumper_->GetQuickOatCode(m);
1867    }
1868    if (oat_dumper_->GetInstructionSet() == kThumb2) {
1869      quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
1870    }
1871    return quick_code;
1872  }
1873
1874  uint32_t GetQuickOatCodeSize(ArtMethod* m)
1875      SHARED_REQUIRES(Locks::mutator_lock_) {
1876    const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
1877    if (oat_code_begin == nullptr) {
1878      return 0;
1879    }
1880    return oat_code_begin[-1];
1881  }
1882
1883  const void* GetQuickOatCodeEnd(ArtMethod* m)
1884      SHARED_REQUIRES(Locks::mutator_lock_) {
1885    const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
1886    if (oat_code_begin == nullptr) {
1887      return nullptr;
1888    }
1889    return oat_code_begin + GetQuickOatCodeSize(m);
1890  }
1891
1892  static void Callback(mirror::Object* obj, void* arg) SHARED_REQUIRES(Locks::mutator_lock_) {
1893    DCHECK(obj != nullptr);
1894    DCHECK(arg != nullptr);
1895    ImageDumper* state = reinterpret_cast<ImageDumper*>(arg);
1896    if (!state->InDumpSpace(obj)) {
1897      return;
1898    }
1899
1900    size_t object_bytes = obj->SizeOf();
1901    size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
1902    state->stats_.object_bytes += object_bytes;
1903    state->stats_.alignment_bytes += alignment_bytes;
1904
1905    std::ostream& os = state->vios_.Stream();
1906
1907    mirror::Class* obj_class = obj->GetClass();
1908    if (obj_class->IsArrayClass()) {
1909      os << StringPrintf("%p: %s length:%d\n", obj, PrettyDescriptor(obj_class).c_str(),
1910                         obj->AsArray()->GetLength());
1911    } else if (obj->IsClass()) {
1912      mirror::Class* klass = obj->AsClass();
1913      os << StringPrintf("%p: java.lang.Class \"%s\" (", obj, PrettyDescriptor(klass).c_str())
1914         << klass->GetStatus() << ")\n";
1915    } else if (obj_class->IsStringClass()) {
1916      os << StringPrintf("%p: java.lang.String %s\n", obj,
1917                         PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
1918    } else {
1919      os << StringPrintf("%p: %s\n", obj, PrettyDescriptor(obj_class).c_str());
1920    }
1921    ScopedIndentation indent1(&state->vios_);
1922    DumpFields(os, obj, obj_class);
1923    const auto image_pointer_size =
1924        InstructionSetPointerSize(state->oat_dumper_->GetOatInstructionSet());
1925    if (obj->IsObjectArray()) {
1926      auto* obj_array = obj->AsObjectArray<mirror::Object>();
1927      for (int32_t i = 0, length = obj_array->GetLength(); i < length; i++) {
1928        mirror::Object* value = obj_array->Get(i);
1929        size_t run = 0;
1930        for (int32_t j = i + 1; j < length; j++) {
1931          if (value == obj_array->Get(j)) {
1932            run++;
1933          } else {
1934            break;
1935          }
1936        }
1937        if (run == 0) {
1938          os << StringPrintf("%d: ", i);
1939        } else {
1940          os << StringPrintf("%d to %zd: ", i, i + run);
1941          i = i + run;
1942        }
1943        mirror::Class* value_class =
1944            (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
1945        PrettyObjectValue(os, value_class, value);
1946      }
1947    } else if (obj->IsClass()) {
1948      mirror::Class* klass = obj->AsClass();
1949      if (klass->NumStaticFields() != 0) {
1950        os << "STATICS:\n";
1951        ScopedIndentation indent2(&state->vios_);
1952        for (ArtField& field : klass->GetSFields()) {
1953          PrintField(os, &field, field.GetDeclaringClass());
1954        }
1955      }
1956    } else {
1957      auto it = state->dex_caches_.find(obj);
1958      if (it != state->dex_caches_.end()) {
1959        auto* dex_cache = down_cast<mirror::DexCache*>(obj);
1960        const auto& field_section = state->image_header_.GetImageSection(
1961            ImageHeader::kSectionArtFields);
1962        const auto& method_section = state->image_header_.GetMethodsSection();
1963        size_t num_methods = dex_cache->NumResolvedMethods();
1964        if (num_methods != 0u) {
1965          os << "Methods (size=" << num_methods << "):";
1966          ScopedIndentation indent2(&state->vios_);
1967          auto* resolved_methods = dex_cache->GetResolvedMethods();
1968          for (size_t i = 0, length = dex_cache->NumResolvedMethods(); i < length; ++i) {
1969            auto* elem = mirror::DexCache::GetElementPtrSize(resolved_methods, i, image_pointer_size);
1970            size_t run = 0;
1971            for (size_t j = i + 1;
1972                j != length && elem == mirror::DexCache::GetElementPtrSize(resolved_methods,
1973                                                                           j,
1974                                                                           image_pointer_size);
1975                ++j, ++run) {}
1976            if (run == 0) {
1977              os << StringPrintf("%zd: ", i);
1978            } else {
1979              os << StringPrintf("%zd to %zd: ", i, i + run);
1980              i = i + run;
1981            }
1982            std::string msg;
1983            if (elem == nullptr) {
1984              msg = "null";
1985            } else if (method_section.Contains(
1986                reinterpret_cast<uint8_t*>(elem) - state->image_space_.Begin())) {
1987              msg = PrettyMethod(reinterpret_cast<ArtMethod*>(elem));
1988            } else {
1989              msg = "<not in method section>";
1990            }
1991            os << StringPrintf("%p   %s\n", elem, msg.c_str());
1992          }
1993        }
1994        size_t num_fields = dex_cache->NumResolvedFields();
1995        if (num_fields != 0u) {
1996          os << "Fields (size=" << num_fields << "):";
1997          ScopedIndentation indent2(&state->vios_);
1998          auto* resolved_fields = dex_cache->GetResolvedFields();
1999          for (size_t i = 0, length = dex_cache->NumResolvedFields(); i < length; ++i) {
2000            auto* elem = mirror::DexCache::GetElementPtrSize(resolved_fields, i, image_pointer_size);
2001            size_t run = 0;
2002            for (size_t j = i + 1;
2003                j != length && elem == mirror::DexCache::GetElementPtrSize(resolved_fields,
2004                                                                           j,
2005                                                                           image_pointer_size);
2006                ++j, ++run) {}
2007            if (run == 0) {
2008              os << StringPrintf("%zd: ", i);
2009            } else {
2010              os << StringPrintf("%zd to %zd: ", i, i + run);
2011              i = i + run;
2012            }
2013            std::string msg;
2014            if (elem == nullptr) {
2015              msg = "null";
2016            } else if (field_section.Contains(
2017                reinterpret_cast<uint8_t*>(elem) - state->image_space_.Begin())) {
2018              msg = PrettyField(reinterpret_cast<ArtField*>(elem));
2019            } else {
2020              msg = "<not in field section>";
2021            }
2022            os << StringPrintf("%p   %s\n", elem, msg.c_str());
2023          }
2024        }
2025      }
2026    }
2027    std::string temp;
2028    state->stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
2029  }
2030
2031  void DumpMethod(ArtMethod* method, ImageDumper* state, std::ostream& indent_os)
2032      SHARED_REQUIRES(Locks::mutator_lock_) {
2033    DCHECK(method != nullptr);
2034    const auto image_pointer_size =
2035        InstructionSetPointerSize(state->oat_dumper_->GetOatInstructionSet());
2036    const void* quick_oat_code_begin = state->GetQuickOatCodeBegin(method);
2037    const void* quick_oat_code_end = state->GetQuickOatCodeEnd(method);
2038    OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2039        reinterpret_cast<uintptr_t>(quick_oat_code_begin) - sizeof(OatQuickMethodHeader));
2040    if (method->IsNative()) {
2041      if (!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(quick_oat_code_begin)) {
2042        DCHECK(method_header->GetNativeGcMap() == nullptr) << PrettyMethod(method);
2043        DCHECK(method_header->GetMappingTable() == nullptr) << PrettyMethod(method);
2044      }
2045      bool first_occurrence;
2046      uint32_t quick_oat_code_size = state->GetQuickOatCodeSize(method);
2047      state->ComputeOatSize(quick_oat_code_begin, &first_occurrence);
2048      if (first_occurrence) {
2049        state->stats_.native_to_managed_code_bytes += quick_oat_code_size;
2050      }
2051      if (quick_oat_code_begin !=
2052            method->GetEntryPointFromQuickCompiledCodePtrSize(image_pointer_size)) {
2053        indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code_begin);
2054      }
2055    } else if (method->IsAbstract() || method->IsCalleeSaveMethod() ||
2056      method->IsResolutionMethod() || method->IsImtConflictMethod() ||
2057      method->IsImtUnimplementedMethod() || method->IsClassInitializer()) {
2058    } else {
2059      const DexFile::CodeItem* code_item = method->GetCodeItem();
2060      size_t dex_instruction_bytes = code_item->insns_size_in_code_units_ * 2;
2061      state->stats_.dex_instruction_bytes += dex_instruction_bytes;
2062
2063      bool first_occurrence;
2064      size_t gc_map_bytes = state->ComputeOatSize(
2065          method_header->GetNativeGcMap(), &first_occurrence);
2066      if (first_occurrence) {
2067        state->stats_.gc_map_bytes += gc_map_bytes;
2068      }
2069
2070      size_t pc_mapping_table_bytes = state->ComputeOatSize(
2071          method_header->GetMappingTable(), &first_occurrence);
2072      if (first_occurrence) {
2073        state->stats_.pc_mapping_table_bytes += pc_mapping_table_bytes;
2074      }
2075
2076      size_t vmap_table_bytes = 0u;
2077      if (!method_header->IsOptimized()) {
2078        // Method compiled with the optimizing compiler have no vmap table.
2079        vmap_table_bytes = state->ComputeOatSize(
2080            method_header->GetVmapTable(), &first_occurrence);
2081        if (first_occurrence) {
2082          state->stats_.vmap_table_bytes += vmap_table_bytes;
2083        }
2084      }
2085
2086      uint32_t quick_oat_code_size = state->GetQuickOatCodeSize(method);
2087      state->ComputeOatSize(quick_oat_code_begin, &first_occurrence);
2088      if (first_occurrence) {
2089        state->stats_.managed_code_bytes += quick_oat_code_size;
2090        if (method->IsConstructor()) {
2091          if (method->IsStatic()) {
2092            state->stats_.class_initializer_code_bytes += quick_oat_code_size;
2093          } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
2094            state->stats_.large_initializer_code_bytes += quick_oat_code_size;
2095          }
2096        } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
2097          state->stats_.large_method_code_bytes += quick_oat_code_size;
2098        }
2099      }
2100      state->stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
2101
2102      uint32_t method_access_flags = method->GetAccessFlags();
2103
2104      indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
2105      indent_os << StringPrintf("SIZE: Dex Instructions=%zd GC=%zd Mapping=%zd AccessFlags=0x%x\n",
2106                                dex_instruction_bytes, gc_map_bytes, pc_mapping_table_bytes,
2107                                method_access_flags);
2108
2109      size_t total_size = dex_instruction_bytes + gc_map_bytes + pc_mapping_table_bytes +
2110          vmap_table_bytes + quick_oat_code_size + ArtMethod::Size(image_pointer_size);
2111
2112      double expansion =
2113      static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
2114      state->stats_.ComputeOutliers(total_size, expansion, method);
2115    }
2116  }
2117
2118  std::set<const void*> already_seen_;
2119  // Compute the size of the given data within the oat file and whether this is the first time
2120  // this data has been requested
2121  size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
2122    if (already_seen_.count(oat_data) == 0) {
2123      *first_occurrence = true;
2124      already_seen_.insert(oat_data);
2125    } else {
2126      *first_occurrence = false;
2127    }
2128    return oat_dumper_->ComputeSize(oat_data);
2129  }
2130
2131 public:
2132  struct Stats {
2133    size_t oat_file_bytes;
2134    size_t file_bytes;
2135
2136    size_t header_bytes;
2137    size_t object_bytes;
2138    size_t art_field_bytes;
2139    size_t art_method_bytes;
2140    size_t dex_cache_arrays_bytes;
2141    size_t interned_strings_bytes;
2142    size_t class_table_bytes;
2143    size_t bitmap_bytes;
2144    size_t alignment_bytes;
2145
2146    size_t managed_code_bytes;
2147    size_t managed_code_bytes_ignoring_deduplication;
2148    size_t managed_to_native_code_bytes;
2149    size_t native_to_managed_code_bytes;
2150    size_t class_initializer_code_bytes;
2151    size_t large_initializer_code_bytes;
2152    size_t large_method_code_bytes;
2153
2154    size_t gc_map_bytes;
2155    size_t pc_mapping_table_bytes;
2156    size_t vmap_table_bytes;
2157
2158    size_t dex_instruction_bytes;
2159
2160    std::vector<ArtMethod*> method_outlier;
2161    std::vector<size_t> method_outlier_size;
2162    std::vector<double> method_outlier_expansion;
2163    std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
2164
2165    Stats()
2166        : oat_file_bytes(0),
2167          file_bytes(0),
2168          header_bytes(0),
2169          object_bytes(0),
2170          art_field_bytes(0),
2171          art_method_bytes(0),
2172          dex_cache_arrays_bytes(0),
2173          interned_strings_bytes(0),
2174          class_table_bytes(0),
2175          bitmap_bytes(0),
2176          alignment_bytes(0),
2177          managed_code_bytes(0),
2178          managed_code_bytes_ignoring_deduplication(0),
2179          managed_to_native_code_bytes(0),
2180          native_to_managed_code_bytes(0),
2181          class_initializer_code_bytes(0),
2182          large_initializer_code_bytes(0),
2183          large_method_code_bytes(0),
2184          gc_map_bytes(0),
2185          pc_mapping_table_bytes(0),
2186          vmap_table_bytes(0),
2187          dex_instruction_bytes(0) {}
2188
2189    struct SizeAndCount {
2190      SizeAndCount(size_t bytes_in, size_t count_in) : bytes(bytes_in), count(count_in) {}
2191      size_t bytes;
2192      size_t count;
2193    };
2194    typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
2195    SizeAndCountTable sizes_and_counts;
2196
2197    void Update(const char* descriptor, size_t object_bytes_in) {
2198      SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
2199      if (it != sizes_and_counts.end()) {
2200        it->second.bytes += object_bytes_in;
2201        it->second.count += 1;
2202      } else {
2203        sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes_in, 1));
2204      }
2205    }
2206
2207    double PercentOfOatBytes(size_t size) {
2208      return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
2209    }
2210
2211    double PercentOfFileBytes(size_t size) {
2212      return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
2213    }
2214
2215    double PercentOfObjectBytes(size_t size) {
2216      return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
2217    }
2218
2219    void ComputeOutliers(size_t total_size, double expansion, ArtMethod* method) {
2220      method_outlier_size.push_back(total_size);
2221      method_outlier_expansion.push_back(expansion);
2222      method_outlier.push_back(method);
2223    }
2224
2225    void DumpOutliers(std::ostream& os)
2226        SHARED_REQUIRES(Locks::mutator_lock_) {
2227      size_t sum_of_sizes = 0;
2228      size_t sum_of_sizes_squared = 0;
2229      size_t sum_of_expansion = 0;
2230      size_t sum_of_expansion_squared = 0;
2231      size_t n = method_outlier_size.size();
2232      if (n == 0) {
2233        return;
2234      }
2235      for (size_t i = 0; i < n; i++) {
2236        size_t cur_size = method_outlier_size[i];
2237        sum_of_sizes += cur_size;
2238        sum_of_sizes_squared += cur_size * cur_size;
2239        double cur_expansion = method_outlier_expansion[i];
2240        sum_of_expansion += cur_expansion;
2241        sum_of_expansion_squared += cur_expansion * cur_expansion;
2242      }
2243      size_t size_mean = sum_of_sizes / n;
2244      size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
2245      double expansion_mean = sum_of_expansion / n;
2246      double expansion_variance =
2247          (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
2248
2249      // Dump methods whose size is a certain number of standard deviations from the mean
2250      size_t dumped_values = 0;
2251      size_t skipped_values = 0;
2252      for (size_t i = 100; i > 0; i--) {  // i is the current number of standard deviations
2253        size_t cur_size_variance = i * i * size_variance;
2254        bool first = true;
2255        for (size_t j = 0; j < n; j++) {
2256          size_t cur_size = method_outlier_size[j];
2257          if (cur_size > size_mean) {
2258            size_t cur_var = cur_size - size_mean;
2259            cur_var = cur_var * cur_var;
2260            if (cur_var > cur_size_variance) {
2261              if (dumped_values > 20) {
2262                if (i == 1) {
2263                  skipped_values++;
2264                } else {
2265                  i = 2;  // jump to counting for 1 standard deviation
2266                  break;
2267                }
2268              } else {
2269                if (first) {
2270                  os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
2271                  first = false;
2272                }
2273                os << PrettyMethod(method_outlier[j]) << " requires storage of "
2274                    << PrettySize(cur_size) << "\n";
2275                method_outlier_size[j] = 0;  // don't consider this method again
2276                dumped_values++;
2277              }
2278            }
2279          }
2280        }
2281      }
2282      if (skipped_values > 0) {
2283        os << "... skipped " << skipped_values
2284           << " methods with size > 1 standard deviation from the norm\n";
2285      }
2286      os << std::flush;
2287
2288      // Dump methods whose expansion is a certain number of standard deviations from the mean
2289      dumped_values = 0;
2290      skipped_values = 0;
2291      for (size_t i = 10; i > 0; i--) {  // i is the current number of standard deviations
2292        double cur_expansion_variance = i * i * expansion_variance;
2293        bool first = true;
2294        for (size_t j = 0; j < n; j++) {
2295          double cur_expansion = method_outlier_expansion[j];
2296          if (cur_expansion > expansion_mean) {
2297            size_t cur_var = cur_expansion - expansion_mean;
2298            cur_var = cur_var * cur_var;
2299            if (cur_var > cur_expansion_variance) {
2300              if (dumped_values > 20) {
2301                if (i == 1) {
2302                  skipped_values++;
2303                } else {
2304                  i = 2;  // jump to counting for 1 standard deviation
2305                  break;
2306                }
2307              } else {
2308                if (first) {
2309                  os << "\nLarge expansion methods (size > " << i
2310                      << " standard deviations the norm):\n";
2311                  first = false;
2312                }
2313                os << PrettyMethod(method_outlier[j]) << " expanded code by "
2314                   << cur_expansion << "\n";
2315                method_outlier_expansion[j] = 0.0;  // don't consider this method again
2316                dumped_values++;
2317              }
2318            }
2319          }
2320        }
2321      }
2322      if (skipped_values > 0) {
2323        os << "... skipped " << skipped_values
2324           << " methods with expansion > 1 standard deviation from the norm\n";
2325      }
2326      os << "\n" << std::flush;
2327    }
2328
2329    void Dump(std::ostream& os, std::ostream& indent_os)
2330        SHARED_REQUIRES(Locks::mutator_lock_) {
2331      {
2332        os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
2333           << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
2334        indent_os << StringPrintf("header_bytes           =  %8zd (%2.0f%% of art file bytes)\n"
2335                                  "object_bytes           =  %8zd (%2.0f%% of art file bytes)\n"
2336                                  "art_field_bytes        =  %8zd (%2.0f%% of art file bytes)\n"
2337                                  "art_method_bytes       =  %8zd (%2.0f%% of art file bytes)\n"
2338                                  "dex_cache_arrays_bytes =  %8zd (%2.0f%% of art file bytes)\n"
2339                                  "interned_string_bytes  =  %8zd (%2.0f%% of art file bytes)\n"
2340                                  "class_table_bytes      =  %8zd (%2.0f%% of art file bytes)\n"
2341                                  "bitmap_bytes           =  %8zd (%2.0f%% of art file bytes)\n"
2342                                  "alignment_bytes        =  %8zd (%2.0f%% of art file bytes)\n\n",
2343                                  header_bytes, PercentOfFileBytes(header_bytes),
2344                                  object_bytes, PercentOfFileBytes(object_bytes),
2345                                  art_field_bytes, PercentOfFileBytes(art_field_bytes),
2346                                  art_method_bytes, PercentOfFileBytes(art_method_bytes),
2347                                  dex_cache_arrays_bytes,
2348                                  PercentOfFileBytes(dex_cache_arrays_bytes),
2349                                  interned_strings_bytes,
2350                                  PercentOfFileBytes(interned_strings_bytes),
2351                                  class_table_bytes, PercentOfFileBytes(class_table_bytes),
2352                                  bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
2353                                  alignment_bytes, PercentOfFileBytes(alignment_bytes))
2354            << std::flush;
2355        CHECK_EQ(file_bytes,
2356                 header_bytes + object_bytes + art_field_bytes + art_method_bytes +
2357                 dex_cache_arrays_bytes + interned_strings_bytes + class_table_bytes +
2358                 bitmap_bytes + alignment_bytes);
2359      }
2360
2361      os << "object_bytes breakdown:\n";
2362      size_t object_bytes_total = 0;
2363      for (const auto& sizes_and_count : sizes_and_counts) {
2364        const std::string& descriptor(sizes_and_count.first);
2365        double average = static_cast<double>(sizes_and_count.second.bytes) /
2366            static_cast<double>(sizes_and_count.second.count);
2367        double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
2368        os << StringPrintf("%32s %8zd bytes %6zd instances "
2369                           "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
2370                           descriptor.c_str(), sizes_and_count.second.bytes,
2371                           sizes_and_count.second.count, average, percent);
2372        object_bytes_total += sizes_and_count.second.bytes;
2373      }
2374      os << "\n" << std::flush;
2375      CHECK_EQ(object_bytes, object_bytes_total);
2376
2377      os << StringPrintf("oat_file_bytes               = %8zd\n"
2378                         "managed_code_bytes           = %8zd (%2.0f%% of oat file bytes)\n"
2379                         "managed_to_native_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2380                         "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
2381                         "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2382                         "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2383                         "large_method_code_bytes      = %8zd (%2.0f%% of oat file bytes)\n\n",
2384                         oat_file_bytes,
2385                         managed_code_bytes,
2386                         PercentOfOatBytes(managed_code_bytes),
2387                         managed_to_native_code_bytes,
2388                         PercentOfOatBytes(managed_to_native_code_bytes),
2389                         native_to_managed_code_bytes,
2390                         PercentOfOatBytes(native_to_managed_code_bytes),
2391                         class_initializer_code_bytes,
2392                         PercentOfOatBytes(class_initializer_code_bytes),
2393                         large_initializer_code_bytes,
2394                         PercentOfOatBytes(large_initializer_code_bytes),
2395                         large_method_code_bytes,
2396                         PercentOfOatBytes(large_method_code_bytes))
2397            << "DexFile sizes:\n";
2398      for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
2399        os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
2400                           oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2401                           PercentOfOatBytes(oat_dex_file_size.second));
2402      }
2403
2404      os << "\n" << StringPrintf("gc_map_bytes           = %7zd (%2.0f%% of oat file bytes)\n"
2405                                 "pc_mapping_table_bytes = %7zd (%2.0f%% of oat file bytes)\n"
2406                                 "vmap_table_bytes       = %7zd (%2.0f%% of oat file bytes)\n\n",
2407                                 gc_map_bytes, PercentOfOatBytes(gc_map_bytes),
2408                                 pc_mapping_table_bytes, PercentOfOatBytes(pc_mapping_table_bytes),
2409                                 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
2410         << std::flush;
2411
2412      os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2413         << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
2414                         static_cast<double>(managed_code_bytes) /
2415                             static_cast<double>(dex_instruction_bytes),
2416                         static_cast<double>(managed_code_bytes_ignoring_deduplication) /
2417                             static_cast<double>(dex_instruction_bytes))
2418         << std::flush;
2419
2420      DumpOutliers(os);
2421    }
2422  } stats_;
2423
2424 private:
2425  enum {
2426    // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2427    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2428    kLargeConstructorDexBytes = 4000,
2429    // Number of bytes for a method to be considered large. Based on the 4000 basic block
2430    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2431    kLargeMethodDexBytes = 16000
2432  };
2433
2434  // For performance, use the *os_ directly for anything that doesn't need indentation
2435  // and prepare an indentation stream with default indentation 1.
2436  std::ostream* os_;
2437  VariableIndentationOutputStream vios_;
2438  ScopedIndentation indent1_;
2439
2440  gc::space::ImageSpace& image_space_;
2441  const ImageHeader& image_header_;
2442  std::unique_ptr<OatDumper> oat_dumper_;
2443  OatDumperOptions* oat_dumper_options_;
2444  std::set<mirror::Object*> dex_caches_;
2445
2446  DISALLOW_COPY_AND_ASSIGN(ImageDumper);
2447};
2448
2449static int DumpImage(Runtime* runtime, OatDumperOptions* options, std::ostream* os) {
2450  // Dumping the image, no explicit class loader.
2451  ScopedNullHandle<mirror::ClassLoader> null_class_loader;
2452  options->class_loader_ = &null_class_loader;
2453
2454  ScopedObjectAccess soa(Thread::Current());
2455  gc::Heap* heap = runtime->GetHeap();
2456  std::vector<gc::space::ImageSpace*> image_spaces = heap->GetBootImageSpaces();
2457  CHECK(!image_spaces.empty());
2458  for (gc::space::ImageSpace* image_space : image_spaces) {
2459    const ImageHeader& image_header = image_space->GetImageHeader();
2460    if (!image_header.IsValid()) {
2461      fprintf(stderr, "Invalid image header %s\n", image_space->GetImageLocation().c_str());
2462      return EXIT_FAILURE;
2463    }
2464
2465    ImageDumper image_dumper(os, *image_space, image_header, options);
2466    if (!image_dumper.Dump()) {
2467      return EXIT_FAILURE;
2468    }
2469  }
2470  return EXIT_SUCCESS;
2471}
2472
2473static int DumpOatWithRuntime(Runtime* runtime, OatFile* oat_file, OatDumperOptions* options,
2474                              std::ostream* os) {
2475  CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
2476
2477  Thread* self = Thread::Current();
2478  CHECK(self != nullptr);
2479  // Need well-known-classes.
2480  WellKnownClasses::Init(self->GetJniEnv());
2481
2482  // Need to register dex files to get a working dex cache.
2483  ScopedObjectAccess soa(self);
2484  ClassLinker* class_linker = runtime->GetClassLinker();
2485  runtime->GetOatFileManager().RegisterOatFile(std::unique_ptr<const OatFile>(oat_file));
2486  std::vector<const DexFile*> class_path;
2487  for (const OatFile::OatDexFile* odf : oat_file->GetOatDexFiles()) {
2488    std::string error_msg;
2489    const DexFile* const dex_file = OpenDexFile(odf, &error_msg);
2490    CHECK(dex_file != nullptr) << error_msg;
2491    class_linker->RegisterDexFile(*dex_file, runtime->GetLinearAlloc());
2492    class_path.push_back(dex_file);
2493  }
2494
2495  // Need a class loader.
2496  // Fake that we're a compiler.
2497  jobject class_loader = class_linker->CreatePathClassLoader(self, class_path);
2498
2499  // Use the class loader while dumping.
2500  StackHandleScope<1> scope(self);
2501  Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
2502      soa.Decode<mirror::ClassLoader*>(class_loader));
2503  options->class_loader_ = &loader_handle;
2504
2505  OatDumper oat_dumper(*oat_file, *options);
2506  bool success = oat_dumper.Dump(*os);
2507  return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2508}
2509
2510static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
2511  CHECK(oat_file != nullptr && options != nullptr);
2512  // No image = no class loader.
2513  ScopedNullHandle<mirror::ClassLoader> null_class_loader;
2514  options->class_loader_ = &null_class_loader;
2515
2516  OatDumper oat_dumper(*oat_file, *options);
2517  bool success = oat_dumper.Dump(*os);
2518  return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2519}
2520
2521static int DumpOat(Runtime* runtime, const char* oat_filename, OatDumperOptions* options,
2522                   std::ostream* os) {
2523  std::string error_msg;
2524  OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, nullptr, nullptr, false,
2525                                    nullptr, &error_msg);
2526  if (oat_file == nullptr) {
2527    fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
2528    return EXIT_FAILURE;
2529  }
2530
2531  if (runtime != nullptr) {
2532    return DumpOatWithRuntime(runtime, oat_file, options, os);
2533  } else {
2534    return DumpOatWithoutRuntime(oat_file, options, os);
2535  }
2536}
2537
2538static int SymbolizeOat(const char* oat_filename, std::string& output_name) {
2539  std::string error_msg;
2540  OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, nullptr, nullptr, false,
2541                                    nullptr, &error_msg);
2542  if (oat_file == nullptr) {
2543    fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
2544    return EXIT_FAILURE;
2545  }
2546
2547  OatSymbolizer oat_symbolizer(oat_file, output_name);
2548  if (!oat_symbolizer.Symbolize()) {
2549    fprintf(stderr, "Failed to symbolize\n");
2550    return EXIT_FAILURE;
2551  }
2552
2553  return EXIT_SUCCESS;
2554}
2555
2556struct OatdumpArgs : public CmdlineArgs {
2557 protected:
2558  using Base = CmdlineArgs;
2559
2560  virtual ParseStatus ParseCustom(const StringPiece& option,
2561                                  std::string* error_msg) OVERRIDE {
2562    {
2563      ParseStatus base_parse = Base::ParseCustom(option, error_msg);
2564      if (base_parse != kParseUnknownArgument) {
2565        return base_parse;
2566      }
2567    }
2568
2569    if (option.starts_with("--oat-file=")) {
2570      oat_filename_ = option.substr(strlen("--oat-file=")).data();
2571    } else if (option.starts_with("--image=")) {
2572      image_location_ = option.substr(strlen("--image=")).data();
2573    } else if (option =="--dump:raw_mapping_table") {
2574      dump_raw_mapping_table_ = true;
2575    } else if (option == "--dump:raw_gc_map") {
2576      dump_raw_gc_map_ = true;
2577    } else if (option == "--no-dump:vmap") {
2578      dump_vmap_ = false;
2579    } else if (option =="--dump:code_info_stack_maps") {
2580      dump_code_info_stack_maps_ = true;
2581    } else if (option == "--no-disassemble") {
2582      disassemble_code_ = false;
2583    } else if (option =="--header-only") {
2584      dump_header_only_ = true;
2585    } else if (option.starts_with("--symbolize=")) {
2586      oat_filename_ = option.substr(strlen("--symbolize=")).data();
2587      symbolize_ = true;
2588    } else if (option.starts_with("--class-filter=")) {
2589      class_filter_ = option.substr(strlen("--class-filter=")).data();
2590    } else if (option.starts_with("--method-filter=")) {
2591      method_filter_ = option.substr(strlen("--method-filter=")).data();
2592    } else if (option.starts_with("--list-classes")) {
2593      list_classes_ = true;
2594    } else if (option.starts_with("--list-methods")) {
2595      list_methods_ = true;
2596    } else if (option.starts_with("--export-dex-to=")) {
2597      export_dex_location_ = option.substr(strlen("--export-dex-to=")).data();
2598    } else if (option.starts_with("--addr2instr=")) {
2599      if (!ParseUint(option.substr(strlen("--addr2instr=")).data(), &addr2instr_)) {
2600        *error_msg = "Address conversion failed";
2601        return kParseError;
2602      }
2603    } else {
2604      return kParseUnknownArgument;
2605    }
2606
2607    return kParseOk;
2608  }
2609
2610  virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
2611    // Infer boot image location from the image location if possible.
2612    if (boot_image_location_ == nullptr) {
2613      boot_image_location_ = image_location_;
2614    }
2615
2616    // Perform the parent checks.
2617    ParseStatus parent_checks = Base::ParseChecks(error_msg);
2618    if (parent_checks != kParseOk) {
2619      return parent_checks;
2620    }
2621
2622    // Perform our own checks.
2623    if (image_location_ == nullptr && oat_filename_ == nullptr) {
2624      *error_msg = "Either --image or --oat-file must be specified";
2625      return kParseError;
2626    } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
2627      *error_msg = "Either --image or --oat-file must be specified but not both";
2628      return kParseError;
2629    }
2630
2631    return kParseOk;
2632  }
2633
2634  virtual std::string GetUsage() const {
2635    std::string usage;
2636
2637    usage +=
2638        "Usage: oatdump [options] ...\n"
2639        "    Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
2640        "    Example: adb shell oatdump --image=/system/framework/boot.art\n"
2641        "\n"
2642        // Either oat-file or image is required.
2643        "  --oat-file=<file.oat>: specifies an input oat filename.\n"
2644        "      Example: --oat-file=/system/framework/boot.oat\n"
2645        "\n"
2646        "  --image=<file.art>: specifies an input image location.\n"
2647        "      Example: --image=/system/framework/boot.art\n"
2648        "\n";
2649
2650    usage += Base::GetUsage();
2651
2652    usage +=  // Optional.
2653        "  --dump:raw_mapping_table enables dumping of the mapping table.\n"
2654        "      Example: --dump:raw_mapping_table\n"
2655        "\n"
2656        "  --dump:raw_gc_map enables dumping of the GC map.\n"
2657        "      Example: --dump:raw_gc_map\n"
2658        "\n"
2659        "  --no-dump:vmap may be used to disable vmap dumping.\n"
2660        "      Example: --no-dump:vmap\n"
2661        "\n"
2662        "  --dump:code_info_stack_maps enables dumping of stack maps in CodeInfo sections.\n"
2663        "      Example: --dump:code_info_stack_maps\n"
2664        "\n"
2665        "  --no-disassemble may be used to disable disassembly.\n"
2666        "      Example: --no-disassemble\n"
2667        "\n"
2668        "  --header-only may be used to print only the oat header.\n"
2669        "      Example: --header-only\n"
2670        "\n"
2671        "  --list-classes may be used to list target file classes (can be used with filters).\n"
2672        "      Example: --list-classes\n"
2673        "      Example: --list-classes --class-filter=com.example.foo\n"
2674        "\n"
2675        "  --list-methods may be used to list target file methods (can be used with filters).\n"
2676        "      Example: --list-methods\n"
2677        "      Example: --list-methods --class-filter=com.example --method-filter=foo\n"
2678        "\n"
2679        "  --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
2680        "      Example: --symbolize=/system/framework/boot.oat\n"
2681        "\n"
2682        "  --class-filter=<class name>: only dumps classes that contain the filter.\n"
2683        "      Example: --class-filter=com.example.foo\n"
2684        "\n"
2685        "  --method-filter=<method name>: only dumps methods that contain the filter.\n"
2686        "      Example: --method-filter=foo\n"
2687        "\n"
2688        "  --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
2689        "      Example: --export-dex-to=/data/local/tmp\n"
2690        "\n"
2691        "  --addr2instr=<address>: output matching method disassembled code from relative\n"
2692        "                          address (e.g. PC from crash dump)\n"
2693        "      Example: --addr2instr=0x00001a3b\n"
2694        "\n";
2695
2696    return usage;
2697  }
2698
2699 public:
2700  const char* oat_filename_ = nullptr;
2701  const char* class_filter_ = "";
2702  const char* method_filter_ = "";
2703  const char* image_location_ = nullptr;
2704  std::string elf_filename_prefix_;
2705  bool dump_raw_mapping_table_ = false;
2706  bool dump_raw_gc_map_ = false;
2707  bool dump_vmap_ = true;
2708  bool dump_code_info_stack_maps_ = false;
2709  bool disassemble_code_ = true;
2710  bool symbolize_ = false;
2711  bool list_classes_ = false;
2712  bool list_methods_ = false;
2713  bool dump_header_only_ = false;
2714  uint32_t addr2instr_ = 0;
2715  const char* export_dex_location_ = nullptr;
2716};
2717
2718struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
2719  virtual bool NeedsRuntime() OVERRIDE {
2720    CHECK(args_ != nullptr);
2721
2722    // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
2723    bool absolute_addresses = (args_->oat_filename_ == nullptr);
2724
2725    oat_dumper_options_ = std::unique_ptr<OatDumperOptions>(new OatDumperOptions(
2726        args_->dump_raw_mapping_table_,
2727        args_->dump_raw_gc_map_,
2728        args_->dump_vmap_,
2729        args_->dump_code_info_stack_maps_,
2730        args_->disassemble_code_,
2731        absolute_addresses,
2732        args_->class_filter_,
2733        args_->method_filter_,
2734        args_->list_classes_,
2735        args_->list_methods_,
2736        args_->dump_header_only_,
2737        args_->export_dex_location_,
2738        args_->addr2instr_));
2739
2740    return (args_->boot_image_location_ != nullptr || args_->image_location_ != nullptr) &&
2741          !args_->symbolize_;
2742  }
2743
2744  virtual bool ExecuteWithoutRuntime() OVERRIDE {
2745    CHECK(args_ != nullptr);
2746    CHECK(args_->oat_filename_ != nullptr);
2747
2748    MemMap::Init();
2749
2750    if (args_->symbolize_) {
2751      return SymbolizeOat(args_->oat_filename_, args_->output_name_) == EXIT_SUCCESS;
2752    } else {
2753      return DumpOat(nullptr,
2754                     args_->oat_filename_,
2755                     oat_dumper_options_.get(),
2756                     args_->os_) == EXIT_SUCCESS;
2757    }
2758  }
2759
2760  virtual bool ExecuteWithRuntime(Runtime* runtime) {
2761    CHECK(args_ != nullptr);
2762
2763    if (args_->oat_filename_ != nullptr) {
2764      return DumpOat(runtime,
2765                     args_->oat_filename_,
2766                     oat_dumper_options_.get(),
2767                     args_->os_) == EXIT_SUCCESS;
2768    }
2769
2770    return DumpImage(runtime, oat_dumper_options_.get(), args_->os_) == EXIT_SUCCESS;
2771  }
2772
2773  std::unique_ptr<OatDumperOptions> oat_dumper_options_;
2774};
2775
2776}  // namespace art
2777
2778int main(int argc, char** argv) {
2779  art::OatdumpMain main;
2780  return main.Main(argc, argv);
2781}
2782