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