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