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