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