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