oatdump.cc revision 0c5bbc11a6af7b4f83b3929bc99de690635095c0
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19
20#include <fstream>
21#include <iostream>
22#include <map>
23#include <set>
24#include <string>
25#include <unordered_map>
26#include <vector>
27
28#include "arch/instruction_set_features.h"
29#include "art_field-inl.h"
30#include "base/unix_file/fd_file.h"
31#include "class_linker.h"
32#include "class_linker-inl.h"
33#include "dex_file-inl.h"
34#include "dex_instruction.h"
35#include "disassembler.h"
36#include "elf_builder.h"
37#include "gc_map.h"
38#include "gc/space/image_space.h"
39#include "gc/space/large_object_space.h"
40#include "gc/space/space-inl.h"
41#include "image.h"
42#include "indenter.h"
43#include "mapping_table.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    uint32_t oat_bss_size = oat_file_->BssSize();
92
93    elf_output_ = OS::CreateEmptyFile(output_name_.c_str());
94
95    builder_.reset(new ElfBuilder<ElfTypes32>(
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        RoundUp(oat_data_size + oat_exec_size, kPageSize),
104        oat_bss_size,
105        true,
106        false));
107
108    if (!builder_->Init()) {
109      builder_.reset(nullptr);
110      return false;
111    }
112
113    return true;
114  }
115
116  typedef void (OatSymbolizer::*Callback)(const DexFile::ClassDef&,
117                                          uint32_t,
118                                          const OatFile::OatMethod&,
119                                          const DexFile&,
120                                          uint32_t,
121                                          const DexFile::CodeItem*,
122                                          uint32_t);
123
124  bool Symbolize() {
125    if (builder_.get() == nullptr) {
126      return false;
127    }
128
129    Walk(&art::OatSymbolizer::RegisterForDedup);
130
131    NormalizeState();
132
133    Walk(&art::OatSymbolizer::AddSymbol);
134
135    bool result = builder_->Write();
136
137    // Ignore I/O errors.
138    UNUSED(elf_output_->FlushClose());
139
140    return result;
141  }
142
143  void Walk(Callback callback) {
144    std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
145    for (size_t i = 0; i < oat_dex_files.size(); i++) {
146      const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
147      CHECK(oat_dex_file != nullptr);
148      WalkOatDexFile(oat_dex_file, callback);
149    }
150  }
151
152  void WalkOatDexFile(const OatFile::OatDexFile* oat_dex_file, Callback callback) {
153    std::string error_msg;
154    std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(&error_msg));
155    if (dex_file.get() == nullptr) {
156      return;
157    }
158    for (size_t class_def_index = 0;
159        class_def_index < dex_file->NumClassDefs();
160        class_def_index++) {
161      const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
162      const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
163      OatClassType type = oat_class.GetType();
164      switch (type) {
165        case kOatClassAllCompiled:
166        case kOatClassSomeCompiled:
167          WalkOatClass(oat_class, *dex_file.get(), class_def, callback);
168          break;
169
170        case kOatClassNoneCompiled:
171        case kOatClassMax:
172          // Ignore.
173          break;
174      }
175    }
176  }
177
178  void WalkOatClass(const OatFile::OatClass& oat_class, const DexFile& dex_file,
179                    const DexFile::ClassDef& class_def, Callback callback) {
180    const uint8_t* class_data = dex_file.GetClassData(class_def);
181    if (class_data == nullptr) {  // empty class such as a marker interface?
182      return;
183    }
184    // Note: even if this is an interface or a native class, we still have to walk it, as there
185    //       might be a static initializer.
186    ClassDataItemIterator it(dex_file, class_data);
187    SkipAllFields(&it);
188    uint32_t class_method_idx = 0;
189    while (it.HasNextDirectMethod()) {
190      const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_idx);
191      WalkOatMethod(class_def, class_method_idx, oat_method, dex_file, it.GetMemberIndex(),
192                    it.GetMethodCodeItem(), it.GetMethodAccessFlags(), callback);
193      class_method_idx++;
194      it.Next();
195    }
196    while (it.HasNextVirtualMethod()) {
197      const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_idx);
198      WalkOatMethod(class_def, class_method_idx, oat_method, dex_file, it.GetMemberIndex(),
199                    it.GetMethodCodeItem(), it.GetMethodAccessFlags(), callback);
200      class_method_idx++;
201      it.Next();
202    }
203    DCHECK(!it.HasNext());
204  }
205
206  void WalkOatMethod(const DexFile::ClassDef& class_def, uint32_t class_method_index,
207                     const OatFile::OatMethod& oat_method, const DexFile& dex_file,
208                     uint32_t dex_method_idx, const DexFile::CodeItem* code_item,
209                     uint32_t method_access_flags, Callback callback) {
210    if ((method_access_flags & kAccAbstract) != 0) {
211      // Abstract method, no code.
212      return;
213    }
214    if (oat_method.GetCodeOffset() == 0) {
215      // No code.
216      return;
217    }
218
219    (this->*callback)(class_def, class_method_index, oat_method, dex_file, dex_method_idx, code_item,
220                      method_access_flags);
221  }
222
223  void RegisterForDedup(const DexFile::ClassDef& class_def ATTRIBUTE_UNUSED,
224                        uint32_t class_method_index ATTRIBUTE_UNUSED,
225                        const OatFile::OatMethod& oat_method,
226                        const DexFile& dex_file ATTRIBUTE_UNUSED,
227                        uint32_t dex_method_idx ATTRIBUTE_UNUSED,
228                        const DexFile::CodeItem* code_item ATTRIBUTE_UNUSED,
229                        uint32_t method_access_flags ATTRIBUTE_UNUSED) {
230    state_[oat_method.GetCodeOffset()]++;
231  }
232
233  void NormalizeState() {
234    for (auto& x : state_) {
235      if (x.second == 1) {
236        state_[x.first] = 0;
237      }
238    }
239  }
240
241  enum class DedupState {  // private
242    kNotDeduplicated,
243    kDeduplicatedFirst,
244    kDeduplicatedOther
245  };
246  DedupState IsDuplicated(uint32_t offset) {
247    if (state_[offset] == 0) {
248      return DedupState::kNotDeduplicated;
249    }
250    if (state_[offset] == 1) {
251      return DedupState::kDeduplicatedOther;
252    }
253    state_[offset] = 1;
254    return DedupState::kDeduplicatedFirst;
255  }
256
257  void AddSymbol(const DexFile::ClassDef& class_def ATTRIBUTE_UNUSED,
258                 uint32_t class_method_index ATTRIBUTE_UNUSED,
259                 const OatFile::OatMethod& oat_method,
260                 const DexFile& dex_file,
261                 uint32_t dex_method_idx,
262                 const DexFile::CodeItem* code_item ATTRIBUTE_UNUSED,
263                 uint32_t method_access_flags ATTRIBUTE_UNUSED) {
264    DedupState dedup = IsDuplicated(oat_method.GetCodeOffset());
265    if (dedup != DedupState::kDeduplicatedOther) {
266      std::string pretty_name = PrettyMethod(dex_method_idx, dex_file, true);
267
268      if (dedup == DedupState::kDeduplicatedFirst) {
269        pretty_name = "[Dedup]" + pretty_name;
270      }
271
272      auto* symtab = builder_->GetSymtabBuilder();
273
274      symtab->AddSymbol(pretty_name, &builder_->GetTextBuilder(),
275          oat_method.GetCodeOffset() - oat_file_->GetOatHeader().GetExecutableOffset(),
276          true, oat_method.GetQuickCodeSize(), STB_GLOBAL, STT_FUNC);
277    }
278  }
279
280  // Set oat data offset. Required by ElfBuilder/CodeOutput.
281  void SetCodeOffset(size_t offset ATTRIBUTE_UNUSED) {
282    // Nothing to do.
283  }
284
285  // Write oat code. Required by ElfBuilder/CodeOutput.
286  bool Write(OutputStream* out) {
287    return out->WriteFully(oat_file_->Begin(), oat_file_->End() - oat_file_->Begin());
288  }
289
290 private:
291  static void SkipAllFields(ClassDataItemIterator* it) {
292    while (it->HasNextStaticField()) {
293      it->Next();
294    }
295    while (it->HasNextInstanceField()) {
296      it->Next();
297    }
298  }
299
300  const OatFile* oat_file_;
301  std::unique_ptr<ElfBuilder<ElfTypes32> > 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    code_info.Dump(os, code_item.registers_size_);
1044  }
1045
1046  // Display a vmap table.
1047  void DumpVmapTable(std::ostream& os,
1048                     const OatFile::OatMethod& oat_method,
1049                     const VmapTable& vmap_table) {
1050    bool first = true;
1051    bool processing_fp = false;
1052    uint32_t spill_mask = oat_method.GetCoreSpillMask();
1053    for (size_t i = 0; i < vmap_table.Size(); i++) {
1054      uint16_t dex_reg = vmap_table[i];
1055      uint32_t cpu_reg = vmap_table.ComputeRegister(spill_mask, i,
1056                                                    processing_fp ? kFloatVReg : kIntVReg);
1057      os << (first ? "v" : ", v")  << dex_reg;
1058      if (!processing_fp) {
1059        os << "/r" << cpu_reg;
1060      } else {
1061        os << "/fr" << cpu_reg;
1062      }
1063      first = false;
1064      if (!processing_fp && dex_reg == 0xFFFF) {
1065        processing_fp = true;
1066        spill_mask = oat_method.GetFpSpillMask();
1067      }
1068    }
1069    os << "\n";
1070  }
1071
1072  void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
1073                         const DexFile::CodeItem* code_item) {
1074    if (code_item != nullptr) {
1075      size_t num_locals_ins = code_item->registers_size_;
1076      size_t num_ins = code_item->ins_size_;
1077      size_t num_locals = num_locals_ins - num_ins;
1078      size_t num_outs = code_item->outs_size_;
1079
1080      os << "vr_stack_locations:";
1081      for (size_t reg = 0; reg <= num_locals_ins; reg++) {
1082        // For readability, delimit the different kinds of VRs.
1083        if (reg == num_locals_ins) {
1084          os << "\n\tmethod*:";
1085        } else if (reg == num_locals && num_ins > 0) {
1086          os << "\n\tins:";
1087        } else if (reg == 0 && num_locals > 0) {
1088          os << "\n\tlocals:";
1089        }
1090
1091        uint32_t offset = StackVisitor::GetVRegOffsetFromQuickCode(
1092            code_item,
1093            oat_method.GetCoreSpillMask(),
1094            oat_method.GetFpSpillMask(),
1095            oat_method.GetFrameSizeInBytes(),
1096            reg,
1097            GetInstructionSet());
1098        os << " v" << reg << "[sp + #" << offset << "]";
1099      }
1100
1101      for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
1102        if (out_reg == 0) {
1103          os << "\n\touts:";
1104        }
1105
1106        uint32_t offset = StackVisitor::GetOutVROffset(out_reg, GetInstructionSet());
1107        os << " v" << out_reg << "[sp + #" << offset << "]";
1108      }
1109
1110      os << "\n";
1111    }
1112  }
1113
1114  void DescribeVReg(std::ostream& os, const OatFile::OatMethod& oat_method,
1115                    const DexFile::CodeItem* code_item, size_t reg, VRegKind kind) {
1116    const uint8_t* raw_table = oat_method.GetVmapTable();
1117    if (raw_table != nullptr) {
1118      const VmapTable vmap_table(raw_table);
1119      uint32_t vmap_offset;
1120      if (vmap_table.IsInContext(reg, kind, &vmap_offset)) {
1121        bool is_float = (kind == kFloatVReg) || (kind == kDoubleLoVReg) || (kind == kDoubleHiVReg);
1122        uint32_t spill_mask = is_float ? oat_method.GetFpSpillMask()
1123                                       : oat_method.GetCoreSpillMask();
1124        os << (is_float ? "fr" : "r") << vmap_table.ComputeRegister(spill_mask, vmap_offset, kind);
1125      } else {
1126        uint32_t offset = StackVisitor::GetVRegOffsetFromQuickCode(
1127            code_item,
1128            oat_method.GetCoreSpillMask(),
1129            oat_method.GetFpSpillMask(),
1130            oat_method.GetFrameSizeInBytes(),
1131            reg,
1132            GetInstructionSet());
1133        os << "[sp + #" << offset << "]";
1134      }
1135    }
1136  }
1137
1138  void DumpGcMapRegisters(std::ostream& os, const OatFile::OatMethod& oat_method,
1139                          const DexFile::CodeItem* code_item,
1140                          size_t num_regs, const uint8_t* reg_bitmap) {
1141    bool first = true;
1142    for (size_t reg = 0; reg < num_regs; reg++) {
1143      if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
1144        if (first) {
1145          os << "  v" << reg << " (";
1146          DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1147          os << ")";
1148          first = false;
1149        } else {
1150          os << ", v" << reg << " (";
1151          DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1152          os << ")";
1153        }
1154      }
1155    }
1156    if (first) {
1157      os << "No registers in GC map\n";
1158    } else {
1159      os << "\n";
1160    }
1161  }
1162  void DumpGcMap(std::ostream& os, const OatFile::OatMethod& oat_method,
1163                 const DexFile::CodeItem* code_item) {
1164    const uint8_t* gc_map_raw = oat_method.GetGcMap();
1165    if (gc_map_raw == nullptr) {
1166      return;  // No GC map.
1167    }
1168    const void* quick_code = oat_method.GetQuickCode();
1169    NativePcOffsetToReferenceMap map(gc_map_raw);
1170    for (size_t entry = 0; entry < map.NumEntries(); entry++) {
1171      const uint8_t* native_pc = reinterpret_cast<const uint8_t*>(quick_code) +
1172          map.GetNativePcOffset(entry);
1173      os << StringPrintf("%p", native_pc);
1174      DumpGcMapRegisters(os, oat_method, code_item, map.RegWidth() * 8, map.GetBitMap(entry));
1175    }
1176  }
1177
1178  void DumpMappingTable(std::ostream& os, const OatFile::OatMethod& oat_method) {
1179    const void* quick_code = oat_method.GetQuickCode();
1180    if (quick_code == nullptr) {
1181      return;
1182    }
1183    MappingTable table(oat_method.GetMappingTable());
1184    if (table.TotalSize() != 0) {
1185      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1186      std::ostream indent_os(&indent_filter);
1187      if (table.PcToDexSize() != 0) {
1188        typedef MappingTable::PcToDexIterator It;
1189        os << "suspend point mappings {\n";
1190        for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
1191          indent_os << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
1192        }
1193        os << "}\n";
1194      }
1195      if (table.DexToPcSize() != 0) {
1196        typedef MappingTable::DexToPcIterator It;
1197        os << "catch entry mappings {\n";
1198        for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
1199          indent_os << StringPrintf("0x%04x -> 0x%04x\n", cur.NativePcOffset(), cur.DexPc());
1200        }
1201        os << "}\n";
1202      }
1203    }
1204  }
1205
1206  uint32_t DumpMappingAtOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
1207                               size_t offset, bool suspend_point_mapping) {
1208    MappingTable table(oat_method.GetMappingTable());
1209    if (suspend_point_mapping && table.PcToDexSize() > 0) {
1210      typedef MappingTable::PcToDexIterator It;
1211      for (It cur = table.PcToDexBegin(), end = table.PcToDexEnd(); cur != end; ++cur) {
1212        if (offset == cur.NativePcOffset()) {
1213          os << StringPrintf("suspend point dex PC: 0x%04x\n", cur.DexPc());
1214          return cur.DexPc();
1215        }
1216      }
1217    } else if (!suspend_point_mapping && table.DexToPcSize() > 0) {
1218      typedef MappingTable::DexToPcIterator It;
1219      for (It cur = table.DexToPcBegin(), end = table.DexToPcEnd(); cur != end; ++cur) {
1220        if (offset == cur.NativePcOffset()) {
1221          os << StringPrintf("catch entry dex PC: 0x%04x\n", cur.DexPc());
1222          return cur.DexPc();
1223        }
1224      }
1225    }
1226    return DexFile::kDexNoIndex;
1227  }
1228
1229  void DumpGcMapAtNativePcOffset(std::ostream& os, const OatFile::OatMethod& oat_method,
1230                                 const DexFile::CodeItem* code_item, size_t native_pc_offset) {
1231    const uint8_t* gc_map_raw = oat_method.GetGcMap();
1232    if (gc_map_raw != nullptr) {
1233      NativePcOffsetToReferenceMap map(gc_map_raw);
1234      if (map.HasEntry(native_pc_offset)) {
1235        size_t num_regs = map.RegWidth() * 8;
1236        const uint8_t* reg_bitmap = map.FindBitMap(native_pc_offset);
1237        bool first = true;
1238        for (size_t reg = 0; reg < num_regs; reg++) {
1239          if (((reg_bitmap[reg / 8] >> (reg % 8)) & 0x01) != 0) {
1240            if (first) {
1241              os << "GC map objects:  v" << reg << " (";
1242              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1243              os << ")";
1244              first = false;
1245            } else {
1246              os << ", v" << reg << " (";
1247              DescribeVReg(os, oat_method, code_item, reg, kReferenceVReg);
1248              os << ")";
1249            }
1250          }
1251        }
1252        if (!first) {
1253          os << "\n";
1254        }
1255      }
1256    }
1257  }
1258
1259  void DumpVRegsAtDexPc(std::ostream& os, verifier::MethodVerifier* verifier,
1260                        const OatFile::OatMethod& oat_method,
1261                        const DexFile::CodeItem* code_item, uint32_t dex_pc) {
1262    DCHECK(verifier != nullptr);
1263    std::vector<int32_t> kinds = verifier->DescribeVRegs(dex_pc);
1264    bool first = true;
1265    for (size_t reg = 0; reg < code_item->registers_size_; reg++) {
1266      VRegKind kind = static_cast<VRegKind>(kinds.at(reg * 2));
1267      if (kind != kUndefined) {
1268        if (first) {
1269          os << "VRegs:  v";
1270          first = false;
1271        } else {
1272          os << ", v";
1273        }
1274        os << reg << " (";
1275        switch (kind) {
1276          case kImpreciseConstant:
1277            os << "Imprecise Constant: " << kinds.at((reg * 2) + 1) << ", ";
1278            DescribeVReg(os, oat_method, code_item, reg, kind);
1279            break;
1280          case kConstant:
1281            os << "Constant: " << kinds.at((reg * 2) + 1);
1282            break;
1283          default:
1284            DescribeVReg(os, oat_method, code_item, reg, kind);
1285            break;
1286        }
1287        os << ")";
1288      }
1289    }
1290    if (!first) {
1291      os << "\n";
1292    }
1293  }
1294
1295
1296  void DumpDexCode(std::ostream& os, const DexFile& dex_file, const DexFile::CodeItem* code_item) {
1297    if (code_item != nullptr) {
1298      size_t i = 0;
1299      while (i < code_item->insns_size_in_code_units_) {
1300        const Instruction* instruction = Instruction::At(&code_item->insns_[i]);
1301        os << StringPrintf("0x%04zx: ", i) << instruction->DumpHexLE(5)
1302           << StringPrintf("\t| %s\n", instruction->DumpString(&dex_file).c_str());
1303        i += instruction->SizeInCodeUnits();
1304      }
1305    }
1306  }
1307
1308  verifier::MethodVerifier* DumpVerifier(std::ostream& os, uint32_t dex_method_idx,
1309                                         const DexFile* dex_file,
1310                                         const DexFile::ClassDef& class_def,
1311                                         const DexFile::CodeItem* code_item,
1312                                         uint32_t method_access_flags) {
1313    if ((method_access_flags & kAccNative) == 0) {
1314      ScopedObjectAccess soa(Thread::Current());
1315      StackHandleScope<1> hs(soa.Self());
1316      Handle<mirror::DexCache> dex_cache(
1317          hs.NewHandle(Runtime::Current()->GetClassLinker()->FindDexCache(*dex_file)));
1318      DCHECK(options_.class_loader_ != nullptr);
1319      return verifier::MethodVerifier::VerifyMethodAndDump(soa.Self(), os, dex_method_idx, dex_file,
1320                                                           dex_cache,
1321                                                           *options_.class_loader_,
1322                                                           &class_def, code_item,
1323                                                           NullHandle<mirror::ArtMethod>(),
1324                                                           method_access_flags);
1325    }
1326
1327    return nullptr;
1328  }
1329
1330  void DumpCode(std::ostream& os, verifier::MethodVerifier* verifier,
1331                const OatFile::OatMethod& oat_method, const DexFile::CodeItem* code_item,
1332                bool bad_input, size_t code_size) {
1333    const void* quick_code = oat_method.GetQuickCode();
1334
1335    if (code_size == 0) {
1336      code_size = oat_method.GetQuickCodeSize();
1337    }
1338    if (code_size == 0 || quick_code == nullptr) {
1339      os << "NO CODE!\n";
1340      return;
1341    } else {
1342      const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1343      size_t offset = 0;
1344      while (offset < code_size) {
1345        if (!bad_input) {
1346          DumpMappingAtOffset(os, oat_method, offset, false);
1347        }
1348        offset += disassembler_->Dump(os, quick_native_pc + offset);
1349        if (!bad_input) {
1350          uint32_t dex_pc = DumpMappingAtOffset(os, oat_method, offset, true);
1351          if (dex_pc != DexFile::kDexNoIndex) {
1352            DumpGcMapAtNativePcOffset(os, oat_method, code_item, offset);
1353            if (verifier != nullptr) {
1354              DumpVRegsAtDexPc(os, verifier, oat_method, code_item, dex_pc);
1355            }
1356          }
1357        }
1358      }
1359    }
1360  }
1361
1362  const OatFile& oat_file_;
1363  const std::vector<const OatFile::OatDexFile*> oat_dex_files_;
1364  const OatDumperOptions& options_;
1365  uint32_t resolved_addr2instr_;
1366  InstructionSet instruction_set_;
1367  std::set<uintptr_t> offsets_;
1368  Disassembler* disassembler_;
1369};
1370
1371class ImageDumper {
1372 public:
1373  explicit ImageDumper(std::ostream* os, gc::space::ImageSpace& image_space,
1374                       const ImageHeader& image_header, OatDumperOptions* oat_dumper_options)
1375      : os_(os),
1376        image_space_(image_space),
1377        image_header_(image_header),
1378        oat_dumper_options_(oat_dumper_options) {}
1379
1380  bool Dump() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1381    std::ostream& os = *os_;
1382    os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
1383
1384    os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n\n";
1385
1386    os << "IMAGE BITMAP OFFSET: " << reinterpret_cast<void*>(image_header_.GetImageBitmapOffset())
1387       << " SIZE: " << reinterpret_cast<void*>(image_header_.GetImageBitmapSize()) << "\n\n";
1388
1389    os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum());
1390
1391    os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n\n";
1392
1393    os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n\n";
1394
1395    os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n\n";
1396
1397    os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
1398
1399    os << "PATCH DELTA:" << image_header_.GetPatchDelta() << "\n\n";
1400
1401    os << "COMPILE PIC: " << (image_header_.CompilePic() ? "yes" : "no") << "\n\n";
1402
1403    {
1404      os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots()) << "\n";
1405      Indenter indent1_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1406      std::ostream indent1_os(&indent1_filter);
1407      CHECK_EQ(arraysize(image_roots_descriptions_), size_t(ImageHeader::kImageRootsMax));
1408      for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
1409        ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
1410        const char* image_root_description = image_roots_descriptions_[i];
1411        mirror::Object* image_root_object = image_header_.GetImageRoot(image_root);
1412        indent1_os << StringPrintf("%s: %p\n", image_root_description, image_root_object);
1413        if (image_root_object->IsObjectArray()) {
1414          Indenter indent2_filter(indent1_os.rdbuf(), kIndentChar, kIndentBy1Count);
1415          std::ostream indent2_os(&indent2_filter);
1416          mirror::ObjectArray<mirror::Object>* image_root_object_array
1417              = image_root_object->AsObjectArray<mirror::Object>();
1418          for (int j = 0; j < image_root_object_array->GetLength(); j++) {
1419            mirror::Object* value = image_root_object_array->Get(j);
1420            size_t run = 0;
1421            for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
1422              if (value == image_root_object_array->Get(k)) {
1423                run++;
1424              } else {
1425                break;
1426              }
1427            }
1428            if (run == 0) {
1429              indent2_os << StringPrintf("%d: ", j);
1430            } else {
1431              indent2_os << StringPrintf("%d to %zd: ", j, j + run);
1432              j = j + run;
1433            }
1434            if (value != nullptr) {
1435              PrettyObjectValue(indent2_os, value->GetClass(), value);
1436            } else {
1437              indent2_os << j << ": null\n";
1438            }
1439          }
1440        }
1441      }
1442    }
1443    os << "\n";
1444
1445    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1446    std::string image_filename = image_space_.GetImageFilename();
1447    std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
1448    os << "OAT LOCATION: " << oat_location;
1449    os << "\n";
1450    std::string error_msg;
1451    const OatFile* oat_file = class_linker->FindOpenedOatFileFromOatLocation(oat_location);
1452    if (oat_file == nullptr) {
1453      oat_file = OatFile::Open(oat_location, oat_location,
1454                               nullptr, nullptr, false, nullptr,
1455                               &error_msg);
1456      if (oat_file == nullptr) {
1457        os << "NOT FOUND: " << error_msg << "\n";
1458        return false;
1459      }
1460    }
1461    os << "\n";
1462
1463    stats_.oat_file_bytes = oat_file->Size();
1464
1465    oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
1466
1467    for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1468      CHECK(oat_dex_file != nullptr);
1469      stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
1470                                                         oat_dex_file->FileSize()));
1471    }
1472
1473    os << "OBJECTS:\n" << std::flush;
1474
1475    // Loop through all the image spaces and dump their objects.
1476    gc::Heap* heap = Runtime::Current()->GetHeap();
1477    const std::vector<gc::space::ContinuousSpace*>& spaces = heap->GetContinuousSpaces();
1478    Thread* self = Thread::Current();
1479    {
1480      {
1481        WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1482        heap->FlushAllocStack();
1483      }
1484      // Since FlushAllocStack() above resets the (active) allocation
1485      // stack. Need to revoke the thread-local allocation stacks that
1486      // point into it.
1487      {
1488        self->TransitionFromRunnableToSuspended(kNative);
1489        ThreadList* thread_list = Runtime::Current()->GetThreadList();
1490        thread_list->SuspendAll(__FUNCTION__);
1491        heap->RevokeAllThreadLocalAllocationStacks(self);
1492        thread_list->ResumeAll();
1493        self->TransitionFromSuspendedToRunnable();
1494      }
1495    }
1496    {
1497      std::ostream* saved_os = os_;
1498      Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1499      std::ostream indent_os(&indent_filter);
1500      os_ = &indent_os;
1501      ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1502      for (const auto& space : spaces) {
1503        if (space->IsImageSpace()) {
1504          gc::space::ImageSpace* image_space = space->AsImageSpace();
1505          image_space->GetLiveBitmap()->Walk(ImageDumper::Callback, this);
1506          indent_os << "\n";
1507        }
1508      }
1509      // Dump the large objects separately.
1510      heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(ImageDumper::Callback, this);
1511      indent_os << "\n";
1512      os_ = saved_os;
1513    }
1514    os << "STATS:\n" << std::flush;
1515    std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
1516    if (file.get() == nullptr) {
1517      LOG(WARNING) << "Failed to find image in " << image_filename;
1518    }
1519    if (file.get() != nullptr) {
1520      stats_.file_bytes = file->GetLength();
1521    }
1522    size_t header_bytes = sizeof(ImageHeader);
1523    stats_.header_bytes = header_bytes;
1524    size_t alignment_bytes = RoundUp(header_bytes, kObjectAlignment) - header_bytes;
1525    stats_.alignment_bytes += alignment_bytes;
1526    stats_.alignment_bytes += image_header_.GetImageBitmapOffset() - image_header_.GetImageSize();
1527    stats_.bitmap_bytes += image_header_.GetImageBitmapSize();
1528    stats_.Dump(os);
1529    os << "\n";
1530
1531    os << std::flush;
1532
1533    return oat_dumper_->Dump(os);
1534  }
1535
1536 private:
1537  static void PrettyObjectValue(std::ostream& os, mirror::Class* type, mirror::Object* value)
1538      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1539    CHECK(type != nullptr);
1540    if (value == nullptr) {
1541      os << StringPrintf("null   %s\n", PrettyDescriptor(type).c_str());
1542    } else if (type->IsStringClass()) {
1543      mirror::String* string = value->AsString();
1544      os << StringPrintf("%p   String: %s\n", string,
1545                         PrintableString(string->ToModifiedUtf8().c_str()).c_str());
1546    } else if (type->IsClassClass()) {
1547      mirror::Class* klass = value->AsClass();
1548      os << StringPrintf("%p   Class: %s\n", klass, PrettyDescriptor(klass).c_str());
1549    } else if (type->IsArtMethodClass()) {
1550      mirror::ArtMethod* method = value->AsArtMethod();
1551      os << StringPrintf("%p   Method: %s\n", method, PrettyMethod(method).c_str());
1552    } else {
1553      os << StringPrintf("%p   %s\n", value, PrettyDescriptor(type).c_str());
1554    }
1555  }
1556
1557  static void PrintField(std::ostream& os, ArtField* field, mirror::Object* obj)
1558      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1559    os << StringPrintf("%s: ", field->GetName());
1560    switch (field->GetTypeAsPrimitiveType()) {
1561      case Primitive::kPrimLong:
1562        os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
1563        break;
1564      case Primitive::kPrimDouble:
1565        os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
1566        break;
1567      case Primitive::kPrimFloat:
1568        os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
1569        break;
1570      case Primitive::kPrimInt:
1571        os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
1572        break;
1573      case Primitive::kPrimChar:
1574        os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
1575        break;
1576      case Primitive::kPrimShort:
1577        os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
1578        break;
1579      case Primitive::kPrimBoolean:
1580        os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj)? "true" : "false",
1581            field->GetBoolean(obj));
1582        break;
1583      case Primitive::kPrimByte:
1584        os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
1585        break;
1586      case Primitive::kPrimNot: {
1587        // Get the value, don't compute the type unless it is non-null as we don't want
1588        // to cause class loading.
1589        mirror::Object* value = field->GetObj(obj);
1590        if (value == nullptr) {
1591          os << StringPrintf("null   %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
1592        } else {
1593          // Grab the field type without causing resolution.
1594          mirror::Class* field_type = field->GetType<false>();
1595          if (field_type != nullptr) {
1596            PrettyObjectValue(os, field_type, value);
1597          } else {
1598            os << StringPrintf("%p   %s\n", value,
1599                               PrettyDescriptor(field->GetTypeDescriptor()).c_str());
1600          }
1601        }
1602        break;
1603      }
1604      default:
1605        os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
1606        break;
1607    }
1608  }
1609
1610  static void DumpFields(std::ostream& os, mirror::Object* obj, mirror::Class* klass)
1611      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1612    mirror::Class* super = klass->GetSuperClass();
1613    if (super != nullptr) {
1614      DumpFields(os, obj, super);
1615    }
1616    ArtField* fields = klass->GetIFields();
1617    for (size_t i = 0, count = klass->NumInstanceFields(); i < count; i++) {
1618      PrintField(os, &fields[i], obj);
1619    }
1620  }
1621
1622  bool InDumpSpace(const mirror::Object* object) {
1623    return image_space_.Contains(object);
1624  }
1625
1626  const void* GetQuickOatCodeBegin(mirror::ArtMethod* m)
1627      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1628    const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
1629        InstructionSetPointerSize(oat_dumper_->GetOatInstructionSet()));
1630    if (Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(quick_code)) {
1631      quick_code = oat_dumper_->GetQuickOatCode(m);
1632    }
1633    if (oat_dumper_->GetInstructionSet() == kThumb2) {
1634      quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
1635    }
1636    return quick_code;
1637  }
1638
1639  uint32_t GetQuickOatCodeSize(mirror::ArtMethod* m)
1640      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1641    const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
1642    if (oat_code_begin == nullptr) {
1643      return 0;
1644    }
1645    return oat_code_begin[-1];
1646  }
1647
1648  const void* GetQuickOatCodeEnd(mirror::ArtMethod* m)
1649      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1650    const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
1651    if (oat_code_begin == nullptr) {
1652      return nullptr;
1653    }
1654    return oat_code_begin + GetQuickOatCodeSize(m);
1655  }
1656
1657  static void Callback(mirror::Object* obj, void* arg)
1658      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1659    DCHECK(obj != nullptr);
1660    DCHECK(arg != nullptr);
1661    ImageDumper* state = reinterpret_cast<ImageDumper*>(arg);
1662    if (!state->InDumpSpace(obj)) {
1663      return;
1664    }
1665
1666    size_t object_bytes = obj->SizeOf();
1667    size_t alignment_bytes = RoundUp(object_bytes, kObjectAlignment) - object_bytes;
1668    state->stats_.object_bytes += object_bytes;
1669    state->stats_.alignment_bytes += alignment_bytes;
1670
1671    std::ostream& os = *state->os_;
1672    mirror::Class* obj_class = obj->GetClass();
1673    if (obj_class->IsArrayClass()) {
1674      os << StringPrintf("%p: %s length:%d\n", obj, PrettyDescriptor(obj_class).c_str(),
1675                         obj->AsArray()->GetLength());
1676    } else if (obj->IsClass()) {
1677      mirror::Class* klass = obj->AsClass();
1678      os << StringPrintf("%p: java.lang.Class \"%s\" (", obj, PrettyDescriptor(klass).c_str())
1679         << klass->GetStatus() << ")\n";
1680    } else if (obj->IsArtMethod()) {
1681      os << StringPrintf("%p: java.lang.reflect.ArtMethod %s\n", obj,
1682                         PrettyMethod(obj->AsArtMethod()).c_str());
1683    } else if (obj_class->IsStringClass()) {
1684      os << StringPrintf("%p: java.lang.String %s\n", obj,
1685                         PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
1686    } else {
1687      os << StringPrintf("%p: %s\n", obj, PrettyDescriptor(obj_class).c_str());
1688    }
1689    Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
1690    std::ostream indent_os(&indent_filter);
1691    DumpFields(indent_os, obj, obj_class);
1692    if (obj->IsObjectArray()) {
1693      mirror::ObjectArray<mirror::Object>* obj_array = obj->AsObjectArray<mirror::Object>();
1694      int32_t length = obj_array->GetLength();
1695      for (int32_t i = 0; i < length; i++) {
1696        mirror::Object* value = obj_array->Get(i);
1697        size_t run = 0;
1698        for (int32_t j = i + 1; j < length; j++) {
1699          if (value == obj_array->Get(j)) {
1700            run++;
1701          } else {
1702            break;
1703          }
1704        }
1705        if (run == 0) {
1706          indent_os << StringPrintf("%d: ", i);
1707        } else {
1708          indent_os << StringPrintf("%d to %zd: ", i, i + run);
1709          i = i + run;
1710        }
1711        mirror::Class* value_class =
1712            (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
1713        PrettyObjectValue(indent_os, value_class, value);
1714      }
1715    } else if (obj->IsClass()) {
1716      mirror::Class* klass = obj->AsClass();
1717      ArtField* sfields = klass->GetSFields();
1718      const size_t num_fields = klass->NumStaticFields();
1719      if (num_fields != 0) {
1720        indent_os << "STATICS:\n";
1721        Indenter indent2_filter(indent_os.rdbuf(), kIndentChar, kIndentBy1Count);
1722        std::ostream indent2_os(&indent2_filter);
1723        for (size_t i = 0; i < num_fields; i++) {
1724          PrintField(indent2_os, &sfields[i], sfields[i].GetDeclaringClass());
1725        }
1726      }
1727    } else if (obj->IsArtMethod()) {
1728      const size_t image_pointer_size = InstructionSetPointerSize(
1729          state->oat_dumper_->GetOatInstructionSet());
1730      mirror::ArtMethod* method = obj->AsArtMethod();
1731      if (method->IsNative()) {
1732        DCHECK(method->GetNativeGcMap(image_pointer_size) == nullptr) << PrettyMethod(method);
1733        DCHECK(method->GetMappingTable(image_pointer_size) == nullptr) << PrettyMethod(method);
1734        bool first_occurrence;
1735        const void* quick_oat_code = state->GetQuickOatCodeBegin(method);
1736        uint32_t quick_oat_code_size = state->GetQuickOatCodeSize(method);
1737        state->ComputeOatSize(quick_oat_code, &first_occurrence);
1738        if (first_occurrence) {
1739          state->stats_.native_to_managed_code_bytes += quick_oat_code_size;
1740        }
1741        if (quick_oat_code != method->GetEntryPointFromQuickCompiledCodePtrSize(
1742            image_pointer_size)) {
1743          indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code);
1744        }
1745      } else if (method->IsAbstract() || method->IsCalleeSaveMethod() ||
1746          method->IsResolutionMethod() || method->IsImtConflictMethod() ||
1747          method->IsImtUnimplementedMethod() || method->IsClassInitializer()) {
1748        DCHECK(method->GetNativeGcMap(image_pointer_size) == nullptr) << PrettyMethod(method);
1749        DCHECK(method->GetMappingTable(image_pointer_size) == nullptr) << PrettyMethod(method);
1750      } else {
1751        const DexFile::CodeItem* code_item = method->GetCodeItem();
1752        size_t dex_instruction_bytes = code_item->insns_size_in_code_units_ * 2;
1753        state->stats_.dex_instruction_bytes += dex_instruction_bytes;
1754
1755        bool first_occurrence;
1756        size_t gc_map_bytes =
1757            state->ComputeOatSize(method->GetNativeGcMap(image_pointer_size), &first_occurrence);
1758        if (first_occurrence) {
1759          state->stats_.gc_map_bytes += gc_map_bytes;
1760        }
1761
1762        size_t pc_mapping_table_bytes =
1763            state->ComputeOatSize(method->GetMappingTable(image_pointer_size), &first_occurrence);
1764        if (first_occurrence) {
1765          state->stats_.pc_mapping_table_bytes += pc_mapping_table_bytes;
1766        }
1767
1768        size_t vmap_table_bytes =
1769            state->ComputeOatSize(method->GetVmapTable(image_pointer_size), &first_occurrence);
1770        if (first_occurrence) {
1771          state->stats_.vmap_table_bytes += vmap_table_bytes;
1772        }
1773
1774        const void* quick_oat_code_begin = state->GetQuickOatCodeBegin(method);
1775        const void* quick_oat_code_end = state->GetQuickOatCodeEnd(method);
1776        uint32_t quick_oat_code_size = state->GetQuickOatCodeSize(method);
1777        state->ComputeOatSize(quick_oat_code_begin, &first_occurrence);
1778        if (first_occurrence) {
1779          state->stats_.managed_code_bytes += quick_oat_code_size;
1780          if (method->IsConstructor()) {
1781            if (method->IsStatic()) {
1782              state->stats_.class_initializer_code_bytes += quick_oat_code_size;
1783            } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
1784              state->stats_.large_initializer_code_bytes += quick_oat_code_size;
1785            }
1786          } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
1787            state->stats_.large_method_code_bytes += quick_oat_code_size;
1788          }
1789        }
1790        state->stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
1791
1792        indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
1793        indent_os << StringPrintf("SIZE: Dex Instructions=%zd GC=%zd Mapping=%zd\n",
1794                                  dex_instruction_bytes, gc_map_bytes, pc_mapping_table_bytes);
1795
1796        size_t total_size = dex_instruction_bytes + gc_map_bytes + pc_mapping_table_bytes +
1797            vmap_table_bytes + quick_oat_code_size + object_bytes;
1798
1799        double expansion =
1800            static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
1801        state->stats_.ComputeOutliers(total_size, expansion, method);
1802      }
1803    }
1804    std::string temp;
1805    state->stats_.Update(obj_class->GetDescriptor(&temp), object_bytes);
1806  }
1807
1808  std::set<const void*> already_seen_;
1809  // Compute the size of the given data within the oat file and whether this is the first time
1810  // this data has been requested
1811  size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
1812    if (already_seen_.count(oat_data) == 0) {
1813      *first_occurrence = true;
1814      already_seen_.insert(oat_data);
1815    } else {
1816      *first_occurrence = false;
1817    }
1818    return oat_dumper_->ComputeSize(oat_data);
1819  }
1820
1821 public:
1822  struct Stats {
1823    size_t oat_file_bytes;
1824    size_t file_bytes;
1825
1826    size_t header_bytes;
1827    size_t object_bytes;
1828    size_t bitmap_bytes;
1829    size_t alignment_bytes;
1830
1831    size_t managed_code_bytes;
1832    size_t managed_code_bytes_ignoring_deduplication;
1833    size_t managed_to_native_code_bytes;
1834    size_t native_to_managed_code_bytes;
1835    size_t class_initializer_code_bytes;
1836    size_t large_initializer_code_bytes;
1837    size_t large_method_code_bytes;
1838
1839    size_t gc_map_bytes;
1840    size_t pc_mapping_table_bytes;
1841    size_t vmap_table_bytes;
1842
1843    size_t dex_instruction_bytes;
1844
1845    std::vector<mirror::ArtMethod*> method_outlier;
1846    std::vector<size_t> method_outlier_size;
1847    std::vector<double> method_outlier_expansion;
1848    std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
1849
1850    explicit Stats()
1851        : oat_file_bytes(0),
1852          file_bytes(0),
1853          header_bytes(0),
1854          object_bytes(0),
1855          bitmap_bytes(0),
1856          alignment_bytes(0),
1857          managed_code_bytes(0),
1858          managed_code_bytes_ignoring_deduplication(0),
1859          managed_to_native_code_bytes(0),
1860          native_to_managed_code_bytes(0),
1861          class_initializer_code_bytes(0),
1862          large_initializer_code_bytes(0),
1863          large_method_code_bytes(0),
1864          gc_map_bytes(0),
1865          pc_mapping_table_bytes(0),
1866          vmap_table_bytes(0),
1867          dex_instruction_bytes(0) {}
1868
1869    struct SizeAndCount {
1870      SizeAndCount(size_t bytes_in, size_t count_in) : bytes(bytes_in), count(count_in) {}
1871      size_t bytes;
1872      size_t count;
1873    };
1874    typedef SafeMap<std::string, SizeAndCount> SizeAndCountTable;
1875    SizeAndCountTable sizes_and_counts;
1876
1877    void Update(const char* descriptor, size_t object_bytes_in) {
1878      SizeAndCountTable::iterator it = sizes_and_counts.find(descriptor);
1879      if (it != sizes_and_counts.end()) {
1880        it->second.bytes += object_bytes_in;
1881        it->second.count += 1;
1882      } else {
1883        sizes_and_counts.Put(descriptor, SizeAndCount(object_bytes_in, 1));
1884      }
1885    }
1886
1887    double PercentOfOatBytes(size_t size) {
1888      return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
1889    }
1890
1891    double PercentOfFileBytes(size_t size) {
1892      return (static_cast<double>(size) / static_cast<double>(file_bytes)) * 100;
1893    }
1894
1895    double PercentOfObjectBytes(size_t size) {
1896      return (static_cast<double>(size) / static_cast<double>(object_bytes)) * 100;
1897    }
1898
1899    void ComputeOutliers(size_t total_size, double expansion, mirror::ArtMethod* method) {
1900      method_outlier_size.push_back(total_size);
1901      method_outlier_expansion.push_back(expansion);
1902      method_outlier.push_back(method);
1903    }
1904
1905    void DumpOutliers(std::ostream& os)
1906        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1907      size_t sum_of_sizes = 0;
1908      size_t sum_of_sizes_squared = 0;
1909      size_t sum_of_expansion = 0;
1910      size_t sum_of_expansion_squared = 0;
1911      size_t n = method_outlier_size.size();
1912      for (size_t i = 0; i < n; i++) {
1913        size_t cur_size = method_outlier_size[i];
1914        sum_of_sizes += cur_size;
1915        sum_of_sizes_squared += cur_size * cur_size;
1916        double cur_expansion = method_outlier_expansion[i];
1917        sum_of_expansion += cur_expansion;
1918        sum_of_expansion_squared += cur_expansion * cur_expansion;
1919      }
1920      size_t size_mean = sum_of_sizes / n;
1921      size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
1922      double expansion_mean = sum_of_expansion / n;
1923      double expansion_variance =
1924          (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
1925
1926      // Dump methods whose size is a certain number of standard deviations from the mean
1927      size_t dumped_values = 0;
1928      size_t skipped_values = 0;
1929      for (size_t i = 100; i > 0; i--) {  // i is the current number of standard deviations
1930        size_t cur_size_variance = i * i * size_variance;
1931        bool first = true;
1932        for (size_t j = 0; j < n; j++) {
1933          size_t cur_size = method_outlier_size[j];
1934          if (cur_size > size_mean) {
1935            size_t cur_var = cur_size - size_mean;
1936            cur_var = cur_var * cur_var;
1937            if (cur_var > cur_size_variance) {
1938              if (dumped_values > 20) {
1939                if (i == 1) {
1940                  skipped_values++;
1941                } else {
1942                  i = 2;  // jump to counting for 1 standard deviation
1943                  break;
1944                }
1945              } else {
1946                if (first) {
1947                  os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
1948                  first = false;
1949                }
1950                os << PrettyMethod(method_outlier[j]) << " requires storage of "
1951                    << PrettySize(cur_size) << "\n";
1952                method_outlier_size[j] = 0;  // don't consider this method again
1953                dumped_values++;
1954              }
1955            }
1956          }
1957        }
1958      }
1959      if (skipped_values > 0) {
1960        os << "... skipped " << skipped_values
1961           << " methods with size > 1 standard deviation from the norm\n";
1962      }
1963      os << std::flush;
1964
1965      // Dump methods whose expansion is a certain number of standard deviations from the mean
1966      dumped_values = 0;
1967      skipped_values = 0;
1968      for (size_t i = 10; i > 0; i--) {  // i is the current number of standard deviations
1969        double cur_expansion_variance = i * i * expansion_variance;
1970        bool first = true;
1971        for (size_t j = 0; j < n; j++) {
1972          double cur_expansion = method_outlier_expansion[j];
1973          if (cur_expansion > expansion_mean) {
1974            size_t cur_var = cur_expansion - expansion_mean;
1975            cur_var = cur_var * cur_var;
1976            if (cur_var > cur_expansion_variance) {
1977              if (dumped_values > 20) {
1978                if (i == 1) {
1979                  skipped_values++;
1980                } else {
1981                  i = 2;  // jump to counting for 1 standard deviation
1982                  break;
1983                }
1984              } else {
1985                if (first) {
1986                  os << "\nLarge expansion methods (size > " << i
1987                      << " standard deviations the norm):\n";
1988                  first = false;
1989                }
1990                os << PrettyMethod(method_outlier[j]) << " expanded code by "
1991                   << cur_expansion << "\n";
1992                method_outlier_expansion[j] = 0.0;  // don't consider this method again
1993                dumped_values++;
1994              }
1995            }
1996          }
1997        }
1998      }
1999      if (skipped_values > 0) {
2000        os << "... skipped " << skipped_values
2001           << " methods with expansion > 1 standard deviation from the norm\n";
2002      }
2003      os << "\n" << std::flush;
2004    }
2005
2006    void Dump(std::ostream& os) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2007      {
2008        os << "art_file_bytes = " << PrettySize(file_bytes) << "\n\n"
2009           << "art_file_bytes = header_bytes + object_bytes + alignment_bytes\n";
2010        Indenter indent_filter(os.rdbuf(), kIndentChar, kIndentBy1Count);
2011        std::ostream indent_os(&indent_filter);
2012        indent_os << StringPrintf("header_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
2013                                  "object_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
2014                                  "bitmap_bytes    =  %8zd (%2.0f%% of art file bytes)\n"
2015                                  "alignment_bytes =  %8zd (%2.0f%% of art file bytes)\n\n",
2016                                  header_bytes, PercentOfFileBytes(header_bytes),
2017                                  object_bytes, PercentOfFileBytes(object_bytes),
2018                                  bitmap_bytes, PercentOfFileBytes(bitmap_bytes),
2019                                  alignment_bytes, PercentOfFileBytes(alignment_bytes))
2020            << std::flush;
2021        CHECK_EQ(file_bytes, bitmap_bytes + header_bytes + object_bytes + alignment_bytes);
2022      }
2023
2024      os << "object_bytes breakdown:\n";
2025      size_t object_bytes_total = 0;
2026      for (const auto& sizes_and_count : sizes_and_counts) {
2027        const std::string& descriptor(sizes_and_count.first);
2028        double average = static_cast<double>(sizes_and_count.second.bytes) /
2029            static_cast<double>(sizes_and_count.second.count);
2030        double percent = PercentOfObjectBytes(sizes_and_count.second.bytes);
2031        os << StringPrintf("%32s %8zd bytes %6zd instances "
2032                           "(%4.0f bytes/instance) %2.0f%% of object_bytes\n",
2033                           descriptor.c_str(), sizes_and_count.second.bytes,
2034                           sizes_and_count.second.count, average, percent);
2035        object_bytes_total += sizes_and_count.second.bytes;
2036      }
2037      os << "\n" << std::flush;
2038      CHECK_EQ(object_bytes, object_bytes_total);
2039
2040      os << StringPrintf("oat_file_bytes               = %8zd\n"
2041                         "managed_code_bytes           = %8zd (%2.0f%% of oat file bytes)\n"
2042                         "managed_to_native_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2043                         "native_to_managed_code_bytes = %8zd (%2.0f%% of oat file bytes)\n\n"
2044                         "class_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2045                         "large_initializer_code_bytes = %8zd (%2.0f%% of oat file bytes)\n"
2046                         "large_method_code_bytes      = %8zd (%2.0f%% of oat file bytes)\n\n",
2047                         oat_file_bytes,
2048                         managed_code_bytes,
2049                         PercentOfOatBytes(managed_code_bytes),
2050                         managed_to_native_code_bytes,
2051                         PercentOfOatBytes(managed_to_native_code_bytes),
2052                         native_to_managed_code_bytes,
2053                         PercentOfOatBytes(native_to_managed_code_bytes),
2054                         class_initializer_code_bytes,
2055                         PercentOfOatBytes(class_initializer_code_bytes),
2056                         large_initializer_code_bytes,
2057                         PercentOfOatBytes(large_initializer_code_bytes),
2058                         large_method_code_bytes,
2059                         PercentOfOatBytes(large_method_code_bytes))
2060            << "DexFile sizes:\n";
2061      for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
2062        os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
2063                           oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2064                           PercentOfOatBytes(oat_dex_file_size.second));
2065      }
2066
2067      os << "\n" << StringPrintf("gc_map_bytes           = %7zd (%2.0f%% of oat file bytes)\n"
2068                                 "pc_mapping_table_bytes = %7zd (%2.0f%% of oat file bytes)\n"
2069                                 "vmap_table_bytes       = %7zd (%2.0f%% of oat file bytes)\n\n",
2070                                 gc_map_bytes, PercentOfOatBytes(gc_map_bytes),
2071                                 pc_mapping_table_bytes, PercentOfOatBytes(pc_mapping_table_bytes),
2072                                 vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
2073         << std::flush;
2074
2075      os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2076         << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
2077                         static_cast<double>(managed_code_bytes) /
2078                             static_cast<double>(dex_instruction_bytes),
2079                         static_cast<double>(managed_code_bytes_ignoring_deduplication) /
2080                             static_cast<double>(dex_instruction_bytes))
2081         << std::flush;
2082
2083      DumpOutliers(os);
2084    }
2085  } stats_;
2086
2087 private:
2088  enum {
2089    // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2090    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2091    kLargeConstructorDexBytes = 4000,
2092    // Number of bytes for a method to be considered large. Based on the 4000 basic block
2093    // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2094    kLargeMethodDexBytes = 16000
2095  };
2096  std::ostream* os_;
2097  gc::space::ImageSpace& image_space_;
2098  const ImageHeader& image_header_;
2099  std::unique_ptr<OatDumper> oat_dumper_;
2100  std::unique_ptr<OatDumperOptions> oat_dumper_options_;
2101
2102  DISALLOW_COPY_AND_ASSIGN(ImageDumper);
2103};
2104
2105static int DumpImage(Runtime* runtime, const char* image_location, OatDumperOptions* options,
2106                     std::ostream* os) {
2107  // Dumping the image, no explicit class loader.
2108  NullHandle<mirror::ClassLoader> null_class_loader;
2109  options->class_loader_ = &null_class_loader;
2110
2111  ScopedObjectAccess soa(Thread::Current());
2112  gc::Heap* heap = runtime->GetHeap();
2113  gc::space::ImageSpace* image_space = heap->GetImageSpace();
2114  CHECK(image_space != nullptr);
2115  const ImageHeader& image_header = image_space->GetImageHeader();
2116  if (!image_header.IsValid()) {
2117    fprintf(stderr, "Invalid image header %s\n", image_location);
2118    return EXIT_FAILURE;
2119  }
2120
2121  ImageDumper image_dumper(os, *image_space, image_header, options);
2122
2123  bool success = image_dumper.Dump();
2124  return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2125}
2126
2127static int DumpOatWithRuntime(Runtime* runtime, OatFile* oat_file, OatDumperOptions* options,
2128                              std::ostream* os) {
2129  CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
2130
2131  Thread* self = Thread::Current();
2132  CHECK(self != nullptr);
2133  // Need well-known-classes.
2134  WellKnownClasses::Init(self->GetJniEnv());
2135
2136  // Need to register dex files to get a working dex cache.
2137  ScopedObjectAccess soa(self);
2138  ClassLinker* class_linker = runtime->GetClassLinker();
2139  class_linker->RegisterOatFile(oat_file);
2140  std::vector<std::unique_ptr<const DexFile>> dex_files;
2141  for (const OatFile::OatDexFile* odf : oat_file->GetOatDexFiles()) {
2142    std::string error_msg;
2143    std::unique_ptr<const DexFile> dex_file = odf->OpenDexFile(&error_msg);
2144    CHECK(dex_file != nullptr) << error_msg;
2145    class_linker->RegisterDexFile(*dex_file);
2146    dex_files.push_back(std::move(dex_file));
2147  }
2148
2149  // Need a class loader.
2150  // Fake that we're a compiler.
2151  std::vector<const DexFile*> class_path;
2152  for (auto& dex_file : dex_files) {
2153    class_path.push_back(dex_file.get());
2154  }
2155  jobject class_loader = class_linker->CreatePathClassLoader(self, class_path);
2156
2157  // Use the class loader while dumping.
2158  StackHandleScope<1> scope(self);
2159  Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
2160      soa.Decode<mirror::ClassLoader*>(class_loader));
2161  options->class_loader_ = &loader_handle;
2162
2163  OatDumper oat_dumper(*oat_file, *options);
2164  bool success = oat_dumper.Dump(*os);
2165  return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2166}
2167
2168static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
2169  CHECK(oat_file != nullptr && options != nullptr);
2170  // No image = no class loader.
2171  NullHandle<mirror::ClassLoader> null_class_loader;
2172  options->class_loader_ = &null_class_loader;
2173
2174  OatDumper oat_dumper(*oat_file, *options);
2175  bool success = oat_dumper.Dump(*os);
2176  return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2177}
2178
2179static int DumpOat(Runtime* runtime, const char* oat_filename, OatDumperOptions* options,
2180                   std::ostream* os) {
2181  std::string error_msg;
2182  OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, nullptr, nullptr, false,
2183                                    nullptr, &error_msg);
2184  if (oat_file == nullptr) {
2185    fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
2186    return EXIT_FAILURE;
2187  }
2188
2189  if (runtime != nullptr) {
2190    return DumpOatWithRuntime(runtime, oat_file, options, os);
2191  } else {
2192    return DumpOatWithoutRuntime(oat_file, options, os);
2193  }
2194}
2195
2196static int SymbolizeOat(const char* oat_filename, std::string& output_name) {
2197  std::string error_msg;
2198  OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, nullptr, nullptr, false,
2199                                    nullptr, &error_msg);
2200  if (oat_file == nullptr) {
2201    fprintf(stderr, "Failed to open oat file from '%s': %s\n", oat_filename, error_msg.c_str());
2202    return EXIT_FAILURE;
2203  }
2204
2205  OatSymbolizer oat_symbolizer(oat_file, output_name);
2206  if (!oat_symbolizer.Init()) {
2207    fprintf(stderr, "Failed to initialize symbolizer\n");
2208    return EXIT_FAILURE;
2209  }
2210  if (!oat_symbolizer.Symbolize()) {
2211    fprintf(stderr, "Failed to symbolize\n");
2212    return EXIT_FAILURE;
2213  }
2214
2215  return EXIT_SUCCESS;
2216}
2217
2218struct OatdumpArgs : public CmdlineArgs {
2219 protected:
2220  using Base = CmdlineArgs;
2221
2222  virtual ParseStatus ParseCustom(const StringPiece& option,
2223                                  std::string* error_msg) OVERRIDE {
2224    {
2225      ParseStatus base_parse = Base::ParseCustom(option, error_msg);
2226      if (base_parse != kParseUnknownArgument) {
2227        return base_parse;
2228      }
2229    }
2230
2231    if (option.starts_with("--oat-file=")) {
2232      oat_filename_ = option.substr(strlen("--oat-file=")).data();
2233    } else if (option.starts_with("--image=")) {
2234      image_location_ = option.substr(strlen("--image=")).data();
2235    } else if (option =="--dump:raw_mapping_table") {
2236      dump_raw_mapping_table_ = true;
2237    } else if (option == "--dump:raw_gc_map") {
2238      dump_raw_gc_map_ = true;
2239    } else if (option == "--no-dump:vmap") {
2240      dump_vmap_ = false;
2241    } else if (option == "--no-disassemble") {
2242      disassemble_code_ = false;
2243    } else if (option.starts_with("--symbolize=")) {
2244      oat_filename_ = option.substr(strlen("--symbolize=")).data();
2245      symbolize_ = true;
2246    } else if (option.starts_with("--class-filter=")) {
2247      class_filter_ = option.substr(strlen("--class-filter=")).data();
2248    } else if (option.starts_with("--method-filter=")) {
2249      method_filter_ = option.substr(strlen("--method-filter=")).data();
2250    } else if (option.starts_with("--list-classes")) {
2251      list_classes_ = true;
2252    } else if (option.starts_with("--list-methods")) {
2253      list_methods_ = true;
2254    } else if (option.starts_with("--export-dex-to=")) {
2255      export_dex_location_ = option.substr(strlen("--export-dex-to=")).data();
2256    } else if (option.starts_with("--addr2instr=")) {
2257      if (!ParseUint(option.substr(strlen("--addr2instr=")).data(), &addr2instr_)) {
2258        *error_msg = "Address conversion failed";
2259        return kParseError;
2260      }
2261    } else {
2262      return kParseUnknownArgument;
2263    }
2264
2265    return kParseOk;
2266  }
2267
2268  virtual ParseStatus ParseChecks(std::string* error_msg) OVERRIDE {
2269    // Infer boot image location from the image location if possible.
2270    if (boot_image_location_ == nullptr) {
2271      boot_image_location_ = image_location_;
2272    }
2273
2274    // Perform the parent checks.
2275    ParseStatus parent_checks = Base::ParseChecks(error_msg);
2276    if (parent_checks != kParseOk) {
2277      return parent_checks;
2278    }
2279
2280    // Perform our own checks.
2281    if (image_location_ == nullptr && oat_filename_ == nullptr) {
2282      *error_msg = "Either --image or --oat-file must be specified";
2283      return kParseError;
2284    } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
2285      *error_msg = "Either --image or --oat-file must be specified but not both";
2286      return kParseError;
2287    }
2288
2289    return kParseOk;
2290  }
2291
2292  virtual std::string GetUsage() const {
2293    std::string usage;
2294
2295    usage +=
2296        "Usage: oatdump [options] ...\n"
2297        "    Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
2298        "    Example: adb shell oatdump --image=/system/framework/boot.art\n"
2299        "\n"
2300        // Either oat-file or image is required.
2301        "  --oat-file=<file.oat>: specifies an input oat filename.\n"
2302        "      Example: --oat-file=/system/framework/boot.oat\n"
2303        "\n"
2304        "  --image=<file.art>: specifies an input image location.\n"
2305        "      Example: --image=/system/framework/boot.art\n"
2306        "\n";
2307
2308    usage += Base::GetUsage();
2309
2310    usage +=  // Optional.
2311        "  --dump:raw_mapping_table enables dumping of the mapping table.\n"
2312        "      Example: --dump:raw_mapping_table\n"
2313        "\n"
2314        "  --dump:raw_mapping_table enables dumping of the GC map.\n"
2315        "      Example: --dump:raw_gc_map\n"
2316        "\n"
2317        "  --no-dump:vmap may be used to disable vmap dumping.\n"
2318        "      Example: --no-dump:vmap\n"
2319        "\n"
2320        "  --no-disassemble may be used to disable disassembly.\n"
2321        "      Example: --no-disassemble\n"
2322        "\n"
2323        "  --list-classes may be used to list target file classes (can be used with filters).\n"
2324        "      Example: --list-classes\n"
2325        "      Example: --list-classes --class-filter=com.example.foo\n"
2326        "\n"
2327        "  --list-methods may be used to list target file methods (can be used with filters).\n"
2328        "      Example: --list-methods\n"
2329        "      Example: --list-methods --class-filter=com.example --method-filter=foo\n"
2330        "\n"
2331        "  --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
2332        "      Example: --symbolize=/system/framework/boot.oat\n"
2333        "\n"
2334        "  --class-filter=<class name>: only dumps classes that contain the filter.\n"
2335        "      Example: --class-filter=com.example.foo\n"
2336        "\n"
2337        "  --method-filter=<method name>: only dumps methods that contain the filter.\n"
2338        "      Example: --method-filter=foo\n"
2339        "\n"
2340        "  --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
2341        "      Example: --export-dex-to=/data/local/tmp\n"
2342        "\n"
2343        "  --addr2instr=<address>: output matching method disassembled code from relative\n"
2344        "                          address (e.g. PC from crash dump)\n"
2345        "      Example: --addr2instr=0x00001a3b\n"
2346        "\n";
2347
2348    return usage;
2349  }
2350
2351 public:
2352  const char* oat_filename_ = nullptr;
2353  const char* class_filter_ = "";
2354  const char* method_filter_ = "";
2355  const char* image_location_ = nullptr;
2356  std::string elf_filename_prefix_;
2357  bool dump_raw_mapping_table_ = false;
2358  bool dump_raw_gc_map_ = false;
2359  bool dump_vmap_ = true;
2360  bool disassemble_code_ = true;
2361  bool symbolize_ = false;
2362  bool list_classes_ = false;
2363  bool list_methods_ = false;
2364  uint32_t addr2instr_ = 0;
2365  const char* export_dex_location_ = nullptr;
2366};
2367
2368struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
2369  virtual bool NeedsRuntime() OVERRIDE {
2370    CHECK(args_ != nullptr);
2371
2372    // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
2373    bool absolute_addresses = (args_->oat_filename_ == nullptr);
2374
2375    oat_dumper_options_ = std::unique_ptr<OatDumperOptions>(new OatDumperOptions(
2376        args_->dump_raw_mapping_table_,
2377        args_->dump_raw_gc_map_,
2378        args_->dump_vmap_,
2379        args_->disassemble_code_,
2380        absolute_addresses,
2381        args_->class_filter_,
2382        args_->method_filter_,
2383        args_->list_classes_,
2384        args_->list_methods_,
2385        args_->export_dex_location_,
2386        args_->addr2instr_));
2387
2388    return (args_->boot_image_location_ != nullptr || args_->image_location_ != nullptr) &&
2389          !args_->symbolize_;
2390  }
2391
2392  virtual bool ExecuteWithoutRuntime() OVERRIDE {
2393    CHECK(args_ != nullptr);
2394    CHECK(args_->oat_filename_ != nullptr);
2395
2396    MemMap::Init();
2397
2398    if (args_->symbolize_) {
2399      return SymbolizeOat(args_->oat_filename_, args_->output_name_) == EXIT_SUCCESS;
2400    } else {
2401      return DumpOat(nullptr,
2402                     args_->oat_filename_,
2403                     oat_dumper_options_.get(),
2404                     args_->os_) == EXIT_SUCCESS;
2405    }
2406  }
2407
2408  virtual bool ExecuteWithRuntime(Runtime* runtime) {
2409    CHECK(args_ != nullptr);
2410
2411    if (args_->oat_filename_ != nullptr) {
2412      return DumpOat(runtime,
2413                     args_->oat_filename_,
2414                     oat_dumper_options_.get(),
2415                     args_->os_) == EXIT_SUCCESS;
2416    }
2417
2418    return DumpImage(runtime, args_->image_location_, oat_dumper_options_.get(), args_->os_)
2419      == EXIT_SUCCESS;
2420  }
2421
2422  std::unique_ptr<OatDumperOptions> oat_dumper_options_;
2423};
2424
2425}  // namespace art
2426
2427int main(int argc, char** argv) {
2428  art::OatdumpMain main;
2429  return main.Main(argc, argv);
2430}
2431