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