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