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