oatdump.cc revision 3774335b08076117d6950cd472cdd59a167470b5
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 "base/unix_file/fd_file.h"
30#include "class_linker.h"
31#include "class_linker-inl.h"
32#include "dex_file-inl.h"
33#include "dex_instruction.h"
34#include "disassembler.h"
35#include "elf_builder.h"
36#include "gc_map.h"
37#include "gc/space/image_space.h"
38#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
40#include "image.h"
41#include "indenter.h"
42#include "mapping_table.h"
43#include "mirror/art_field-inl.h"
44#include "mirror/art_method-inl.h"
45#include "mirror/array-inl.h"
46#include "mirror/class-inl.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array-inl.h"
49#include "oat.h"
50#include "oat_file-inl.h"
51#include "os.h"
52#include "output_stream.h"
53#include "safe_map.h"
54#include "scoped_thread_state_change.h"
55#include "ScopedLocalRef.h"
56#include "thread_list.h"
57#include "verifier/dex_gc_map.h"
58#include "verifier/method_verifier.h"
59#include "vmap_table.h"
60#include "well_known_classes.h"
61
62#include <sys/stat.h>
63#include "cmdline.h"
64
65namespace art {
66
67const char* image_roots_descriptions_[] = {
68  "kResolutionMethod",
69  "kImtConflictMethod",
70  "kImtUnimplementedMethod",
71  "kDefaultImt",
72  "kCalleeSaveMethod",
73  "kRefsOnlySaveMethod",
74  "kRefsAndArgsSaveMethod",
75  "kDexCaches",
76  "kClassRoots",
77};
78
79class OatSymbolizer FINAL : public CodeOutput {
80 public:
81  explicit OatSymbolizer(const OatFile* oat_file, const std::string& output_name) :
82      oat_file_(oat_file), builder_(nullptr), elf_output_(nullptr),
83      output_name_(output_name.empty() ? "symbolized.oat" : output_name) {
84  }
85
86  bool Init() {
87    Elf32_Word oat_data_size = oat_file_->GetOatHeader().GetExecutableOffset();
88
89    uint32_t diff = static_cast<uint32_t>(oat_file_->End() - oat_file_->Begin());
90    uint32_t oat_exec_size = diff - oat_data_size;
91
92    elf_output_ = OS::CreateEmptyFile(output_name_.c_str());
93
94    builder_.reset(new ElfBuilder<Elf32_Word, Elf32_Sword, Elf32_Addr, Elf32_Dyn,
95                                  Elf32_Sym, Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>(
96        this,
97        elf_output_,
98        oat_file_->GetOatHeader().GetInstructionSet(),
99        0,
100        oat_data_size,
101        oat_data_size,
102        oat_exec_size,
103        true,
104        false));
105
106    if (!builder_->Init()) {
107      builder_.reset(nullptr);
108      return false;
109    }
110
111    return true;
112  }
113
114  typedef void (OatSymbolizer::*Callback)(const DexFile::ClassDef&,
115                                          uint32_t,
116                                          const OatFile::OatMethod&,
117                                          const DexFile&,
118                                          uint32_t,
119                                          const DexFile::CodeItem*,
120                                          uint32_t);
121
122  bool Symbolize() {
123    if (builder_.get() == nullptr) {
124      return false;
125    }
126
127    Walk(&art::OatSymbolizer::RegisterForDedup);
128
129    NormalizeState();
130
131    Walk(&art::OatSymbolizer::AddSymbol);
132
133    bool result = builder_->Write();
134
135    // Ignore I/O errors.
136    UNUSED(elf_output_->FlushClose());
137
138    return result;
139  }
140
141  void Walk(Callback callback) {
142    std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
143    for (size_t i = 0; i < oat_dex_files.size(); i++) {
144      const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
145      CHECK(oat_dex_file != NULL);
146      WalkOatDexFile(oat_dex_file, callback);
147    }
148  }
149
150  void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file, Callback callback) {
151    std::string error_msg;
152    std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
153    if (dex_file.get() == nullptr) {
154      return;
155    }
156    for (size_t class_def_index = 0;
157        class_def_index < dex_file->NumClassDefs();
158        class_def_index++) {
159      const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
160      const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
161      OatClassType type = oat_class.GetType();
162      switch (type) {
163        case kOatClassAllCompiled:
164        case kOatClassSomeCompiled:
165          WalkOatClass(oat_class, *dex_file.get(), class_def, callback);
166          break;
167
168        case kOatClassNoneCompiled:
169        case kOatClassMax:
170          // Ignore.
171          break;
172      }
173    }
174  }
175
176  void WalkOatClass(const OatFile::OatClass& oat_class, const DexFile& dex_file,
177                    const DexFile::ClassDef& class_def, Callback callback) {
178    const uint8_t* class_data = dex_file.GetClassData(class_def);
179    if (class_data == nullptr) {  // empty class such as a marker interface?
180      return;
181    }
182    // Note: even if this is an interface or a native class, we still have to walk it, as there
183    //       might be a static initializer.
184    ClassDataItemIterator it(dex_file, class_data);
185    SkipAllFields(&it);
186    uint32_t class_method_idx = 0;
187    while (it.HasNextDirectMethod()) {
188      const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_idx);
189      WalkOatMethod(class_def, class_method_idx, oat_method, dex_file, it.GetMemberIndex(),
190                    it.GetMethodCodeItem(), it.GetMethodAccessFlags(), callback);
191      class_method_idx++;
192      it.Next();
193    }
194    while (it.HasNextVirtualMethod()) {
195      const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_idx);
196      WalkOatMethod(class_def, class_method_idx, oat_method, dex_file, it.GetMemberIndex(),
197                    it.GetMethodCodeItem(), it.GetMethodAccessFlags(), callback);
198      class_method_idx++;
199      it.Next();
200    }
201    DCHECK(!it.HasNext());
202  }
203
204  void WalkOatMethod(const DexFile::ClassDef& class_def, uint32_t class_method_index,
205                     const OatFile::OatMethod& oat_method, const DexFile& dex_file,
206                     uint32_t dex_method_idx, const DexFile::CodeItem* code_item,
207                     uint32_t method_access_flags, Callback callback) {
208    if ((method_access_flags & kAccAbstract) != 0) {
209      // Abstract method, no code.
210      return;
211    }
212    if (oat_method.GetCodeOffset() == 0) {
213      // No code.
214      return;
215    }
216
217    (this->*callback)(class_def, class_method_index, oat_method, dex_file, dex_method_idx, code_item,
218                      method_access_flags);
219  }
220
221  void RegisterForDedup(const DexFile::ClassDef& class_def ATTRIBUTE_UNUSED,
222                        uint32_t class_method_index ATTRIBUTE_UNUSED,
223                        const OatFile::OatMethod& oat_method,
224                        const DexFile& dex_file ATTRIBUTE_UNUSED,
225                        uint32_t dex_method_idx ATTRIBUTE_UNUSED,
226                        const DexFile::CodeItem* code_item ATTRIBUTE_UNUSED,
227                        uint32_t method_access_flags ATTRIBUTE_UNUSED) {
228    state_[oat_method.GetCodeOffset()]++;
229  }
230
231  void NormalizeState() {
232    for (auto& x : state_) {
233      if (x.second == 1) {
234        state_[x.first] = 0;
235      }
236    }
237  }
238
239  enum class DedupState {  // private
240    kNotDeduplicated,
241    kDeduplicatedFirst,
242    kDeduplicatedOther
243  };
244  DedupState IsDuplicated(uint32_t offset) {
245    if (state_[offset] == 0) {
246      return DedupState::kNotDeduplicated;
247    }
248    if (state_[offset] == 1) {
249      return DedupState::kDeduplicatedOther;
250    }
251    state_[offset] = 1;
252    return DedupState::kDeduplicatedFirst;
253  }
254
255  void AddSymbol(const DexFile::ClassDef& class_def ATTRIBUTE_UNUSED,
256                 uint32_t class_method_index ATTRIBUTE_UNUSED,
257                 const OatFile::OatMethod& oat_method,
258                 const DexFile& dex_file,
259                 uint32_t dex_method_idx,
260                 const DexFile::CodeItem* code_item ATTRIBUTE_UNUSED,
261                 uint32_t method_access_flags ATTRIBUTE_UNUSED) {
262    DedupState dedup = IsDuplicated(oat_method.GetCodeOffset());
263    if (dedup != DedupState::kDeduplicatedOther) {
264      std::string pretty_name = PrettyMethod(dex_method_idx, dex_file, true);
265
266      if (dedup == DedupState::kDeduplicatedFirst) {
267        pretty_name = "[Dedup]" + pretty_name;
268      }
269
270      ElfSymtabBuilder<Elf32_Word, Elf32_Sword, Elf32_Addr,
271      Elf32_Sym, Elf32_Shdr>* symtab = builder_->GetSymtabBuilder();
272
273      symtab->AddSymbol(pretty_name, &builder_->GetTextBuilder(),
274          oat_method.GetCodeOffset() - oat_file_->GetOatHeader().GetExecutableOffset(),
275          true, oat_method.GetQuickCodeSize(), STB_GLOBAL, STT_FUNC);
276    }
277  }
278
279  // Set oat data offset. Required by ElfBuilder/CodeOutput.
280  void SetCodeOffset(size_t offset ATTRIBUTE_UNUSED) {
281    // Nothing to do.
282  }
283
284  // Write oat code. Required by ElfBuilder/CodeOutput.
285  bool Write(OutputStream* out) {
286    return out->WriteFully(oat_file_->Begin(), oat_file_->End() - oat_file_->Begin());
287  }
288
289 private:
290  static void SkipAllFields(ClassDataItemIterator* it) {
291    while (it->HasNextStaticField()) {
292      it->Next();
293    }
294    while (it->HasNextInstanceField()) {
295      it->Next();
296    }
297  }
298
299  const OatFile* oat_file_;
300  std::unique_ptr<ElfBuilder<Elf32_Word, Elf32_Sword, Elf32_Addr, Elf32_Dyn,
301                              Elf32_Sym, Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr> > builder_;
302  File* elf_output_;
303  std::unordered_map<uint32_t, uint32_t> state_;
304  const std::string output_name_;
305};
306
307class OatDumperOptions {
308 public:
309  OatDumperOptions(bool dump_raw_mapping_table,
310                   bool dump_raw_gc_map,
311                   bool dump_vmap,
312                   bool disassemble_code,
313                   bool absolute_addresses,
314                   const char* method_filter)
315    : dump_raw_mapping_table_(dump_raw_mapping_table),
316      dump_raw_gc_map_(dump_raw_gc_map),
317      dump_vmap_(dump_vmap),
318      disassemble_code_(disassemble_code),
319      absolute_addresses_(absolute_addresses),
320      method_filter_(method_filter),
321      class_loader_(nullptr) {}
322
323  const bool dump_raw_mapping_table_;
324  const bool dump_raw_gc_map_;
325  const bool dump_vmap_;
326  const bool disassemble_code_;
327  const bool absolute_addresses_;
328  const char* const method_filter_;
329  Handle<mirror::ClassLoader>* class_loader_;
330};
331
332class OatDumper {
333 public:
334  explicit OatDumper(const OatFile& oat_file, OatDumperOptions* options)
335    : oat_file_(oat_file),
336      oat_dex_files_(oat_file.GetOatDexFiles()),
337      options_(options),
338      instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
339      disassembler_(Disassembler::Create(instruction_set_,
340                                         new DisassemblerOptions(options_->absolute_addresses_,
341                                                                 oat_file.Begin(),
342                                                                 true /* can_read_litals_ */))) {
343    CHECK(options_->class_loader_ != nullptr);
344    AddAllOffsets();
345  }
346
347  ~OatDumper() {
348    delete options_;
349    delete disassembler_;
350  }
351
352  InstructionSet GetInstructionSet() {
353    return instruction_set_;
354  }
355
356  bool Dump(std::ostream& os) {
357    bool success = true;
358    const OatHeader& oat_header = oat_file_.GetOatHeader();
359
360    os << "MAGIC:\n";
361    os << oat_header.GetMagic() << "\n\n";
362
363    os << "CHECKSUM:\n";
364    os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
365
366    os << "INSTRUCTION SET:\n";
367    os << oat_header.GetInstructionSet() << "\n\n";
368
369    {
370      std::unique_ptr<const InstructionSetFeatures> features(
371          InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
372                                             oat_header.GetInstructionSetFeaturesBitmap()));
373      os << "INSTRUCTION SET FEATURES:\n";
374      os << features->GetFeatureString() << "\n\n";
375    }
376
377    os << "DEX FILE COUNT:\n";
378    os << oat_header.GetDexFileCount() << "\n\n";
379
380#define DUMP_OAT_HEADER_OFFSET(label, offset) \
381    os << label " OFFSET:\n"; \
382    os << StringPrintf("0x%08x", oat_header.offset()); \
383    if (oat_header.offset() != 0 && options_->absolute_addresses_) { \
384      os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
385    } \
386    os << StringPrintf("\n\n");
387
388    DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
389    DUMP_OAT_HEADER_OFFSET("INTERPRETER TO INTERPRETER BRIDGE",
390                           GetInterpreterToInterpreterBridgeOffset);
391    DUMP_OAT_HEADER_OFFSET("INTERPRETER TO COMPILED CODE BRIDGE",
392                           GetInterpreterToCompiledCodeBridgeOffset);
393    DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP",
394                           GetJniDlsymLookupOffset);
395    DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
396                           GetQuickGenericJniTrampolineOffset);
397    DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
398                           GetQuickImtConflictTrampolineOffset);
399    DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
400                           GetQuickResolutionTrampolineOffset);
401    DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
402                           GetQuickToInterpreterBridgeOffset);
403#undef DUMP_OAT_HEADER_OFFSET
404
405    os << "IMAGE PATCH DELTA:\n";
406    os << StringPrintf("%d (0x%08x)\n\n",
407                       oat_header.GetImagePatchDelta(),
408                       oat_header.GetImagePatchDelta());
409
410    os << "IMAGE FILE LOCATION OAT CHECKSUM:\n";
411    os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatChecksum());
412
413    os << "IMAGE FILE LOCATION OAT BEGIN:\n";
414    os << StringPrintf("0x%08x\n\n", oat_header.GetImageFileLocationOatDataBegin());
415
416    // Print the key-value store.
417    {
418      os << "KEY VALUE STORE:\n";
419      size_t index = 0;
420      const char* key;
421      const char* value;
422      while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
423        os << key << " = " << value << "\n";
424        index++;
425      }
426      os << "\n";
427    }
428
429    if (options_->absolute_addresses_) {
430      os << "BEGIN:\n";
431      os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
432
433      os << "END:\n";
434      os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
435    }
436
437    os << "SIZE:\n";
438    os << oat_file_.Size() << "\n\n";
439
440    os << std::flush;
441
442    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
443      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
444      CHECK(oat_dex_file != nullptr);
445      if (!DumpOatDexFile(os, *oat_dex_file)) {
446        success = false;
447      }
448    }
449    os << std::flush;
450    return success;
451  }
452
453  size_t ComputeSize(const void* oat_data) {
454    if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
455        reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
456      return 0;  // Address not in oat file
457    }
458    uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
459                             reinterpret_cast<uintptr_t>(oat_file_.Begin());
460    auto it = offsets_.upper_bound(begin_offset);
461    CHECK(it != offsets_.end());
462    uintptr_t end_offset = *it;
463    return end_offset - begin_offset;
464  }
465
466  InstructionSet GetOatInstructionSet() {
467    return oat_file_.GetOatHeader().GetInstructionSet();
468  }
469
470  const void* GetQuickOatCode(mirror::ArtMethod* m) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
471    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
472      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
473      CHECK(oat_dex_file != nullptr);
474      std::string error_msg;
475      std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
476      if (dex_file.get() == nullptr) {
477        LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
478            << "': " << error_msg;
479      } else {
480        const char* descriptor = m->GetDeclaringClassDescriptor();
481        const DexFile::ClassDef* class_def =
482            dex_file->FindClassDef(descriptor, ComputeModifiedUtf8Hash(descriptor));
483        if (class_def != nullptr) {
484          uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
485          const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
486          size_t method_index = m->GetMethodIndex();
487          return oat_class.GetOatMethod(method_index).GetQuickCode();
488        }
489      }
490    }
491    return nullptr;
492  }
493
494 private:
495  void AddAllOffsets() {
496    // We don't know the length of the code for each method, but we need to know where to stop
497    // when disassembling. What we do know is that a region of code will be followed by some other
498    // region, so if we keep a sorted sequence of the start of each region, we can infer the length
499    // of a piece of code by using upper_bound to find the start of the next region.
500    for (size_t i = 0; i < oat_dex_files_.size(); i++) {
501      const OatFile::OatDexFile* oat_dex_file = oat_dex_files_[i];
502      CHECK(oat_dex_file != nullptr);
503      std::string error_msg;
504      std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
505      if (dex_file.get() == nullptr) {
506        LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
507            << "': " << error_msg;
508        continue;
509      }
510      offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
511      for (size_t class_def_index = 0;
512           class_def_index < dex_file->NumClassDefs();
513           class_def_index++) {
514        const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
515        const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
516        const uint8_t* class_data = dex_file->GetClassData(class_def);
517        if (class_data != nullptr) {
518          ClassDataItemIterator it(*dex_file, class_data);
519          SkipAllFields(it);
520          uint32_t class_method_index = 0;
521          while (it.HasNextDirectMethod()) {
522            AddOffsets(oat_class.GetOatMethod(class_method_index++));
523            it.Next();
524          }
525          while (it.HasNextVirtualMethod()) {
526            AddOffsets(oat_class.GetOatMethod(class_method_index++));
527            it.Next();
528          }
529        }
530      }
531    }
532
533    // If the last thing in the file is code for a method, there won't be an offset for the "next"
534    // thing. Instead of having a special case in the upper_bound code, let's just add an entry
535    // for the end of the file.
536    offsets_.insert(oat_file_.Size());
537  }
538
539  static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
540    return maybe_thumb_offset & ~0x1;  // TODO: Make this Thumb2 specific.
541  }
542
543  void AddOffsets(const OatFile::OatMethod& oat_method) {
544    uint32_t code_offset = oat_method.GetCodeOffset();
545    if (oat_file_.GetOatHeader().GetInstructionSet() == kThumb2) {
546      code_offset &= ~0x1;
547    }
548    offsets_.insert(code_offset);
549    offsets_.insert(oat_method.GetMappingTableOffset());
550    offsets_.insert(oat_method.GetVmapTableOffset());
551    offsets_.insert(oat_method.GetGcMapOffset());
552  }
553
554  bool DumpOatDexFile(std::ostream& os, const OatFile::OatDexFile& oat_dex_file) {
555    bool success = true;
556    os << "OatDexFile:\n";
557    os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
558    os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
559
560    // Create the verifier early.
561
562    std::string error_msg;
563    std::unique_ptr<const DexFile> dex_file(oat_dex_file.OpenDexFile(&error_msg));
564    if (dex_file.get() == nullptr) {
565      os << "NOT FOUND: " << error_msg << "\n\n";
566      os << std::flush;
567      return false;
568    }
569    for (size_t class_def_index = 0;
570         class_def_index < dex_file->NumClassDefs();
571         class_def_index++) {
572      const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
573      const char* descriptor = dex_file->GetClassDescriptor(class_def);
574      uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
575      const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
576      os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
577                         class_def_index, descriptor, oat_class_offset, class_def.class_idx_)
578         << " (" << oat_class.GetStatus() << ")"
579         << " (" << oat_class.GetType() << ")\n";
580      // TODO: include bitmap here if type is kOatClassSomeCompiled?
581      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
582      std::ostream indented_os(&indent_filter);
583      if (!DumpOatClass(indented_os, oat_class, *(dex_file.get()), class_def)) {
584        success = false;
585      }
586    }
587
588    os << std::flush;
589    return success;
590  }
591
592  static void SkipAllFields(ClassDataItemIterator& it) {
593    while (it.HasNextStaticField()) {
594      it.Next();
595    }
596    while (it.HasNextInstanceField()) {
597      it.Next();
598    }
599  }
600
601  bool DumpOatClass(std::ostream& os, const OatFile::OatClass& oat_class, const DexFile& dex_file,
602                    const DexFile::ClassDef& class_def) {
603    bool success = true;
604    const uint8_t* class_data = dex_file.GetClassData(class_def);
605    if (class_data == nullptr) {  // empty class such as a marker interface?
606      os << std::flush;
607      return success;
608    }
609    ClassDataItemIterator it(dex_file, class_data);
610    SkipAllFields(it);
611    uint32_t class_method_index = 0;
612    while (it.HasNextDirectMethod()) {
613      if (!DumpOatMethod(os, class_def, class_method_index, oat_class, dex_file,
614                         it.GetMemberIndex(), it.GetMethodCodeItem(),
615                         it.GetRawMemberAccessFlags())) {
616        success = false;
617      }
618      class_method_index++;
619      it.Next();
620    }
621    while (it.HasNextVirtualMethod()) {
622      if (!DumpOatMethod(os, class_def, class_method_index, oat_class, dex_file,
623                         it.GetMemberIndex(), it.GetMethodCodeItem(),
624                         it.GetRawMemberAccessFlags())) {
625        success = false;
626      }
627      class_method_index++;
628      it.Next();
629    }
630    DCHECK(!it.HasNext());
631    os << std::flush;
632    return success;
633  }
634
635  static constexpr uint32_t kPrologueBytes = 16;
636
637  // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
638  static constexpr uint32_t kMaxCodeSize = 100 * 1000;
639
640  bool DumpOatMethod(std::ostream& os, const DexFile::ClassDef& class_def,
641                     uint32_t class_method_index,
642                     const OatFile::OatClass& oat_class, const DexFile& dex_file,
643                     uint32_t dex_method_idx, const DexFile::CodeItem* code_item,
644                     uint32_t method_access_flags) {
645    bool success = true;
646    std::string pretty_method = PrettyMethod(dex_method_idx, dex_file, true);
647    if (pretty_method.find(options_->method_filter_) == std::string::npos) {
648      return success;
649    }
650
651    os << StringPrintf("%d: %s (dex_method_idx=%d)\n",
652                       class_method_index, pretty_method.c_str(),
653                       dex_method_idx);
654    Indenter indent1_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
655    std::unique_ptr<std::ostream> indent1_os(new std::ostream(&indent1_filter));
656    Indenter indent2_filter(indent1_os->rdbuf(), kIndentChar, kIndentBy1Count);
657    std::unique_ptr<std::ostream> indent2_os(new std::ostream(&indent2_filter));
658    {
659      *indent1_os << "DEX CODE:\n";
660      DumpDexCode(*indent2_os, dex_file, code_item);
661    }
662
663    std::unique_ptr<verifier::MethodVerifier> verifier;
664    if (Runtime::Current() != nullptr) {
665      *indent1_os << "VERIFIER TYPE ANALYSIS:\n";
666      verifier.reset(DumpVerifier(*indent2_os, dex_method_idx, &dex_file, class_def, code_item,
667                                  method_access_flags));
668    }
669
670    uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
671    const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
672    const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
673    {
674      *indent1_os << "OatMethodOffsets ";
675      if (options_->absolute_addresses_) {
676        *indent1_os << StringPrintf("%p ", oat_method_offsets);
677      }
678      *indent1_os << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
679      if (oat_method_offsets_offset > oat_file_.Size()) {
680        *indent1_os << StringPrintf(
681            "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
682            oat_method_offsets_offset, oat_file_.Size());
683        // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
684        os << std::flush;
685        return false;
686      }
687
688      uint32_t code_offset = oat_method.GetCodeOffset();
689      *indent2_os << StringPrintf("code_offset: 0x%08x ", code_offset);
690      uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
691      if (aligned_code_begin > oat_file_.Size()) {
692        *indent2_os << StringPrintf("WARNING: "
693                                    "code offset 0x%08x is past end of file 0x%08zx.\n",
694                                    aligned_code_begin, oat_file_.Size());
695        success = false;
696      }
697      *indent2_os << "\n";
698
699      *indent2_os << "gc_map: ";
700      if (options_->absolute_addresses_) {
701        *indent2_os << StringPrintf("%p ", oat_method.GetGcMap());
702      }
703      uint32_t gc_map_offset = oat_method.GetGcMapOffset();
704      *indent2_os << StringPrintf("(offset=0x%08x)\n", gc_map_offset);
705      if (gc_map_offset > oat_file_.Size()) {
706        *indent2_os << StringPrintf("WARNING: "
707                                    "gc map table offset 0x%08x is past end of file 0x%08zx.\n",
708                                    gc_map_offset, oat_file_.Size());
709        success = false;
710      } else if (options_->dump_raw_gc_map_) {
711        Indenter indent3_filter(indent2_os->rdbuf(), kIndentChar, kIndentBy1Count);
712        std::ostream indent3_os(&indent3_filter);
713        DumpGcMap(indent3_os, oat_method, code_item);
714      }
715    }
716    {
717      *indent1_os << "OatQuickMethodHeader ";
718      uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
719      const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
720
721      if (options_->absolute_addresses_) {
722        *indent1_os << StringPrintf("%p ", method_header);
723      }
724      *indent1_os << StringPrintf("(offset=0x%08x)\n", method_header_offset);
725      if (method_header_offset > oat_file_.Size()) {
726        *indent1_os << StringPrintf(
727            "WARNING: oat quick method header offset 0x%08x is past end of file 0x%08zx.\n",
728            method_header_offset, oat_file_.Size());
729        // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
730        os << std::flush;
731        return false;
732      }
733
734      *indent2_os << "mapping_table: ";
735      if (options_->absolute_addresses_) {
736        *indent2_os << StringPrintf("%p ", oat_method.GetMappingTable());
737      }
738      uint32_t mapping_table_offset = oat_method.GetMappingTableOffset();
739      *indent2_os << StringPrintf("(offset=0x%08x)\n", oat_method.GetMappingTableOffset());
740      if (mapping_table_offset > oat_file_.Size()) {
741        *indent2_os << StringPrintf("WARNING: "
742                                    "mapping table offset 0x%08x is past end of file 0x%08zx. "
743                                    "mapping table offset was loaded from offset 0x%08x.\n",
744                                    mapping_table_offset, oat_file_.Size(),
745                                    oat_method.GetMappingTableOffsetOffset());
746        success = false;
747      } else if (options_->dump_raw_mapping_table_) {
748        Indenter indent3_filter(indent2_os->rdbuf(), kIndentChar, kIndentBy1Count);
749        std::ostream indent3_os(&indent3_filter);
750        DumpMappingTable(indent3_os, oat_method);
751      }
752
753      *indent2_os << "vmap_table: ";
754      if (options_->absolute_addresses_) {
755        *indent2_os << StringPrintf("%p ", oat_method.GetVmapTable());
756      }
757      uint32_t vmap_table_offset = oat_method.GetVmapTableOffset();
758      *indent2_os << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
759      if (vmap_table_offset > oat_file_.Size()) {
760        *indent2_os << StringPrintf("WARNING: "
761                                    "vmap table offset 0x%08x is past end of file 0x%08zx. "
762                                    "vmap table offset was loaded from offset 0x%08x.\n",
763                                    vmap_table_offset, oat_file_.Size(),
764                                    oat_method.GetVmapTableOffsetOffset());
765        success = false;
766      } else if (options_->dump_vmap_) {
767        DumpVmap(*indent2_os, oat_method);
768      }
769    }
770    {
771      *indent1_os << "QuickMethodFrameInfo\n";
772
773      *indent2_os << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
774      *indent2_os << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
775      DumpSpillMask(*indent2_os, oat_method.GetCoreSpillMask(), false);
776      *indent2_os << "\n";
777      *indent2_os << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
778      DumpSpillMask(*indent2_os, oat_method.GetFpSpillMask(), true);
779      *indent2_os << "\n";
780    }
781    {
782        // Based on spill masks from QuickMethodFrameInfo so placed
783        // after it is dumped, but useful for understanding quick
784        // code, so dumped here.
785        DumpVregLocations(*indent2_os, oat_method, code_item);
786    }
787    {
788      *indent1_os << "CODE: ";
789      uint32_t code_size_offset = oat_method.GetQuickCodeSizeOffset();
790      if (code_size_offset > oat_file_.Size()) {
791        *indent2_os << StringPrintf("WARNING: "
792                                    "code size offset 0x%08x is past end of file 0x%08zx.",
793                                    code_size_offset, oat_file_.Size());
794        success = false;
795      } else {
796        const void* code = oat_method.GetQuickCode();
797        uint32_t code_size = oat_method.GetQuickCodeSize();
798        uint32_t code_offset = oat_method.GetCodeOffset();
799        uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
800        uint64_t aligned_code_end = aligned_code_begin + code_size;
801
802        if (options_->absolute_addresses_) {
803          *indent1_os << StringPrintf("%p ", code);
804        }
805        *indent1_os << StringPrintf("(code_offset=0x%08x size_offset=0x%08x size=%u)%s\n",
806                                    code_offset,
807                                    code_size_offset,
808                                    code_size,
809                                    code != nullptr ? "..." : "");
810
811        if (aligned_code_begin > oat_file_.Size()) {
812          *indent2_os << StringPrintf("WARNING: "
813                                      "start of code at 0x%08x is past end of file 0x%08zx.",
814                                      aligned_code_begin, oat_file_.Size());
815          success = false;
816        } else if (aligned_code_end > oat_file_.Size()) {
817          *indent2_os << StringPrintf("WARNING: "
818                                      "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
819                                      "code size is 0x%08x loaded from offset 0x%08x.\n",
820                                      aligned_code_end, oat_file_.Size(),
821                                      code_size, code_size_offset);
822          success = false;
823          if (options_->disassemble_code_) {
824            if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
825              DumpCode(*indent2_os, verifier.get(), oat_method, code_item, true, kPrologueBytes);
826            }
827          }
828        } else if (code_size > kMaxCodeSize) {
829          *indent2_os << StringPrintf("WARNING: "
830                                      "code size %d is bigger than max expected threshold of %d. "
831                                      "code size is 0x%08x loaded from offset 0x%08x.\n",
832                                      code_size, kMaxCodeSize,
833                                      code_size, code_size_offset);
834          success = false;
835          if (options_->disassemble_code_) {
836            if (code_size_offset + kPrologueBytes <= oat_file_.Size()) {
837              DumpCode(*indent2_os, verifier.get(), oat_method, code_item, true, kPrologueBytes);
838            }
839          }
840        } else if (options_->disassemble_code_) {
841          DumpCode(*indent2_os, verifier.get(), oat_method, code_item, !success, 0);
842        }
843      }
844    }
845    os << std::flush;
846    return success;
847  }
848
849  void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
850    if (spill_mask == 0) {
851      return;
852    }
853    os << "(";
854    for (size_t i = 0; i < 32; i++) {
855      if ((spill_mask & (1 << i)) != 0) {
856        if (is_float) {
857          os << "fr" << i;
858        } else {
859          os << "r" << i;
860        }
861        spill_mask ^= 1 << i;  // clear bit
862        if (spill_mask != 0) {
863          os << ", ";
864        } else {
865          break;
866        }
867      }
868    }
869    os << ")";
870  }
871
872  void DumpVmap(std::ostream& os, const OatFile::OatMethod& oat_method) {
873    // If the native GC map is null, then this method has been compiled with the
874    // optimizing compiler. The optimizing compiler currently outputs its stack map
875    // in the vmap table, and the code below does not work with such a stack map.
876    if (oat_method.GetGcMap() == nullptr) {
877      return;
878    }
879    const uint8_t* raw_table = oat_method.GetVmapTable();
880    if (raw_table != nullptr) {
881      const VmapTable vmap_table(raw_table);
882      bool first = true;
883      bool processing_fp = false;
884      uint32_t spill_mask = oat_method.GetCoreSpillMask();
885      for (size_t i = 0; i < vmap_table.Size(); i++) {
886        uint16_t dex_reg = vmap_table[i];
887        uint32_t cpu_reg = vmap_table.ComputeRegister(spill_mask, i,
888                                                      processing_fp ? kFloatVReg : kIntVReg);
889        os << (first ? "v" : ", v")  << dex_reg;
890        if (!processing_fp) {
891          os << "/r" << cpu_reg;
892        } else {
893          os << "/fr" << cpu_reg;
894        }
895        first = false;
896        if (!processing_fp && dex_reg == 0xFFFF) {
897          processing_fp = true;
898          spill_mask = oat_method.GetFpSpillMask();
899        }
900      }
901      os << "\n";
902    }
903  }
904
905  void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
906                         const DexFile::CodeItem* code_item) {
907    if (code_item != nullptr) {
908      size_t num_locals_ins = code_item->registers_size_;
909      size_t num_ins = code_item->ins_size_;
910      size_t num_locals = num_locals_ins - num_ins;
911      size_t num_outs = code_item->outs_size_;
912
913      os << "vr_stack_locations:";
914      for (size_t reg = 0; reg <= num_locals_ins; reg++) {
915        // For readability, delimit the different kinds of VRs.
916        if (reg == num_locals_ins) {
917          os << "\n\tmethod*:";
918        } else if (reg == num_locals && num_ins > 0) {
919          os << "\n\tins:";
920        } else if (reg == 0 && num_locals > 0) {
921          os << "\n\tlocals:";
922        }
923
924        uint32_t offset = StackVisitor::GetVRegOffset(code_item, oat_method.GetCoreSpillMask(),
925                                                      oat_method.GetFpSpillMask(),
926                                                      oat_method.GetFrameSizeInBytes(), reg,
927                                                      GetInstructionSet());
928        os << " v" << reg << "[sp + #" << offset << "]";
929      }
930
931      for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
932        if (out_reg == 0) {
933          os << "\n\touts:";
934        }
935
936        uint32_t offset = StackVisitor::GetOutVROffset(out_reg, GetInstructionSet());
937        os << " v" << out_reg << "[sp + #" << offset << "]";
938      }
939
940      os << "\n";
941    }
942  }
943
944  void DescribeVReg(std::ostream& os, const OatFile::OatMethod& oat_method,
945                    const DexFile::CodeItem* code_item, size_t reg, VRegKind kind) {
946    const uint8_t* raw_table = oat_method.GetVmapTable();
947    if (raw_table != nullptr) {
948      const VmapTable vmap_table(raw_table);
949      uint32_t vmap_offset;
950      if (vmap_table.IsInContext(reg, kind, &vmap_offset)) {
951        bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
952        uint32_t spill_mask = is_float ? oat_method.GetFpSpillMask()
953                                       : oat_method.GetCoreSpillMask();
954        os << (is_float ? "fr" : "r") << vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
955      } else {
956        uint32_t offset = StackVisitor::GetVRegOffset(code_item, oat_method.GetCoreSpillMask(),
957                                                      oat_method.GetFpSpillMask(),
958                                                      oat_method.GetFrameSizeInBytes(), reg,
959                                                      GetInstructionSet());
960        os << "[sp + #" << offset << "]";
961      }
962    }
963  }
964
965  void DumpGcMapRegisters(std::ostream& os, const OatFile::OatMethod& oat_method,
966                          const DexFile::CodeItem* code_item,
967                          size_t num_regs, const uint8_t* reg_bitmap) {
968    bool first = true;
969    for (size_t reg = 0; reg < num_regs; reg++) {
970      if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
971        if (first) {
972          os << "  v" << reg << " (";
973          DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
974          os << ")";
975          first = false;
976        } else {
977          os << ", v" << reg << " (";
978          DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
979          os << ")";
980        }
981      }
982    }
983    if (first) {
984      os << "No registers in GC map\n";
985    } else {
986      os << "\n";
987    }
988  }
989  void DumpGcMap(std::ostream& os, const OatFile::OatMethod& oat_method,
990                 const DexFile::CodeItem* code_item) {
991    const uint8_t* gc_map_raw = oat_method.GetGcMap();
992    if (gc_map_raw == nullptr) {
993      return;  // No GC map.
994    }
995    const void* quick_code = oat_method.GetQuickCode();
996    NativePcOffsetToReferenceMap map(gc_map_raw);
997    for (size_t entry = 0; entry < map.NumEntries(); entry++) {
998      const uint8_t* native_pc = reinterpret_cast<const uint8_t*>(quick_code) +
999          map.GetNativePcOffset(entry);
1000      os << StringPrintf("%p", native_pc);
1001      DumpGcMapRegisters(os, oat_method, code_item, map.RegWidth() * 8, map.GetBitMap(entry));
1002    }
1003  }
1004
1005  void DumpMappingTable(std::ostream& os, const OatFile::OatMethod& oat_method) {
1006    const void* quick_code = oat_method.GetQuickCode();
1007    if (quick_code == nullptr) {
1008      return;
1009    }
1010    MappingTable table(oat_method.GetMappingTable());
1011    if (table.TotalSize() != 0) {
1012      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1013      std::ostream indent_os(&indent_filter);
1014      if (table.PcToDexSize() != 0) {
1015        typedef MappingTable::PcToDexIterator It;
1016        os << "suspend point mappings {\n";
1017        for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
1018          indent_os << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
1019        }
1020        os << "}\n";
1021      }
1022      if (table.DexToPcSize() != 0) {
1023        typedef MappingTable::DexToPcIterator It;
1024        os << "catch entry mappings {\n";
1025        for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
1026          indent_os << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
1027        }
1028        os << "}\n";
1029      }
1030    }
1031  }
1032
1033  uint32_t DumpMappingAtOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
1034                               size_t offset, bool suspend_point_mapping) {
1035    MappingTable table(oat_method.GetMappingTable());
1036    if (suspend_point_mapping && table.PcToDexSize() > 0) {
1037      typedef MappingTable::PcToDexIterator It;
1038      for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
1039        if (offset == cur.NativePcOffset()) {
1040          os << StringPrintf("suspend point dex PC: 0x%04x\n", cur.DexPc());
1041          return cur.DexPc();
1042        }
1043      }
1044    } else if (!suspend_point_mapping && table.DexToPcSize() > 0) {
1045      typedef MappingTable::DexToPcIterator It;
1046      for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
1047        if (offset == cur.NativePcOffset()) {
1048          os << StringPrintf("catch entry dex PC: 0x%04x\n", cur.DexPc());
1049          return cur.DexPc();
1050        }
1051      }
1052    }
1053    return DexFile::kDexNoIndex;
1054  }
1055
1056  void DumpGcMapAtNativePcOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
1057                                 const DexFile::CodeItem* code_item, size_t native_pc_offset) {
1058    const uint8_t* gc_map_raw = oat_method.GetGcMap();
1059    if (gc_map_raw != nullptr) {
1060      NativePcOffsetToReferenceMap map(gc_map_raw);
1061      if (map.HasEntry(native_pc_offset)) {
1062        size_t num_regs = map.RegWidth() * 8;
1063        const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset);
1064        bool first = true;
1065        for (size_t reg = 0; reg < num_regs; reg++) {
1066          if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
1067            if (first) {
1068              os << "GC map objects:  v" << reg << " (";
1069              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1070              os << ")";
1071              first = false;
1072            } else {
1073              os << ", v" << reg << " (";
1074              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1075              os << ")";
1076            }
1077          }
1078        }
1079        if (!first) {
1080          os << "\n";
1081        }
1082      }
1083    }
1084  }
1085
1086  void DumpVRegsAtDexPc(std::ostream& os, verifier::MethodVerifier* verifier,
1087                        const OatFile::OatMethod& oat_method,
1088                        const DexFile::CodeItem* code_item, uint32_t dex_pc) {
1089    DCHECK(verifier != nullptr);
1090    std::vector<int32_t> kinds = verifier->DescribeVRegs(dex_pc);
1091    bool first = true;
1092    for (size_t reg = 0; reg < code_item->registers_size_; reg++) {
1093      VRegKind kind = static_cast<VRegKind>(kinds.at(reg * 2));
1094      if (kind != kUndefined) {
1095        if (first) {
1096          os << "VRegs:  v";
1097          first = false;
1098        } else {
1099          os << ", v";
1100        }
1101        os << reg << " (";
1102        switch (kind) {
1103          case kImpreciseConstant:
1104            os << "Imprecise Constant: " << kinds.at((reg * 2) + 1) << ", ";
1105            DescribeVReg(os, oat_method, code_item, reg, kind);
1106            break;
1107          case kConstant:
1108            os << "Constant: " << kinds.at((reg * 2) + 1);
1109            break;
1110          default:
1111            DescribeVReg(os, oat_method, code_item, reg, kind);
1112            break;
1113        }
1114        os << ")";
1115      }
1116    }
1117    if (!first) {
1118      os << "\n";
1119    }
1120  }
1121
1122
1123  void DumpDexCode(std::ostream& os, const DexFile& dex_file, const DexFile::CodeItem* code_item) {
1124    if (code_item != nullptr) {
1125      size_t i = 0;
1126      while (i < code_item->insns_size_in_code_units_) {
1127        const Instruction* instruction = Instruction::At(&code_item->insns_[i]);
1128        os << StringPrintf("0x%04zx: %s\n", i, instruction->DumpString(&dex_file).c_str());
1129        i += instruction->SizeInCodeUnits();
1130      }
1131    }
1132  }
1133
1134  verifier::MethodVerifier* DumpVerifier(std::ostream& os, uint32_t dex_method_idx,
1135                                         const DexFile* dex_file,
1136                                         const DexFile::ClassDef& class_def,
1137                                         const DexFile::CodeItem* code_item,
1138                                         uint32_t method_access_flags) {
1139    if ((method_access_flags & kAccNative) == 0) {
1140      ScopedObjectAccess soa(Thread::Current());
1141      StackHandleScope<1> hs(soa.Self());
1142      Handle<mirror::DexCache> dex_cache(
1143          hs.NewHandle(Runtime::Current()->GetClassLinker()->FindDexCache(*dex_file)));
1144      DCHECK(options_->class_loader_ != nullptr);
1145      return verifier::MethodVerifier::VerifyMethodAndDump(soa.Self(), os, dex_method_idx, dex_file,
1146                                                           dex_cache,
1147                                                           *options_->class_loader_,
1148                                                           &class_def, code_item,
1149                                                           NullHandle<mirror::ArtMethod>(),
1150                                                           method_access_flags);
1151    }
1152
1153    return nullptr;
1154  }
1155
1156  void DumpCode(std::ostream& os, verifier::MethodVerifier* verifier,
1157                const OatFile::OatMethod& oat_method, const DexFile::CodeItem* code_item,
1158                bool bad_input, size_t code_size) {
1159    const void* quick_code = oat_method.GetQuickCode();
1160
1161    if (code_size == 0) {
1162      code_size = oat_method.GetQuickCodeSize();
1163    }
1164    if (code_size == 0 || quick_code == nullptr) {
1165      os << "NO CODE!\n";
1166      return;
1167    } else {
1168      const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1169      size_t offset = 0;
1170      while (offset < code_size) {
1171        if (!bad_input) {
1172          DumpMappingAtOffset(os, oat_method, offset, false);
1173        }
1174        offset += disassembler_->Dump(os, quick_native_pc + offset);
1175        if (!bad_input) {
1176          uint32_t dex_pc = DumpMappingAtOffset(os, oat_method, offset, true);
1177          if (dex_pc != DexFile::kDexNoIndex) {
1178            DumpGcMapAtNativePcOffset(os, oat_method, code_item, offset);
1179            if (verifier != nullptr) {
1180              DumpVRegsAtDexPc(os, verifier, oat_method, code_item, dex_pc);
1181            }
1182          }
1183        }
1184      }
1185    }
1186  }
1187
1188  const OatFile& oat_file_;
1189  const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
1190  const OatDumperOptions* options_;
1191  InstructionSet instruction_set_;
1192  std::set<uintptr_t> offsets_;
1193  Disassembler* disassembler_;
1194};
1195
1196class ImageDumper {
1197 public:
1198  explicit ImageDumper(std::ostream* os, gc::space::ImageSpace& image_space,
1199                       const ImageHeader& image_header, OatDumperOptions* oat_dumper_options)
1200      : os_(os),
1201        image_space_(image_space),
1202        image_header_(image_header),
1203        oat_dumper_options_(oat_dumper_options) {}
1204
1205  bool Dump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1206    std::ostream& os = *os_;
1207    os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
1208
1209    os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
1210
1211    os << "IMAGE BITMAP OFFSET: " << reinterpret_cast<void*>(image_header_.GetImageBitmapOffset())
1212       << " SIZE: " << reinterpret_cast<void*>(image_header_.GetImageBitmapSize()) << "\n\n";
1213
1214    os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
1215
1216    os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
1217
1218    os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
1219
1220    os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
1221
1222    os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
1223
1224    os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
1225
1226    os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
1227
1228    {
1229      os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
1230      Indenter indent1_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1231      std::ostream indent1_os(&indent1_filter);
1232      CHECK_EQ(arraysize(image_roots_descriptions_), size_t(ImageHeader::kImageRootsMax));
1233      for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
1234        ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
1235        const char* image_root_description = image_roots_descriptions_[i];
1236        mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
1237        indent1_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
1238        if (image_root_object->IsObjectArray()) {
1239          Indenter indent2_filter(indent1_os.rdbuf(), kIndentChar, kIndentBy1Count);
1240          std::ostream indent2_os(&indent2_filter);
1241          mirror::ObjectArray<mirror::Object>* image_root_object_array
1242              = image_root_object->AsObjectArray<mirror::Object>();
1243          for (int j = 0; j < image_root_object_array->GetLength(); j++) {
1244            mirror::Object* value = image_root_object_array->Get(j);
1245            size_t run = 0;
1246            for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
1247              if (value == image_root_object_array->Get(k)) {
1248                run++;
1249              } else {
1250                break;
1251              }
1252            }
1253            if (run == 0) {
1254              indent2_os << StringPrintf("%d: ", j);
1255            } else {
1256              indent2_os << StringPrintf("%d to %zd: ", j, j + run);
1257              j = j + run;
1258            }
1259            if (value != nullptr) {
1260              PrettyObjectValue(indent2_os, value->GetClass(), value);
1261            } else {
1262              indent2_os << j << ": null\n";
1263            }
1264          }
1265        }
1266      }
1267    }
1268    os << "\n";
1269
1270    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1271    std::string image_filename = image_space_.GetImageFilename();
1272    std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
1273    os << "OAT LOCATION: " << oat_location;
1274    os << "\n";
1275    std::string error_msg;
1276    const OatFile* oat_file = class_linker->FindOpenedOatFileFromOatLocation(oat_location);
1277    if (oat_file == nullptr) {
1278      oat_file = OatFile::Open(oat_location, oat_location, nullptr, nullptr, false, &error_msg);
1279      if (oat_file == nullptr) {
1280        os << "NOT FOUND: " << error_msg << "\n";
1281        return false;
1282      }
1283    }
1284    os << "\n";
1285
1286    stats_.oat_file_bytes = oat_file->Size();
1287
1288    oat_dumper_.reset(new OatDumper(*oat_file, oat_dumper_options_.release()));
1289
1290    for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1291      CHECK(oat_dex_file != nullptr);
1292      stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
1293                                                         oat_dex_file->FileSize()));
1294    }
1295
1296    os << "OBJECTS:\n" << std::flush;
1297
1298    // Loop through all the image spaces and dump their objects.
1299    gc::Heap* heap = Runtime::Current()->GetHeap();
1300    const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
1301    Thread* self = Thread::Current();
1302    {
1303      {
1304        WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1305        heap->FlushAllocStack();
1306      }
1307      // Since FlushAllocStack() above resets the (active) allocation
1308      // stack. Need to revoke the thread-local allocation stacks that
1309      // point into it.
1310      {
1311        self->TransitionFromRunnableToSuspended(kNative);
1312        ThreadList* thread_list = Runtime::Current()->GetThreadList();
1313        thread_list->SuspendAll();
1314        heap->RevokeAllThreadLocalAllocationStacks(self);
1315        thread_list->ResumeAll();
1316        self->TransitionFromSuspendedToRunnable();
1317      }
1318    }
1319    {
1320      std::ostream* saved_os = os_;
1321      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1322      std::ostream indent_os(&indent_filter);
1323      os_ = &indent_os;
1324      ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1325      for (const auto& space : spaces) {
1326        if (space->IsImageSpace()) {
1327          gc::space::ImageSpace* image_space = space->AsImageSpace();
1328          image_space->GetLiveBitmap()->Walk(ImageDumper::Callback, this);
1329          indent_os << "\n";
1330        }
1331      }
1332      // Dump the large objects separately.
1333      heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(ImageDumper::Callback, this);
1334      indent_os << "\n";
1335      os_ = saved_os;
1336    }
1337    os << "STATS:\n" << std::flush;
1338    std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
1339    if (file.get() == nullptr) {
1340      LOG(WARNING) << "Failed to find image in " << image_filename;
1341    }
1342    if (file.get() != nullptr) {
1343      stats_.file_bytes = file->GetLength();
1344    }
1345    size_t header_bytes = sizeof(ImageHeader);
1346    stats_.header_bytes = header_bytes;
1347    size_t alignment_bytes = RoundUp(header_bytes, kObjectAlignment) - header_bytes;
1348    stats_.alignment_bytes += alignment_bytes;
1349    stats_.alignment_bytes += image_header_.GetImageBitmapOffset() - image_header_.GetImageSize();
1350    stats_.bitmap_bytes += image_header_.GetImageBitmapSize();
1351    stats_.Dump(os);
1352    os << "\n";
1353
1354    os << std::flush;
1355
1356    return oat_dumper_->Dump(os);
1357  }
1358
1359 private:
1360  static void PrettyObjectValue(std::ostream& os, mirror::Class* type, mirror::Object* value)
1361      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1362    CHECK(type != nullptr);
1363    if (value == nullptr) {
1364      os << StringPrintf("null   %s\n", PrettyDescriptor(type).c_str());
1365    } else if (type->IsStringClass()) {
1366      mirror::String* string = value->AsString();
1367      os << StringPrintf("%p   String: %s\n", string,
1368                         PrintableString(string->ToModifiedUtf8().c_str()).c_str());
1369    } else if (type->IsClassClass()) {
1370      mirror::Class* klass = value->AsClass();
1371      os << StringPrintf("%p   Class: %s\n", klass, PrettyDescriptor(klass).c_str());
1372    } else if (type->IsArtFieldClass()) {
1373      mirror::ArtField* field = value->AsArtField();
1374      os << StringPrintf("%p   Field: %s\n", field, PrettyField(field).c_str());
1375    } else if (type->IsArtMethodClass()) {
1376      mirror::ArtMethod* method = value->AsArtMethod();
1377      os << StringPrintf("%p   Method: %s\n", method, PrettyMethod(method).c_str());
1378    } else {
1379      os << StringPrintf("%p   %s\n", value, PrettyDescriptor(type).c_str());
1380    }
1381  }
1382
1383  static void PrintField(std::ostream& os, mirror::ArtField* field, mirror::Object* obj)
1384      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1385    os << StringPrintf("%s: ", field->GetName());
1386    switch (field->GetTypeAsPrimitiveType()) {
1387      case Primitive::kPrimLong:
1388        os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
1389        break;
1390      case Primitive::kPrimDouble:
1391        os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
1392        break;
1393      case Primitive::kPrimFloat:
1394        os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
1395        break;
1396      case Primitive::kPrimInt:
1397        os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
1398        break;
1399      case Primitive::kPrimChar:
1400        os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
1401        break;
1402      case Primitive::kPrimShort:
1403        os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
1404        break;
1405      case Primitive::kPrimBoolean:
1406        os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj)? "true" : "false",
1407            field->GetBoolean(obj));
1408        break;
1409      case Primitive::kPrimByte:
1410        os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
1411        break;
1412      case Primitive::kPrimNot: {
1413        // Get the value, don't compute the type unless it is non-null as we don't want
1414        // to cause class loading.
1415        mirror::Object* value = field->GetObj(obj);
1416        if (value == nullptr) {
1417          os << StringPrintf("null   %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
1418        } else {
1419          // Grab the field type without causing resolution.
1420          mirror::Class* field_type = field->GetType(false);
1421          if (field_type != nullptr) {
1422            PrettyObjectValue(os, field_type, value);
1423          } else {
1424            os << StringPrintf("%p   %s\n", value,
1425                               PrettyDescriptor(field->GetTypeDescriptor()).c_str());
1426          }
1427        }
1428        break;
1429      }
1430      default:
1431        os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
1432        break;
1433    }
1434  }
1435
1436  static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
1437      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1438    mirror::Class* super = klass->GetSuperClass();
1439    if (super != nullptr) {
1440      DumpFields(os, obj, super);
1441    }
1442    mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
1443    if (fields != nullptr) {
1444      for (int32_t i = 0; i < fields->GetLength(); i++) {
1445        mirror::ArtField* field = fields->Get(i);
1446        PrintField(os, field, obj);
1447      }
1448    }
1449  }
1450
1451  bool InDumpSpace(const mirror::Object* object) {
1452    return image_space_.Contains(object);
1453  }
1454
1455  const void* GetQuickOatCodeBegin(mirror::ArtMethod* m)
1456      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1457    const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
1458        InstructionSetPointerSize(oat_dumper_->GetOatInstructionSet()));
1459    if (Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(quick_code)) {
1460      quick_code = oat_dumper_->GetQuickOatCode(m);
1461    }
1462    if (oat_dumper_->GetInstructionSet() == kThumb2) {
1463      quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
1464    }
1465    return quick_code;
1466  }
1467
1468  uint32_t GetQuickOatCodeSize(mirror::ArtMethod* m)
1469      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1470    const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
1471    if (oat_code_begin == nullptr) {
1472      return 0;
1473    }
1474    return oat_code_begin[-1];
1475  }
1476
1477  const void* GetQuickOatCodeEnd(mirror::ArtMethod* m)
1478      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1479    const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
1480    if (oat_code_begin == nullptr) {
1481      return nullptr;
1482    }
1483    return oat_code_begin + GetQuickOatCodeSize(m);
1484  }
1485
1486  static void Callback(mirror::Object* obj, void* arg)
1487      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1488    DCHECK(obj != nullptr);
1489    DCHECK(arg != nullptr);
1490    ImageDumper* state = reinterpret_cast<ImageDumper*>(arg);
1491    if (!state->InDumpSpace(obj)) {
1492      return;
1493    }
1494
1495    size_t object_bytes = obj->SizeOf();
1496    size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
1497    state->stats_.object_bytes += object_bytes;
1498    state->stats_.alignment_bytes += alignment_bytes;
1499
1500    std::ostream& os = *state->os_;
1501    mirror::Class* obj_class = obj->GetClass();
1502    if (obj_class->IsArrayClass()) {
1503      os << StringPrintf("%p: %s length:%d\n", obj, PrettyDescriptor(obj_class).c_str(),
1504                         obj->AsArray()->GetLength());
1505    } else if (obj->IsClass()) {
1506      mirror::Class* klass = obj->AsClass();
1507      os << StringPrintf("%p: java.lang.Class \"%s\" (", obj, PrettyDescriptor(klass).c_str())
1508         << klass->GetStatus() << ")\n";
1509    } else if (obj->IsArtField()) {
1510      os << StringPrintf("%p: java.lang.reflect.ArtField %s\n", obj,
1511                         PrettyField(obj->AsArtField()).c_str());
1512    } else if (obj->IsArtMethod()) {
1513      os << StringPrintf("%p: java.lang.reflect.ArtMethod %s\n", obj,
1514                         PrettyMethod(obj->AsArtMethod()).c_str());
1515    } else if (obj_class->IsStringClass()) {
1516      os << StringPrintf("%p: java.lang.String %s\n", obj,
1517                         PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
1518    } else {
1519      os << StringPrintf("%p: %s\n", obj, PrettyDescriptor(obj_class).c_str());
1520    }
1521    Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1522    std::ostream indent_os(&indent_filter);
1523    DumpFields(indent_os, obj, obj_class);
1524    if (obj->IsObjectArray()) {
1525      mirror::ObjectArray<mirror::Object>* obj_array = obj->AsObjectArray<mirror::Object>();
1526      int32_t length = obj_array->GetLength();
1527      for (int32_t i = 0; i < length; i++) {
1528        mirror::Object* value = obj_array->Get(i);
1529        size_t run = 0;
1530        for (int32_t j = i + 1; j < length; j++) {
1531          if (value == obj_array->Get(j)) {
1532            run++;
1533          } else {
1534            break;
1535          }
1536        }
1537        if (run == 0) {
1538          indent_os << StringPrintf("%d: ", i);
1539        } else {
1540          indent_os << StringPrintf("%d to %zd: ", i, i + run);
1541          i = i + run;
1542        }
1543        mirror::Class* value_class =
1544            (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
1545        PrettyObjectValue(indent_os, value_class, value);
1546      }
1547    } else if (obj->IsClass()) {
1548      mirror::ObjectArray<mirror::ArtField>* sfields = obj->AsClass()->GetSFields();
1549      if (sfields != nullptr) {
1550        indent_os << "STATICS:\n";
1551        Indenter indent2_filter(indent_os.rdbuf(), kIndentChar, kIndentBy1Count);
1552        std::ostream indent2_os(&indent2_filter);
1553        for (int32_t i = 0; i < sfields->GetLength(); i++) {
1554          mirror::ArtField* field = sfields->Get(i);
1555          PrintField(indent2_os, field, field->GetDeclaringClass());
1556        }
1557      }
1558    } else if (obj->IsArtMethod()) {
1559      const size_t image_pointer_size = InstructionSetPointerSize(
1560          state->oat_dumper_->GetOatInstructionSet());
1561      mirror::ArtMethod* method = obj->AsArtMethod();
1562      if (method->IsNative()) {
1563        DCHECK(method->GetNativeGcMap(image_pointer_size) == nullptr) << PrettyMethod(method);
1564        DCHECK(method->GetMappingTable(image_pointer_size) == nullptr) << PrettyMethod(method);
1565        bool first_occurrence;
1566        const void* quick_oat_code = state->GetQuickOatCodeBegin(method);
1567        uint32_t quick_oat_code_size = state->GetQuickOatCodeSize(method);
1568        state->ComputeOatSize(quick_oat_code, &first_occurrence);
1569        if (first_occurrence) {
1570          state->stats_.native_to_managed_code_bytes += quick_oat_code_size;
1571        }
1572        if (quick_oat_code != method->GetEntryPointFromQuickCompiledCodePtrSize(
1573            image_pointer_size)) {
1574          indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code);
1575        }
1576      } else if (method->IsAbstract() || method->IsCalleeSaveMethod() ||
1577          method->IsResolutionMethod() || method->IsImtConflictMethod() ||
1578          method->IsImtUnimplementedMethod() || method->IsClassInitializer()) {
1579        DCHECK(method->GetNativeGcMap(image_pointer_size) == nullptr) << PrettyMethod(method);
1580        DCHECK(method->GetMappingTable(image_pointer_size) == nullptr) << PrettyMethod(method);
1581      } else {
1582        const DexFile::CodeItem* code_item = method->GetCodeItem();
1583        size_t dex_instruction_bytes = code_item->insns_size_in_code_units_ * 2;
1584        state->stats_.dex_instruction_bytes += dex_instruction_bytes;
1585
1586        bool first_occurrence;
1587        size_t gc_map_bytes =
1588            state->ComputeOatSize(method->GetNativeGcMap(image_pointer_size), &first_occurrence);
1589        if (first_occurrence) {
1590          state->stats_.gc_map_bytes += gc_map_bytes;
1591        }
1592
1593        size_t pc_mapping_table_bytes =
1594            state->ComputeOatSize(method->GetMappingTable(image_pointer_size), &first_occurrence);
1595        if (first_occurrence) {
1596          state->stats_.pc_mapping_table_bytes += pc_mapping_table_bytes;
1597        }
1598
1599        size_t vmap_table_bytes =
1600            state->ComputeOatSize(method->GetVmapTable(image_pointer_size), &first_occurrence);
1601        if (first_occurrence) {
1602          state->stats_.vmap_table_bytes += vmap_table_bytes;
1603        }
1604
1605        const void* quick_oat_code_begin = state->GetQuickOatCodeBegin(method);
1606        const void* quick_oat_code_end = state->GetQuickOatCodeEnd(method);
1607        uint32_t quick_oat_code_size = state->GetQuickOatCodeSize(method);
1608        state->ComputeOatSize(quick_oat_code_begin, &first_occurrence);
1609        if (first_occurrence) {
1610          state->stats_.managed_code_bytes += quick_oat_code_size;
1611          if (method->IsConstructor()) {
1612            if (method->IsStatic()) {
1613              state->stats_.class_initializer_code_bytes += quick_oat_code_size;
1614            } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
1615              state->stats_.large_initializer_code_bytes += quick_oat_code_size;
1616            }
1617          } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
1618            state->stats_.large_method_code_bytes += quick_oat_code_size;
1619          }
1620        }
1621        state->stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
1622
1623        indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
1624        indent_os << StringPrintf("SIZE: Dex Instructions=%zd GC=%zd Mapping=%zd\n",
1625                                  dex_instruction_bytes, gc_map_bytes, pc_mapping_table_bytes);
1626
1627        size_t total_size = dex_instruction_bytes + gc_map_bytes + pc_mapping_table_bytes +
1628            vmap_table_bytes + quick_oat_code_size + object_bytes;
1629
1630        double expansion =
1631            static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
1632        state->stats_.ComputeOutliers(total_size, expansion, method);
1633      }
1634    }
1635    std::string temp;
1636    state->stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
1637  }
1638
1639  std::set<const void*> already_seen_;
1640  // Compute the size of the given data within the oat file and whether this is the first time
1641  // this data has been requested
1642  size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
1643    if (already_seen_.count(oat_data) == 0) {
1644      *first_occurrence = true;
1645      already_seen_.insert(oat_data);
1646    } else {
1647      *first_occurrence = false;
1648    }
1649    return oat_dumper_->ComputeSize(oat_data);
1650  }
1651
1652 public:
1653  struct Stats {
1654    size_t oat_file_bytes;
1655    size_t file_bytes;
1656
1657    size_t header_bytes;
1658    size_t object_bytes;
1659    size_t bitmap_bytes;
1660    size_t alignment_bytes;
1661
1662    size_t managed_code_bytes;
1663    size_t managed_code_bytes_ignoring_deduplication;
1664    size_t managed_to_native_code_bytes;
1665    size_t native_to_managed_code_bytes;
1666    size_t class_initializer_code_bytes;
1667    size_t large_initializer_code_bytes;
1668    size_t large_method_code_bytes;
1669
1670    size_t gc_map_bytes;
1671    size_t pc_mapping_table_bytes;
1672    size_t vmap_table_bytes;
1673
1674    size_t dex_instruction_bytes;
1675
1676    std::vector<mirror::ArtMethod*> method_outlier;
1677    std::vector<size_t> method_outlier_size;
1678    std::vector<double> method_outlier_expansion;
1679    std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
1680
1681    explicit Stats()
1682        : oat_file_bytes(0),
1683          file_bytes(0),
1684          header_bytes(0),
1685          object_bytes(0),
1686          bitmap_bytes(0),
1687          alignment_bytes(0),
1688          managed_code_bytes(0),
1689          managed_code_bytes_ignoring_deduplication(0),
1690          managed_to_native_code_bytes(0),
1691          native_to_managed_code_bytes(0),
1692          class_initializer_code_bytes(0),
1693          large_initializer_code_bytes(0),
1694          large_method_code_bytes(0),
1695          gc_map_bytes(0),
1696          pc_mapping_table_bytes(0),
1697          vmap_table_bytes(0),
1698          dex_instruction_bytes(0) {}
1699
1700    struct SizeAndCount {
1701      SizeAndCount(size_t bytes_in, size_t count_in) : bytes(bytes_in), count(count_in) {}
1702      size_t bytes;
1703      size_t count;
1704    };
1705    typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
1706    SizeAndCountTable sizes_and_counts;
1707
1708    void Update(const char* descriptor, size_t object_bytes_in) {
1709      SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
1710      if (it != sizes_and_counts.end()) {
1711        it->second.bytes += object_bytes_in;
1712        it->second.count += 1;
1713      } else {
1714        sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes_in, 1));
1715      }
1716    }
1717
1718    double PercentOfOatBytes(size_t size) {
1719      return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
1720    }
1721
1722    double PercentOfFileBytes(size_t size) {
1723      return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
1724    }
1725
1726    double PercentOfObjectBytes(size_t size) {
1727      return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
1728    }
1729
1730    void ComputeOutliers(size_t total_size, double expansion, mirror::ArtMethod* method) {
1731      method_outlier_size.push_back(total_size);
1732      method_outlier_expansion.push_back(expansion);
1733      method_outlier.push_back(method);
1734    }
1735
1736    void DumpOutliers(std::ostream& os)
1737        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1738      size_t sum_of_sizes = 0;
1739      size_t sum_of_sizes_squared = 0;
1740      size_t sum_of_expansion = 0;
1741      size_t sum_of_expansion_squared = 0;
1742      size_t n = method_outlier_size.size();
1743      for (size_t i = 0; i < n; i++) {
1744        size_t cur_size = method_outlier_size[i];
1745        sum_of_sizes += cur_size;
1746        sum_of_sizes_squared += cur_size * cur_size;
1747        double cur_expansion = method_outlier_expansion[i];
1748        sum_of_expansion += cur_expansion;
1749        sum_of_expansion_squared += cur_expansion * cur_expansion;
1750      }
1751      size_t size_mean = sum_of_sizes / n;
1752      size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
1753      double expansion_mean = sum_of_expansion / n;
1754      double expansion_variance =
1755          (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
1756
1757      // Dump methods whose size is a certain number of standard deviations from the mean
1758      size_t dumped_values = 0;
1759      size_t skipped_values = 0;
1760      for (size_t i = 100; i > 0; i--) {  // i is the current number of standard deviations
1761        size_t cur_size_variance = i * i * size_variance;
1762        bool first = true;
1763        for (size_t j = 0; j < n; j++) {
1764          size_t cur_size = method_outlier_size[j];
1765          if (cur_size > size_mean) {
1766            size_t cur_var = cur_size - size_mean;
1767            cur_var = cur_var * cur_var;
1768            if (cur_var > cur_size_variance) {
1769              if (dumped_values > 20) {
1770                if (i == 1) {
1771                  skipped_values++;
1772                } else {
1773                  i = 2;  // jump to counting for 1 standard deviation
1774                  break;
1775                }
1776              } else {
1777                if (first) {
1778                  os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
1779                  first = false;
1780                }
1781                os << PrettyMethod(method_outlier[j]) << " requires storage of "
1782                    << PrettySize(cur_size) << "\n";
1783                method_outlier_size[j] = 0;  // don't consider this method again
1784                dumped_values++;
1785              }
1786            }
1787          }
1788        }
1789      }
1790      if (skipped_values > 0) {
1791        os << "... skipped " << skipped_values
1792           << " methods with size > 1 standard deviation from the norm\n";
1793      }
1794      os << std::flush;
1795
1796      // Dump methods whose expansion is a certain number of standard deviations from the mean
1797      dumped_values = 0;
1798      skipped_values = 0;
1799      for (size_t i = 10; i > 0; i--) {  // i is the current number of standard deviations
1800        double cur_expansion_variance = i * i * expansion_variance;
1801        bool first = true;
1802        for (size_t j = 0; j < n; j++) {
1803          double cur_expansion = method_outlier_expansion[j];
1804          if (cur_expansion > expansion_mean) {
1805            size_t cur_var = cur_expansion - expansion_mean;
1806            cur_var = cur_var * cur_var;
1807            if (cur_var > cur_expansion_variance) {
1808              if (dumped_values > 20) {
1809                if (i == 1) {
1810                  skipped_values++;
1811                } else {
1812                  i = 2;  // jump to counting for 1 standard deviation
1813                  break;
1814                }
1815              } else {
1816                if (first) {
1817                  os << "\nLarge expansion methods (size > " << i
1818                      << " standard deviations the norm):\n";
1819                  first = false;
1820                }
1821                os << PrettyMethod(method_outlier[j]) << " expanded code by "
1822                   << cur_expansion << "\n";
1823                method_outlier_expansion[j] = 0.0;  // don't consider this method again
1824                dumped_values++;
1825              }
1826            }
1827          }
1828        }
1829      }
1830      if (skipped_values > 0) {
1831        os << "... skipped " << skipped_values
1832           << " methods with expansion > 1 standard deviation from the norm\n";
1833      }
1834      os << "\n" << std::flush;
1835    }
1836
1837    void Dump(std::ostream& os) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1838      {
1839        os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
1840           << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
1841        Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1842        std::ostream indent_os(&indent_filter);
1843        indent_os << StringPrintf("header_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
1844                                  "object_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
1845                                  "bitmap_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
1846                                  "alignment_bytes =  %8zd (%2.0f%% of art file bytes)\n\n",
1847                                  header_bytes, PercentOfFileBytes(header_bytes),
1848                                  object_bytes, PercentOfFileBytes(object_bytes),
1849                                  bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
1850                                  alignment_bytes, PercentOfFileBytes(alignment_bytes))
1851            << std::flush;
1852        CHECK_EQ(file_bytes, bitmap_bytes + header_bytes + object_bytes + alignment_bytes);
1853      }
1854
1855      os << "object_bytes breakdown:\n";
1856      size_t object_bytes_total = 0;
1857      for (const auto& sizes_and_count : sizes_and_counts) {
1858        const std::string& descriptor(sizes_and_count.first);
1859        double average = static_cast<double>(sizes_and_count.second.bytes) /
1860            static_cast<double>(sizes_and_count.second.count);
1861        double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
1862        os << StringPrintf("%32s %8zd bytes %6zd instances "
1863                           "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
1864                           descriptor.c_str(), sizes_and_count.second.bytes,
1865                           sizes_and_count.second.count, average, percent);
1866        object_bytes_total += sizes_and_count.second.bytes;
1867      }
1868      os << "\n" << std::flush;
1869      CHECK_EQ(object_bytes, object_bytes_total);
1870
1871      os << StringPrintf("oat_file_bytes               = %8zd\n"
1872                         "managed_code_bytes           = %8zd (%2.0f%% of oat file bytes)\n"
1873                         "managed_to_native_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
1874                         "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
1875                         "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
1876                         "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
1877                         "large_method_code_bytes      = %8zd (%2.0f%% of oat file bytes)\n\n",
1878                         oat_file_bytes,
1879                         managed_code_bytes,
1880                         PercentOfOatBytes(managed_code_bytes),
1881                         managed_to_native_code_bytes,
1882                         PercentOfOatBytes(managed_to_native_code_bytes),
1883                         native_to_managed_code_bytes,
1884                         PercentOfOatBytes(native_to_managed_code_bytes),
1885                         class_initializer_code_bytes,
1886                         PercentOfOatBytes(class_initializer_code_bytes),
1887                         large_initializer_code_bytes,
1888                         PercentOfOatBytes(large_initializer_code_bytes),
1889                         large_method_code_bytes,
1890                         PercentOfOatBytes(large_method_code_bytes))
1891            << "DexFile sizes:\n";
1892      for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
1893        os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
1894                           oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
1895                           PercentOfOatBytes(oat_dex_file_size.second));
1896      }
1897
1898      os << "\n" << StringPrintf("gc_map_bytes           = %7zd (%2.0f%% of oat file bytes)\n"
1899                                 "pc_mapping_table_bytes = %7zd (%2.0f%% of oat file bytes)\n"
1900                                 "vmap_table_bytes       = %7zd (%2.0f%% of oat file bytes)\n\n",
1901                                 gc_map_bytes, PercentOfOatBytes(gc_map_bytes),
1902                                 pc_mapping_table_bytes, PercentOfOatBytes(pc_mapping_table_bytes),
1903                                 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
1904         << std::flush;
1905
1906      os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
1907         << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
1908                         static_cast<double>(managed_code_bytes) /
1909                             static_cast<double>(dex_instruction_bytes),
1910                         static_cast<double>(managed_code_bytes_ignoring_deduplication) /
1911                             static_cast<double>(dex_instruction_bytes))
1912         << std::flush;
1913
1914      DumpOutliers(os);
1915    }
1916  } stats_;
1917
1918 private:
1919  enum {
1920    // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
1921    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
1922    kLargeConstructorDexBytes = 4000,
1923    // Number of bytes for a method to be considered large. Based on the 4000 basic block
1924    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
1925    kLargeMethodDexBytes = 16000
1926  };
1927  std::ostream* os_;
1928  gc::space::ImageSpace& image_space_;
1929  const ImageHeader& image_header_;
1930  std::unique_ptr<OatDumper> oat_dumper_;
1931  std::unique_ptr<OatDumperOptions> oat_dumper_options_;
1932
1933  DISALLOW_COPY_AND_ASSIGN(ImageDumper);
1934};
1935
1936static int DumpImage(Runtime* runtime, const char* image_location, OatDumperOptions* options,
1937                     std::ostream* os) {
1938  // Dumping the image, no explicit class loader.
1939  NullHandle<mirror::ClassLoader> null_class_loader;
1940  options->class_loader_ = &null_class_loader;
1941
1942  ScopedObjectAccess soa(Thread::Current());
1943  gc::Heap* heap = runtime->GetHeap();
1944  gc::space::ImageSpace* image_space = heap->GetImageSpace();
1945  CHECK(image_space != nullptr);
1946  const ImageHeader& image_header = image_space->GetImageHeader();
1947  if (!image_header.IsValid()) {
1948    fprintf(stderr, "Invalid image header %s\n", image_location);
1949    return EXIT_FAILURE;
1950  }
1951
1952  ImageDumper image_dumper(os, *image_space, image_header, options);
1953
1954  bool success = image_dumper.Dump();
1955  return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
1956}
1957
1958static int DumpOatWithRuntime(Runtime* runtime, OatFile* oat_file, OatDumperOptions* options,
1959                              std::ostream* os) {
1960  CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
1961
1962  Thread* self = Thread::Current();
1963  CHECK(self != nullptr);
1964  // Need well-known-classes.
1965  WellKnownClasses::Init(self->GetJniEnv());
1966
1967  // Need to register dex files to get a working dex cache.
1968  ScopedObjectAccess soa(self);
1969  ClassLinker* class_linker = runtime->GetClassLinker();
1970  class_linker->RegisterOatFile(oat_file);
1971  std::vector<const DexFile*> dex_files;
1972  for (const OatFile::OatDexFile* odf : oat_file->GetOatDexFiles()) {
1973    std::string error_msg;
1974    const DexFile* dex_file = odf->OpenDexFile(&error_msg);
1975    CHECK(dex_file != nullptr) << error_msg;
1976    class_linker->RegisterDexFile(*dex_file);
1977    dex_files.push_back(dex_file);
1978  }
1979
1980  // Need a class loader.
1981  soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1982  ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1983      soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1984  jobject class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1985  // Fake that we're a compiler.
1986  runtime->SetCompileTimeClassPath(class_loader, dex_files);
1987
1988  // Use the class loader while dumping.
1989  StackHandleScope<1> scope(self);
1990  Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
1991      soa.Decode<mirror::ClassLoader*>(class_loader));
1992  options->class_loader_ = &loader_handle;
1993
1994  OatDumper oat_dumper(*oat_file, options);
1995  bool success = oat_dumper.Dump(*os);
1996  return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
1997}
1998
1999static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
2000  // No image = no class loader.
2001  NullHandle<mirror::ClassLoader> null_class_loader;
2002  options->class_loader_ = &null_class_loader;
2003
2004  OatDumper oat_dumper(*oat_file, options);
2005  bool success = oat_dumper.Dump(*os);
2006  return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2007}
2008
2009static int DumpOat(Runtime* runtime, const char* oat_filename, OatDumperOptions* options,
2010                   std::ostream* os) {
2011  std::string error_msg;
2012  OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, nullptr, nullptr, false,
2013                                    &error_msg);
2014  if (oat_file == nullptr) {
2015    fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
2016    return EXIT_FAILURE;
2017  }
2018
2019  if (runtime != nullptr) {
2020    return DumpOatWithRuntime(runtime, oat_file, options, os);
2021  } else {
2022    return DumpOatWithoutRuntime(oat_file, options, os);
2023  }
2024}
2025
2026static int SymbolizeOat(const char* oat_filename, std::string& output_name) {
2027  std::string error_msg;
2028  OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, nullptr, nullptr, false,
2029                                    &error_msg);
2030  if (oat_file == nullptr) {
2031    fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
2032    return EXIT_FAILURE;
2033  }
2034
2035  OatSymbolizer oat_symbolizer(oat_file, output_name);
2036  if (!oat_symbolizer.Init()) {
2037    fprintf(stderr, "Failed to initialize symbolizer\n");
2038    return EXIT_FAILURE;
2039  }
2040  if (!oat_symbolizer.Symbolize()) {
2041    fprintf(stderr, "Failed to symbolize\n");
2042    return EXIT_FAILURE;
2043  }
2044
2045  return EXIT_SUCCESS;
2046}
2047
2048struct OatdumpArgs : public CmdlineArgs {
2049 protected:
2050  using Base = CmdlineArgs;
2051
2052  virtual ParseStatus ParseCustom(const StringPiece& option,
2053                                  std::string* error_msg) OVERRIDE {
2054    {
2055      ParseStatus base_parse = Base::ParseCustom(option, error_msg);
2056      if (base_parse != kParseUnknownArgument) {
2057        return base_parse;
2058      }
2059    }
2060
2061    if (option.starts_with("--oat-file=")) {
2062      oat_filename_ = option.substr(strlen("--oat-file=")).data();
2063    } else if (option.starts_with("--image=")) {
2064      image_location_ = option.substr(strlen("--image=")).data();
2065    } else if (option =="--dump:raw_mapping_table") {
2066      dump_raw_mapping_table_ = true;
2067    } else if (option == "--dump:raw_gc_map") {
2068      dump_raw_gc_map_ = true;
2069    } else if (option == "--no-dump:vmap") {
2070      dump_vmap_ = false;
2071    } else if (option == "--no-disassemble") {
2072      disassemble_code_ = false;
2073    } else if (option.starts_with("--symbolize=")) {
2074      oat_filename_ = option.substr(strlen("--symbolize=")).data();
2075      symbolize_ = true;
2076    } else if (option.starts_with("--method-filter=")) {
2077      method_filter_ = option.substr(strlen("--method-filter=")).data();
2078    } else {
2079      return kParseUnknownArgument;
2080    }
2081
2082    return kParseOk;
2083  }
2084
2085  virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
2086    // Infer boot image location from the image location if possible.
2087    if (boot_image_location_ == nullptr) {
2088      boot_image_location_ = image_location_;
2089    }
2090
2091    // Perform the parent checks.
2092    ParseStatus parent_checks = Base::ParseChecks(error_msg);
2093    if (parent_checks != kParseOk) {
2094      return parent_checks;
2095    }
2096
2097    // Perform our own checks.
2098    if (image_location_ == nullptr && oat_filename_ == nullptr) {
2099      *error_msg = "Either --image or --oat-file must be specified";
2100      return kParseError;
2101    } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
2102      *error_msg = "Either --image or --oat-file must be specified but not both";
2103      return kParseError;
2104    }
2105
2106    return kParseOk;
2107  }
2108
2109  virtual std::string GetUsage() const {
2110    std::string usage;
2111
2112    usage +=
2113        "Usage: oatdump [options] ...\n"
2114        "    Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
2115        "    Example: adb shell oatdump --image=/system/framework/boot.art\n"
2116        "\n"
2117        // Either oat-file or image is required.
2118        "  --oat-file=<file.oat>: specifies an input oat filename.\n"
2119        "      Example: --oat-file=/system/framework/boot.oat\n"
2120        "\n"
2121        "  --image=<file.art>: specifies an input image location.\n"
2122        "      Example: --image=/system/framework/boot.art\n"
2123        "\n";
2124
2125    usage += Base::GetUsage();
2126
2127    usage +=  // Optional.
2128        "  --dump:raw_mapping_table enables dumping of the mapping table.\n"
2129        "      Example: --dump:raw_mapping_table\n"
2130        "\n"
2131        "  --dump:raw_mapping_table enables dumping of the GC map.\n"
2132        "      Example: --dump:raw_gc_map\n"
2133        "\n"
2134        "  --no-dump:vmap may be used to disable vmap dumping.\n"
2135        "      Example: --no-dump:vmap\n"
2136        "\n"
2137        "  --no-disassemble may be used to disable disassembly.\n"
2138        "      Example: --no-disassemble\n"
2139        "\n"
2140        "  --method-filter=<method name>: only dumps methods that contain the filter.\n"
2141        "      Example: --method-filter=foo\n"
2142        "\n";
2143
2144    return usage;
2145  }
2146
2147 public:
2148  const char* oat_filename_ = nullptr;
2149  const char* method_filter_ = "";
2150  const char* image_location_ = nullptr;
2151  std::string elf_filename_prefix_;
2152  bool dump_raw_mapping_table_ = false;
2153  bool dump_raw_gc_map_ = false;
2154  bool dump_vmap_ = true;
2155  bool disassemble_code_ = true;
2156  bool symbolize_ = false;
2157};
2158
2159struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
2160  virtual bool NeedsRuntime() OVERRIDE {
2161    CHECK(args_ != nullptr);
2162
2163    // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
2164    bool absolute_addresses = (args_->oat_filename_ == nullptr);
2165
2166    oat_dumper_options_ = std::unique_ptr<OatDumperOptions>(new OatDumperOptions(
2167        args_->dump_raw_mapping_table_,
2168        args_->dump_raw_gc_map_,
2169        args_->dump_vmap_,
2170        args_->disassemble_code_,
2171        absolute_addresses,
2172        args_->method_filter_));
2173
2174    return (args_->boot_image_location_ != nullptr || args_->image_location_ != nullptr) &&
2175          !args_->symbolize_;
2176  }
2177
2178  virtual bool ExecuteWithoutRuntime() OVERRIDE {
2179    CHECK(args_ != nullptr);
2180    CHECK(args_->symbolize_);
2181
2182    MemMap::Init();
2183
2184    return SymbolizeOat(args_->oat_filename_, args_->output_name_) == EXIT_SUCCESS;
2185  }
2186
2187  virtual bool ExecuteWithRuntime(Runtime* runtime) {
2188    CHECK(args_ != nullptr);
2189
2190    if (args_->oat_filename_ != nullptr) {
2191      return DumpOat(runtime,
2192                     args_->oat_filename_,
2193                     oat_dumper_options_.release(),
2194                     args_->os_) == EXIT_SUCCESS;
2195    }
2196
2197    return DumpImage(runtime, args_->image_location_, oat_dumper_options_.release(), args_->os_)
2198      == EXIT_SUCCESS;
2199  }
2200
2201  std::unique_ptr<OatDumperOptions> oat_dumper_options_;
2202};
2203
2204}  // namespace art
2205
2206int main(int argc, char** argv) {
2207  art::OatdumpMain main;
2208  return main.Main(argc, argv);
2209}
2210