• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <iomanip>
22 #include <iostream>
23 #include <map>
24 #include <set>
25 #include <string>
26 #include <unordered_map>
27 #include <unordered_set>
28 #include <vector>
29 
30 #include "android-base/logging.h"
31 #include "android-base/parseint.h"
32 #include "android-base/stringprintf.h"
33 #include "android-base/strings.h"
34 
35 #include "arch/instruction_set_features.h"
36 #include "art_field-inl.h"
37 #include "art_method-inl.h"
38 #include "base/bit_utils_iterator.h"
39 #include "base/indenter.h"
40 #include "base/os.h"
41 #include "base/safe_map.h"
42 #include "base/stats-inl.h"
43 #include "base/stl_util.h"
44 #include "base/unix_file/fd_file.h"
45 #include "class_linker-inl.h"
46 #include "class_linker.h"
47 #include "class_root-inl.h"
48 #include "compiled_method.h"
49 #include "debug/debug_info.h"
50 #include "debug/elf_debug_writer.h"
51 #include "debug/method_debug_info.h"
52 #include "dex/art_dex_file_loader.h"
53 #include "dex/class_accessor-inl.h"
54 #include "dex/code_item_accessors-inl.h"
55 #include "dex/descriptors_names.h"
56 #include "dex/dex_file-inl.h"
57 #include "dex/dex_instruction-inl.h"
58 #include "dex/string_reference.h"
59 #include "dex/type_lookup_table.h"
60 #include "dexlayout.h"
61 #include "disassembler.h"
62 #include "elf/elf_builder.h"
63 #include "gc/accounting/space_bitmap-inl.h"
64 #include "gc/space/image_space.h"
65 #include "gc/space/large_object_space.h"
66 #include "gc/space/space-inl.h"
67 #include "image-inl.h"
68 #include "imtable-inl.h"
69 #include "index_bss_mapping.h"
70 #include "interpreter/unstarted_runtime.h"
71 #include "mirror/array-inl.h"
72 #include "mirror/class-inl.h"
73 #include "mirror/dex_cache-inl.h"
74 #include "mirror/object-inl.h"
75 #include "mirror/object_array-inl.h"
76 #include "oat.h"
77 #include "oat_file-inl.h"
78 #include "oat_file_manager.h"
79 #include "scoped_thread_state_change-inl.h"
80 #include "stack.h"
81 #include "stack_map.h"
82 #include "stream/buffered_output_stream.h"
83 #include "stream/file_output_stream.h"
84 #include "subtype_check.h"
85 #include "thread_list.h"
86 #include "vdex_file.h"
87 #include "verifier/method_verifier.h"
88 #include "verifier/verifier_deps.h"
89 #include "well_known_classes.h"
90 
91 #include <sys/stat.h>
92 #include "cmdline.h"
93 
94 namespace art {
95 
96 using android::base::StringPrintf;
97 
98 const char* image_methods_descriptions_[] = {
99   "kResolutionMethod",
100   "kImtConflictMethod",
101   "kImtUnimplementedMethod",
102   "kSaveAllCalleeSavesMethod",
103   "kSaveRefsOnlyMethod",
104   "kSaveRefsAndArgsMethod",
105   "kSaveEverythingMethod",
106   "kSaveEverythingMethodForClinit",
107   "kSaveEverythingMethodForSuspendCheck",
108 };
109 
110 const char* image_roots_descriptions_[] = {
111   "kDexCaches",
112   "kClassRoots",
113   "kSpecialRoots",
114 };
115 
116 // Map is so that we don't allocate multiple dex files for the same OatDexFile.
117 static std::map<const OatDexFile*, std::unique_ptr<const DexFile>> opened_dex_files;
118 
OpenDexFile(const OatDexFile * oat_dex_file,std::string * error_msg)119 const DexFile* OpenDexFile(const OatDexFile* oat_dex_file, std::string* error_msg) {
120   DCHECK(oat_dex_file != nullptr);
121   auto it = opened_dex_files.find(oat_dex_file);
122   if (it != opened_dex_files.end()) {
123     return it->second.get();
124   }
125   const DexFile* ret = oat_dex_file->OpenDexFile(error_msg).release();
126   opened_dex_files.emplace(oat_dex_file, std::unique_ptr<const DexFile>(ret));
127   return ret;
128 }
129 
130 template <typename ElfTypes>
131 class OatSymbolizer final {
132  public:
OatSymbolizer(const OatFile * oat_file,const std::string & output_name,bool no_bits)133   OatSymbolizer(const OatFile* oat_file, const std::string& output_name, bool no_bits) :
134       oat_file_(oat_file),
135       builder_(nullptr),
136       output_name_(output_name.empty() ? "symbolized.oat" : output_name),
137       no_bits_(no_bits) {
138   }
139 
Symbolize()140   bool Symbolize() {
141     const InstructionSet isa = oat_file_->GetOatHeader().GetInstructionSet();
142     std::unique_ptr<const InstructionSetFeatures> features = InstructionSetFeatures::FromBitmap(
143         isa, oat_file_->GetOatHeader().GetInstructionSetFeaturesBitmap());
144 
145     std::unique_ptr<File> elf_file(OS::CreateEmptyFile(output_name_.c_str()));
146     if (elf_file == nullptr) {
147       return false;
148     }
149     std::unique_ptr<BufferedOutputStream> output_stream =
150         std::make_unique<BufferedOutputStream>(
151             std::make_unique<FileOutputStream>(elf_file.get()));
152     builder_.reset(new ElfBuilder<ElfTypes>(isa, output_stream.get()));
153 
154     builder_->Start();
155 
156     auto* rodata = builder_->GetRoData();
157     auto* text = builder_->GetText();
158 
159     const uint8_t* rodata_begin = oat_file_->Begin();
160     const size_t rodata_size = oat_file_->GetOatHeader().GetExecutableOffset();
161     if (!no_bits_) {
162       rodata->Start();
163       rodata->WriteFully(rodata_begin, rodata_size);
164       rodata->End();
165     }
166 
167     const uint8_t* text_begin = oat_file_->Begin() + rodata_size;
168     const size_t text_size = oat_file_->End() - text_begin;
169     if (!no_bits_) {
170       text->Start();
171       text->WriteFully(text_begin, text_size);
172       text->End();
173     }
174 
175     builder_->PrepareDynamicSection(elf_file->GetPath(),
176                                     rodata_size,
177                                     text_size,
178                                     oat_file_->DataBimgRelRoSize(),
179                                     oat_file_->BssSize(),
180                                     oat_file_->BssMethodsOffset(),
181                                     oat_file_->BssRootsOffset(),
182                                     oat_file_->VdexSize());
183     builder_->WriteDynamicSection();
184 
185     const OatHeader& oat_header = oat_file_->GetOatHeader();
186     #define DO_TRAMPOLINE(fn_name)                                                \
187       if (oat_header.Get ## fn_name ## Offset() != 0) {                           \
188         debug::MethodDebugInfo info = {};                                         \
189         info.custom_name = #fn_name;                                              \
190         info.isa = oat_header.GetInstructionSet();                                \
191         info.is_code_address_text_relative = true;                                \
192         size_t code_offset = oat_header.Get ## fn_name ## Offset();               \
193         code_offset -= CompiledCode::CodeDelta(oat_header.GetInstructionSet());   \
194         info.code_address = code_offset - oat_header.GetExecutableOffset();       \
195         info.code_size = 0;  /* The symbol lasts until the next symbol. */        \
196         method_debug_infos_.push_back(std::move(info));                           \
197       }
198     DO_TRAMPOLINE(JniDlsymLookupTrampoline);
199     DO_TRAMPOLINE(JniDlsymLookupCriticalTrampoline);
200     DO_TRAMPOLINE(QuickGenericJniTrampoline);
201     DO_TRAMPOLINE(QuickImtConflictTrampoline);
202     DO_TRAMPOLINE(QuickResolutionTrampoline);
203     DO_TRAMPOLINE(QuickToInterpreterBridge);
204     DO_TRAMPOLINE(NterpTrampoline);
205     #undef DO_TRAMPOLINE
206 
207     Walk();
208 
209     // TODO: Try to symbolize link-time thunks?
210     // This would require disassembling all methods to find branches outside the method code.
211 
212     // TODO: Add symbols for dex bytecode in the .dex section.
213 
214     debug::DebugInfo debug_info{};
215     debug_info.compiled_methods = ArrayRef<const debug::MethodDebugInfo>(method_debug_infos_);
216 
217     debug::WriteDebugInfo(builder_.get(), debug_info);
218 
219     builder_->End();
220 
221     bool ret_value = builder_->Good();
222 
223     builder_.reset();
224     output_stream.reset();
225 
226     if (elf_file->FlushCloseOrErase() != 0) {
227       return false;
228     }
229     elf_file.reset();
230 
231     return ret_value;
232   }
233 
Walk()234   void Walk() {
235     std::vector<const OatDexFile*> oat_dex_files = oat_file_->GetOatDexFiles();
236     for (size_t i = 0; i < oat_dex_files.size(); i++) {
237       const OatDexFile* oat_dex_file = oat_dex_files[i];
238       CHECK(oat_dex_file != nullptr);
239       WalkOatDexFile(oat_dex_file);
240     }
241   }
242 
WalkOatDexFile(const OatDexFile * oat_dex_file)243   void WalkOatDexFile(const OatDexFile* oat_dex_file) {
244     std::string error_msg;
245     const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
246     if (dex_file == nullptr) {
247       return;
248     }
249     for (size_t class_def_index = 0;
250         class_def_index < dex_file->NumClassDefs();
251         class_def_index++) {
252       const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
253       OatClassType type = oat_class.GetType();
254       switch (type) {
255         case OatClassType::kAllCompiled:
256         case OatClassType::kSomeCompiled:
257           WalkOatClass(oat_class, *dex_file, class_def_index);
258           break;
259 
260         case OatClassType::kNoneCompiled:
261         case OatClassType::kOatClassMax:
262           // Ignore.
263           break;
264       }
265     }
266   }
267 
WalkOatClass(const OatFile::OatClass & oat_class,const DexFile & dex_file,uint32_t class_def_index)268   void WalkOatClass(const OatFile::OatClass& oat_class,
269                     const DexFile& dex_file,
270                     uint32_t class_def_index) {
271     ClassAccessor accessor(dex_file, class_def_index);
272     // Note: even if this is an interface or a native class, we still have to walk it, as there
273     //       might be a static initializer.
274     uint32_t class_method_idx = 0;
275     for (const ClassAccessor::Method& method : accessor.GetMethods()) {
276       WalkOatMethod(oat_class.GetOatMethod(class_method_idx++),
277                     dex_file,
278                     class_def_index,
279                     method.GetIndex(),
280                     method.GetCodeItem(),
281                     method.GetAccessFlags());
282     }
283   }
284 
WalkOatMethod(const OatFile::OatMethod & oat_method,const DexFile & dex_file,uint32_t class_def_index,uint32_t dex_method_index,const dex::CodeItem * code_item,uint32_t method_access_flags)285   void WalkOatMethod(const OatFile::OatMethod& oat_method,
286                      const DexFile& dex_file,
287                      uint32_t class_def_index,
288                      uint32_t dex_method_index,
289                      const dex::CodeItem* code_item,
290                      uint32_t method_access_flags) {
291     if ((method_access_flags & kAccAbstract) != 0) {
292       // Abstract method, no code.
293       return;
294     }
295     const OatHeader& oat_header = oat_file_->GetOatHeader();
296     const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
297     if (method_header == nullptr || method_header->GetCodeSize() == 0) {
298       // No code.
299       return;
300     }
301 
302     uint32_t entry_point = oat_method.GetCodeOffset() - oat_header.GetExecutableOffset();
303     // Clear Thumb2 bit.
304     const void* code_address = EntryPointToCodePointer(reinterpret_cast<void*>(entry_point));
305 
306     debug::MethodDebugInfo info = {};
307     DCHECK(info.custom_name.empty());
308     info.dex_file = &dex_file;
309     info.class_def_index = class_def_index;
310     info.dex_method_index = dex_method_index;
311     info.access_flags = method_access_flags;
312     info.code_item = code_item;
313     info.isa = oat_header.GetInstructionSet();
314     info.deduped = !seen_offsets_.insert(oat_method.GetCodeOffset()).second;
315     info.is_native_debuggable = oat_header.IsNativeDebuggable();
316     info.is_optimized = method_header->IsOptimized();
317     info.is_code_address_text_relative = true;
318     info.code_address = reinterpret_cast<uintptr_t>(code_address);
319     info.code_size = method_header->GetCodeSize();
320     info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
321     info.code_info = info.is_optimized ? method_header->GetOptimizedCodeInfoPtr() : nullptr;
322     info.cfi = ArrayRef<uint8_t>();
323     method_debug_infos_.push_back(info);
324   }
325 
326  private:
327   const OatFile* oat_file_;
328   std::unique_ptr<ElfBuilder<ElfTypes>> builder_;
329   std::vector<debug::MethodDebugInfo> method_debug_infos_;
330   std::unordered_set<uint32_t> seen_offsets_;
331   const std::string output_name_;
332   bool no_bits_;
333 };
334 
335 class OatDumperOptions {
336  public:
OatDumperOptions(bool dump_vmap,bool dump_code_info_stack_maps,bool disassemble_code,bool absolute_addresses,const char * class_filter,const char * method_filter,bool list_classes,bool list_methods,bool dump_header_only,const char * export_dex_location,const char * app_image,const char * app_oat,uint32_t addr2instr)337   OatDumperOptions(bool dump_vmap,
338                    bool dump_code_info_stack_maps,
339                    bool disassemble_code,
340                    bool absolute_addresses,
341                    const char* class_filter,
342                    const char* method_filter,
343                    bool list_classes,
344                    bool list_methods,
345                    bool dump_header_only,
346                    const char* export_dex_location,
347                    const char* app_image,
348                    const char* app_oat,
349                    uint32_t addr2instr)
350     : dump_vmap_(dump_vmap),
351       dump_code_info_stack_maps_(dump_code_info_stack_maps),
352       disassemble_code_(disassemble_code),
353       absolute_addresses_(absolute_addresses),
354       class_filter_(class_filter),
355       method_filter_(method_filter),
356       list_classes_(list_classes),
357       list_methods_(list_methods),
358       dump_header_only_(dump_header_only),
359       export_dex_location_(export_dex_location),
360       app_image_(app_image),
361       app_oat_(app_oat),
362       addr2instr_(addr2instr),
363       class_loader_(nullptr) {}
364 
365   const bool dump_vmap_;
366   const bool dump_code_info_stack_maps_;
367   const bool disassemble_code_;
368   const bool absolute_addresses_;
369   const char* const class_filter_;
370   const char* const method_filter_;
371   const bool list_classes_;
372   const bool list_methods_;
373   const bool dump_header_only_;
374   const char* const export_dex_location_;
375   const char* const app_image_;
376   const char* const app_oat_;
377   uint32_t addr2instr_;
378   Handle<mirror::ClassLoader>* class_loader_;
379 };
380 
381 class OatDumper {
382  public:
OatDumper(const OatFile & oat_file,const OatDumperOptions & options)383   OatDumper(const OatFile& oat_file, const OatDumperOptions& options)
384     : oat_file_(oat_file),
385       oat_dex_files_(oat_file.GetOatDexFiles()),
386       options_(options),
387       resolved_addr2instr_(0),
388       instruction_set_(oat_file_.GetOatHeader().GetInstructionSet()),
389       disassembler_(Disassembler::Create(instruction_set_,
390                                          new DisassemblerOptions(
391                                              options_.absolute_addresses_,
392                                              oat_file.Begin(),
393                                              oat_file.End(),
394                                              /* can_read_literals_= */ true,
395                                              Is64BitInstructionSet(instruction_set_)
396                                                  ? &Thread::DumpThreadOffset<PointerSize::k64>
397                                                  : &Thread::DumpThreadOffset<PointerSize::k32>))) {
398     CHECK(options_.class_loader_ != nullptr);
399     CHECK(options_.class_filter_ != nullptr);
400     CHECK(options_.method_filter_ != nullptr);
401     AddAllOffsets();
402   }
403 
~OatDumper()404   ~OatDumper() {
405     delete disassembler_;
406   }
407 
GetInstructionSet()408   InstructionSet GetInstructionSet() {
409     return instruction_set_;
410   }
411 
412   using DexFileUniqV = std::vector<std::unique_ptr<const DexFile>>;
413 
Dump(std::ostream & os)414   bool Dump(std::ostream& os) {
415     bool success = true;
416     const OatHeader& oat_header = oat_file_.GetOatHeader();
417 
418     os << "MAGIC:\n";
419     os << oat_header.GetMagic() << "\n\n";
420 
421     os << "LOCATION:\n";
422     os << oat_file_.GetLocation() << "\n\n";
423 
424     os << "CHECKSUM:\n";
425     os << StringPrintf("0x%08x\n\n", oat_header.GetChecksum());
426 
427     os << "INSTRUCTION SET:\n";
428     os << oat_header.GetInstructionSet() << "\n\n";
429 
430     {
431       std::unique_ptr<const InstructionSetFeatures> features(
432           InstructionSetFeatures::FromBitmap(oat_header.GetInstructionSet(),
433                                              oat_header.GetInstructionSetFeaturesBitmap()));
434       os << "INSTRUCTION SET FEATURES:\n";
435       os << features->GetFeatureString() << "\n\n";
436     }
437 
438     os << "DEX FILE COUNT:\n";
439     os << oat_header.GetDexFileCount() << "\n\n";
440 
441 #define DUMP_OAT_HEADER_OFFSET(label, offset) \
442     os << label " OFFSET:\n"; \
443     os << StringPrintf("0x%08x", oat_header.offset()); \
444     if (oat_header.offset() != 0 && options_.absolute_addresses_) { \
445       os << StringPrintf(" (%p)", oat_file_.Begin() + oat_header.offset()); \
446     } \
447     os << StringPrintf("\n\n");
448 
449     DUMP_OAT_HEADER_OFFSET("EXECUTABLE", GetExecutableOffset);
450     DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP TRAMPOLINE",
451                            GetJniDlsymLookupTrampolineOffset);
452     DUMP_OAT_HEADER_OFFSET("JNI DLSYM LOOKUP CRITICAL TRAMPOLINE",
453                            GetJniDlsymLookupCriticalTrampolineOffset);
454     DUMP_OAT_HEADER_OFFSET("QUICK GENERIC JNI TRAMPOLINE",
455                            GetQuickGenericJniTrampolineOffset);
456     DUMP_OAT_HEADER_OFFSET("QUICK IMT CONFLICT TRAMPOLINE",
457                            GetQuickImtConflictTrampolineOffset);
458     DUMP_OAT_HEADER_OFFSET("QUICK RESOLUTION TRAMPOLINE",
459                            GetQuickResolutionTrampolineOffset);
460     DUMP_OAT_HEADER_OFFSET("QUICK TO INTERPRETER BRIDGE",
461                            GetQuickToInterpreterBridgeOffset);
462     DUMP_OAT_HEADER_OFFSET("NTERP_TRAMPOLINE",
463                            GetNterpTrampolineOffset);
464 #undef DUMP_OAT_HEADER_OFFSET
465 
466     // Print the key-value store.
467     {
468       os << "KEY VALUE STORE:\n";
469       size_t index = 0;
470       const char* key;
471       const char* value;
472       while (oat_header.GetStoreKeyValuePairByIndex(index, &key, &value)) {
473         os << key << " = " << value << "\n";
474         index++;
475       }
476       os << "\n";
477     }
478 
479     if (options_.absolute_addresses_) {
480       os << "BEGIN:\n";
481       os << reinterpret_cast<const void*>(oat_file_.Begin()) << "\n\n";
482 
483       os << "END:\n";
484       os << reinterpret_cast<const void*>(oat_file_.End()) << "\n\n";
485     }
486 
487     os << "SIZE:\n";
488     os << oat_file_.Size() << "\n\n";
489 
490     os << std::flush;
491 
492     // If set, adjust relative address to be searched
493     if (options_.addr2instr_ != 0) {
494       resolved_addr2instr_ = options_.addr2instr_ + oat_header.GetExecutableOffset();
495       os << "SEARCH ADDRESS (executable offset + input):\n";
496       os << StringPrintf("0x%08x\n\n", resolved_addr2instr_);
497     }
498 
499     // Dump .data.bimg.rel.ro entries.
500     DumpDataBimgRelRoEntries(os);
501 
502     // Dump .bss summary, individual entries are dumped per dex file.
503     os << ".bss: ";
504     if (oat_file_.GetBssMethods().empty() && oat_file_.GetBssGcRoots().empty()) {
505       os << "empty.\n\n";
506     } else {
507       os << oat_file_.GetBssMethods().size() << " methods, ";
508       os << oat_file_.GetBssGcRoots().size() << " GC roots.\n\n";
509     }
510 
511     // Dumping the dex file overview is compact enough to do even if header only.
512     for (size_t i = 0; i < oat_dex_files_.size(); i++) {
513       const OatDexFile* oat_dex_file = oat_dex_files_[i];
514       CHECK(oat_dex_file != nullptr);
515       std::string error_msg;
516       const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
517       if (dex_file == nullptr) {
518         os << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation() << "': "
519            << error_msg;
520         continue;
521       }
522 
523       const DexLayoutSections* const layout_sections = oat_dex_file->GetDexLayoutSections();
524       if (layout_sections != nullptr) {
525         os << "Layout data\n";
526         os << *layout_sections;
527         os << "\n";
528       }
529 
530       if (!options_.dump_header_only_) {
531         // Dump .bss entries.
532         DumpBssEntries(
533             os,
534             "ArtMethod",
535             oat_dex_file->GetMethodBssMapping(),
536             dex_file->NumMethodIds(),
537             static_cast<size_t>(GetInstructionSetPointerSize(instruction_set_)),
538             [=](uint32_t index) { return dex_file->PrettyMethod(index); });
539         DumpBssEntries(
540             os,
541             "Class",
542             oat_dex_file->GetTypeBssMapping(),
543             dex_file->NumTypeIds(),
544             sizeof(GcRoot<mirror::Class>),
545             [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
546         DumpBssEntries(
547             os,
548             "Public Class",
549             oat_dex_file->GetPublicTypeBssMapping(),
550             dex_file->NumTypeIds(),
551             sizeof(GcRoot<mirror::Class>),
552             [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
553         DumpBssEntries(
554             os,
555             "Package Class",
556             oat_dex_file->GetPackageTypeBssMapping(),
557             dex_file->NumTypeIds(),
558             sizeof(GcRoot<mirror::Class>),
559             [=](uint32_t index) { return dex_file->PrettyType(dex::TypeIndex(index)); });
560         DumpBssEntries(
561             os,
562             "String",
563             oat_dex_file->GetStringBssMapping(),
564             dex_file->NumStringIds(),
565             sizeof(GcRoot<mirror::Class>),
566             [=](uint32_t index) { return dex_file->StringDataByIdx(dex::StringIndex(index)); });
567       }
568     }
569 
570     if (!options_.dump_header_only_) {
571       VariableIndentationOutputStream vios(&os);
572       VdexFile::VdexFileHeader vdex_header = oat_file_.GetVdexFile()->GetVdexFileHeader();
573       if (vdex_header.IsValid()) {
574         std::string error_msg;
575         std::vector<const DexFile*> dex_files;
576         for (size_t i = 0; i < oat_dex_files_.size(); i++) {
577           const DexFile* dex_file = OpenDexFile(oat_dex_files_[i], &error_msg);
578           if (dex_file == nullptr) {
579             os << "Error opening dex file: " << error_msg << std::endl;
580             return false;
581           }
582           dex_files.push_back(dex_file);
583         }
584         verifier::VerifierDeps deps(dex_files, /*output_only=*/ false);
585         if (!deps.ParseStoredData(dex_files, oat_file_.GetVdexFile()->GetVerifierDepsData())) {
586           os << "Error parsing verifier dependencies." << std::endl;
587           return false;
588         }
589         deps.Dump(&vios);
590       } else {
591         os << "UNRECOGNIZED vdex file, magic "
592            << vdex_header.GetMagic()
593            << ", version "
594            << vdex_header.GetVdexVersion()
595            << "\n";
596       }
597       for (size_t i = 0; i < oat_dex_files_.size(); i++) {
598         const OatDexFile* oat_dex_file = oat_dex_files_[i];
599         CHECK(oat_dex_file != nullptr);
600         if (!DumpOatDexFile(os, *oat_dex_file)) {
601           success = false;
602         }
603       }
604     }
605 
606     if (options_.export_dex_location_) {
607       std::string error_msg;
608       std::string vdex_filename = GetVdexFilename(oat_file_.GetLocation());
609       if (!OS::FileExists(vdex_filename.c_str())) {
610         os << "File " << vdex_filename.c_str() << " does not exist\n";
611         return false;
612       }
613 
614       DexFileUniqV vdex_dex_files;
615       std::unique_ptr<const VdexFile> vdex_file = OpenVdex(vdex_filename,
616                                                            &vdex_dex_files,
617                                                            &error_msg);
618       if (vdex_file.get() == nullptr) {
619         os << "Failed to open vdex file: " << error_msg << "\n";
620         return false;
621       }
622       if (oat_dex_files_.size() != vdex_dex_files.size()) {
623         os << "Dex files number in Vdex file does not match Dex files number in Oat file: "
624            << vdex_dex_files.size() << " vs " << oat_dex_files_.size() << '\n';
625         return false;
626       }
627 
628       size_t i = 0;
629       for (const auto& vdex_dex_file : vdex_dex_files) {
630         const OatDexFile* oat_dex_file = oat_dex_files_[i];
631         CHECK(oat_dex_file != nullptr);
632         CHECK(vdex_dex_file != nullptr);
633 
634         // If a CompactDex file is detected within a Vdex container, DexLayout is used to convert
635         // back to a StandardDex file. Since the converted DexFile will most likely not reproduce
636         // the original input Dex file, the `update_checksum_` option is used to recompute the
637         // checksum. If the vdex container does not contain cdex resources (`used_dexlayout` is
638         // false), ExportDexFile() enforces a reproducible checksum verification.
639         if (vdex_dex_file->IsCompactDexFile()) {
640           Options options;
641           options.compact_dex_level_ = CompactDexLevel::kCompactDexLevelNone;
642           options.update_checksum_ = true;
643           DexLayout dex_layout(options, /*info=*/ nullptr, /*out_file=*/ nullptr, /*header=*/ nullptr);
644           std::unique_ptr<art::DexContainer> dex_container;
645           bool result = dex_layout.ProcessDexFile(vdex_dex_file->GetLocation().c_str(),
646                                                   vdex_dex_file.get(),
647                                                   i,
648                                                   &dex_container,
649                                                   &error_msg);
650           if (!result) {
651             os << "DexLayout failed to process Dex file: " + error_msg;
652             success = false;
653             break;
654           }
655           DexContainer::Section* main_section = dex_container->GetMainSection();
656           CHECK_EQ(dex_container->GetDataSection()->Size(), 0u);
657 
658           const ArtDexFileLoader dex_file_loader;
659           std::unique_ptr<const DexFile> dex(dex_file_loader.Open(
660               main_section->Begin(),
661               main_section->Size(),
662               vdex_dex_file->GetLocation(),
663               vdex_file->GetLocationChecksum(i),
664               /*oat_dex_file=*/ nullptr,
665               /*verify=*/ false,
666               /*verify_checksum=*/ true,
667               &error_msg));
668           if (dex == nullptr) {
669             os << "Failed to load DexFile from layout container: " + error_msg;
670             success = false;
671             break;
672           }
673           if (dex->IsCompactDexFile()) {
674             os <<"CompactDex conversion to StandardDex failed";
675             success = false;
676             break;
677           }
678 
679           if (!ExportDexFile(os, *oat_dex_file, dex.get(), /*used_dexlayout=*/ true)) {
680             success = false;
681             break;
682           }
683         } else {
684           if (!ExportDexFile(os, *oat_dex_file, vdex_dex_file.get(), /*used_dexlayout=*/ false)) {
685             success = false;
686             break;
687           }
688         }
689         i++;
690       }
691     }
692 
693     {
694       os << "OAT FILE STATS:\n";
695       VariableIndentationOutputStream vios(&os);
696       stats_.AddBytes(oat_file_.Size());
697       stats_.DumpSizes(vios, "OatFile");
698     }
699 
700     os << std::flush;
701     return success;
702   }
703 
ComputeSize(const void * oat_data)704   size_t ComputeSize(const void* oat_data) {
705     if (reinterpret_cast<const uint8_t*>(oat_data) < oat_file_.Begin() ||
706         reinterpret_cast<const uint8_t*>(oat_data) > oat_file_.End()) {
707       return 0;  // Address not in oat file
708     }
709     uintptr_t begin_offset = reinterpret_cast<uintptr_t>(oat_data) -
710                              reinterpret_cast<uintptr_t>(oat_file_.Begin());
711     auto it = offsets_.upper_bound(begin_offset);
712     CHECK(it != offsets_.end());
713     uintptr_t end_offset = *it;
714     return end_offset - begin_offset;
715   }
716 
GetOatInstructionSet()717   InstructionSet GetOatInstructionSet() {
718     return oat_file_.GetOatHeader().GetInstructionSet();
719   }
720 
GetQuickOatCode(ArtMethod * m)721   const void* GetQuickOatCode(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
722     for (size_t i = 0; i < oat_dex_files_.size(); i++) {
723       const OatDexFile* oat_dex_file = oat_dex_files_[i];
724       CHECK(oat_dex_file != nullptr);
725       std::string error_msg;
726       const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
727       if (dex_file == nullptr) {
728         LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
729             << "': " << error_msg;
730       } else {
731         const char* descriptor = m->GetDeclaringClassDescriptor();
732         const dex::ClassDef* class_def =
733             OatDexFile::FindClassDef(*dex_file, descriptor, ComputeModifiedUtf8Hash(descriptor));
734         if (class_def != nullptr) {
735           uint16_t class_def_index = dex_file->GetIndexForClassDef(*class_def);
736           const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(class_def_index);
737           uint32_t oat_method_index;
738           if (m->IsStatic() || m->IsDirect()) {
739             // Simple case where the oat method index was stashed at load time.
740             oat_method_index = m->GetMethodIndex();
741           } else {
742             // Compute the oat_method_index by search for its position in the class def.
743             ClassAccessor accessor(*dex_file, *class_def);
744             oat_method_index = accessor.NumDirectMethods();
745             bool found_virtual = false;
746             for (ClassAccessor::Method dex_method : accessor.GetVirtualMethods()) {
747               // Check method index instead of identity in case of duplicate method definitions.
748               if (dex_method.GetIndex() == m->GetDexMethodIndex()) {
749                 found_virtual = true;
750                 break;
751               }
752               ++oat_method_index;
753             }
754             CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
755                                  << dex_file->PrettyMethod(m->GetDexMethodIndex());
756           }
757           return oat_class.GetOatMethod(oat_method_index).GetQuickCode();
758         }
759       }
760     }
761     return nullptr;
762   }
763 
764   // Returns nullptr and updates error_msg if the Vdex file cannot be opened, otherwise all Dex
765   // files are stored in dex_files.
OpenVdex(const std::string & vdex_filename,DexFileUniqV * dex_files,std::string * error_msg)766   std::unique_ptr<const VdexFile> OpenVdex(const std::string& vdex_filename,
767                                            /* out */ DexFileUniqV* dex_files,
768                                            /* out */ std::string* error_msg) {
769     std::unique_ptr<const File> file(OS::OpenFileForReading(vdex_filename.c_str()));
770     if (file == nullptr) {
771       *error_msg = "Could not open file " + vdex_filename + " for reading.";
772       return nullptr;
773     }
774 
775     int64_t vdex_length = file->GetLength();
776     if (vdex_length == -1) {
777       *error_msg = "Could not read the length of file " + vdex_filename;
778       return nullptr;
779     }
780 
781     MemMap mmap = MemMap::MapFile(
782         file->GetLength(),
783         PROT_READ | PROT_WRITE,
784         MAP_PRIVATE,
785         file->Fd(),
786         /* start offset= */ 0,
787         /* low_4gb= */ false,
788         vdex_filename.c_str(),
789         error_msg);
790     if (!mmap.IsValid()) {
791       *error_msg = "Failed to mmap file " + vdex_filename + ": " + *error_msg;
792       return nullptr;
793     }
794 
795     std::unique_ptr<VdexFile> vdex_file(new VdexFile(std::move(mmap)));
796     if (!vdex_file->IsValid()) {
797       *error_msg = "Vdex file is not valid";
798       return nullptr;
799     }
800 
801     DexFileUniqV tmp_dex_files;
802     if (!vdex_file->OpenAllDexFiles(&tmp_dex_files, error_msg)) {
803       *error_msg = "Failed to open Dex files from Vdex: " + *error_msg;
804       return nullptr;
805     }
806 
807     *dex_files = std::move(tmp_dex_files);
808     return vdex_file;
809   }
810 
AddStatsObject(const void * address)811   bool AddStatsObject(const void* address) {
812     return seen_stats_objects_.insert(address).second;  // Inserted new entry.
813   }
814 
815  private:
AddAllOffsets()816   void AddAllOffsets() {
817     // We don't know the length of the code for each method, but we need to know where to stop
818     // when disassembling. What we do know is that a region of code will be followed by some other
819     // region, so if we keep a sorted sequence of the start of each region, we can infer the length
820     // of a piece of code by using upper_bound to find the start of the next region.
821     for (size_t i = 0; i < oat_dex_files_.size(); i++) {
822       const OatDexFile* oat_dex_file = oat_dex_files_[i];
823       CHECK(oat_dex_file != nullptr);
824       std::string error_msg;
825       const DexFile* const dex_file = OpenDexFile(oat_dex_file, &error_msg);
826       if (dex_file == nullptr) {
827         LOG(WARNING) << "Failed to open dex file '" << oat_dex_file->GetDexFileLocation()
828             << "': " << error_msg;
829         continue;
830       }
831       offsets_.insert(reinterpret_cast<uintptr_t>(&dex_file->GetHeader()));
832       for (ClassAccessor accessor : dex_file->GetClasses()) {
833         const OatFile::OatClass oat_class = oat_dex_file->GetOatClass(accessor.GetClassDefIndex());
834         for (uint32_t class_method_index = 0;
835             class_method_index < accessor.NumMethods();
836             ++class_method_index) {
837           AddOffsets(oat_class.GetOatMethod(class_method_index));
838         }
839       }
840     }
841 
842     // If the last thing in the file is code for a method, there won't be an offset for the "next"
843     // thing. Instead of having a special case in the upper_bound code, let's just add an entry
844     // for the end of the file.
845     offsets_.insert(oat_file_.Size());
846   }
847 
AlignCodeOffset(uint32_t maybe_thumb_offset)848   static uint32_t AlignCodeOffset(uint32_t maybe_thumb_offset) {
849     return maybe_thumb_offset & ~0x1;  // TODO: Make this Thumb2 specific.
850   }
851 
AddOffsets(const OatFile::OatMethod & oat_method)852   void AddOffsets(const OatFile::OatMethod& oat_method) {
853     uint32_t code_offset = oat_method.GetCodeOffset();
854     if (oat_file_.GetOatHeader().GetInstructionSet() == InstructionSet::kThumb2) {
855       code_offset &= ~0x1;
856     }
857     offsets_.insert(code_offset);
858     offsets_.insert(oat_method.GetVmapTableOffset());
859   }
860 
DumpOatDexFile(std::ostream & os,const OatDexFile & oat_dex_file)861   bool DumpOatDexFile(std::ostream& os, const OatDexFile& oat_dex_file) {
862     bool success = true;
863     bool stop_analysis = false;
864     os << "OatDexFile:\n";
865     os << StringPrintf("location: %s\n", oat_dex_file.GetDexFileLocation().c_str());
866     os << StringPrintf("checksum: 0x%08x\n", oat_dex_file.GetDexFileLocationChecksum());
867 
868     const uint8_t* const oat_file_begin = oat_dex_file.GetOatFile()->Begin();
869     if (oat_dex_file.GetOatFile()->ContainsDexCode()) {
870       const uint8_t* const vdex_file_begin = oat_dex_file.GetOatFile()->DexBegin();
871 
872       // Print data range of the dex file embedded inside the corresponding vdex file.
873       const uint8_t* const dex_file_pointer = oat_dex_file.GetDexFilePointer();
874       uint32_t dex_offset = dchecked_integral_cast<uint32_t>(dex_file_pointer - vdex_file_begin);
875       os << StringPrintf(
876           "dex-file: 0x%08x..0x%08x\n",
877           dex_offset,
878           dchecked_integral_cast<uint32_t>(dex_offset + oat_dex_file.FileSize() - 1));
879     } else {
880       os << StringPrintf("dex-file not in VDEX file\n");
881     }
882 
883     // Create the dex file early. A lot of print-out things depend on it.
884     std::string error_msg;
885     const DexFile* const dex_file = OpenDexFile(&oat_dex_file, &error_msg);
886     if (dex_file == nullptr) {
887       os << "NOT FOUND: " << error_msg << "\n\n";
888       os << std::flush;
889       return false;
890     }
891 
892     // Print lookup table, if it exists.
893     if (oat_dex_file.GetLookupTableData() != nullptr) {
894       uint32_t table_offset = dchecked_integral_cast<uint32_t>(
895           oat_dex_file.GetLookupTableData() - oat_file_begin);
896       uint32_t table_size = TypeLookupTable::RawDataLength(dex_file->NumClassDefs());
897       os << StringPrintf("type-table: 0x%08x..0x%08x\n",
898                          table_offset,
899                          table_offset + table_size - 1);
900     }
901 
902     VariableIndentationOutputStream vios(&os);
903     ScopedIndentation indent1(&vios);
904     for (ClassAccessor accessor : dex_file->GetClasses()) {
905       // TODO: Support regex
906       const char* descriptor = accessor.GetDescriptor();
907       if (DescriptorToDot(descriptor).find(options_.class_filter_) == std::string::npos) {
908         continue;
909       }
910 
911       const uint16_t class_def_index = accessor.GetClassDefIndex();
912       uint32_t oat_class_offset = oat_dex_file.GetOatClassOffset(class_def_index);
913       const OatFile::OatClass oat_class = oat_dex_file.GetOatClass(class_def_index);
914       os << StringPrintf("%zd: %s (offset=0x%08x) (type_idx=%d)",
915                          static_cast<ssize_t>(class_def_index),
916                          descriptor,
917                          oat_class_offset,
918                          accessor.GetClassIdx().index_)
919          << " (" << oat_class.GetStatus() << ")"
920          << " (" << oat_class.GetType() << ")\n";
921       // TODO: include bitmap here if type is kOatClassSomeCompiled?
922       if (options_.list_classes_) {
923         continue;
924       }
925       if (!DumpOatClass(&vios, oat_class, *dex_file, accessor, &stop_analysis)) {
926         success = false;
927       }
928       if (stop_analysis) {
929         os << std::flush;
930         return success;
931       }
932     }
933     os << "\n";
934     os << std::flush;
935     return success;
936   }
937 
938   // Backwards compatible Dex file export. If dex_file is nullptr (valid Vdex file not present) the
939   // Dex resource is extracted from the oat_dex_file and its checksum is repaired since it's not
940   // unquickened. Otherwise the dex_file has been fully unquickened and is expected to verify the
941   // original checksum.
ExportDexFile(std::ostream & os,const OatDexFile & oat_dex_file,const DexFile * dex_file,bool used_dexlayout)942   bool ExportDexFile(std::ostream& os,
943                      const OatDexFile& oat_dex_file,
944                      const DexFile* dex_file,
945                      bool used_dexlayout) {
946     std::string error_msg;
947     std::string dex_file_location = oat_dex_file.GetDexFileLocation();
948 
949     // If dex_file (from unquicken or dexlayout) is not available, the output DexFile size is the
950     // same as the one extracted from the Oat container (pre-oreo)
951     size_t fsize = dex_file == nullptr ? oat_dex_file.FileSize() : dex_file->Size();
952 
953     // Some quick checks just in case
954     if (fsize == 0 || fsize < sizeof(DexFile::Header)) {
955       os << "Invalid dex file\n";
956       return false;
957     }
958 
959     if (dex_file == nullptr) {
960       // Exported bytecode is quickened (dex-to-dex transformations present)
961       dex_file = OpenDexFile(&oat_dex_file, &error_msg);
962       if (dex_file == nullptr) {
963         os << "Failed to open dex file '" << dex_file_location << "': " << error_msg;
964         return false;
965       }
966 
967       // Recompute checksum
968       reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_ =
969           dex_file->CalculateChecksum();
970     } else {
971       // If dexlayout was used to convert CompactDex back to StandardDex, checksum will be updated
972       // due to `update_checksum_` option, otherwise we expect a reproducible checksum.
973       if (!used_dexlayout) {
974         // Vdex unquicken output should match original input bytecode
975         uint32_t orig_checksum =
976             reinterpret_cast<DexFile::Header*>(const_cast<uint8_t*>(dex_file->Begin()))->checksum_;
977         if (orig_checksum != dex_file->CalculateChecksum()) {
978           os << "Unexpected checksum from unquicken dex file '" << dex_file_location << "'\n";
979           return false;
980         }
981       }
982     }
983 
984     // Verify output directory exists
985     if (!OS::DirectoryExists(options_.export_dex_location_)) {
986       // TODO: Extend OS::DirectoryExists if symlink support is required
987       os << options_.export_dex_location_ << " output directory not found or symlink\n";
988       return false;
989     }
990 
991     // Beautify path names
992     if (dex_file_location.size() > PATH_MAX || dex_file_location.size() <= 0) {
993       return false;
994     }
995 
996     std::string dex_orig_name;
997     size_t dex_orig_pos = dex_file_location.rfind('/');
998     if (dex_orig_pos == std::string::npos)
999       dex_orig_name = dex_file_location;
1000     else
1001       dex_orig_name = dex_file_location.substr(dex_orig_pos + 1);
1002 
1003     // A more elegant approach to efficiently name user installed apps is welcome
1004     if (dex_orig_name.size() == 8 &&
1005         dex_orig_name.compare("base.apk") == 0 &&
1006         dex_orig_pos != std::string::npos) {
1007       dex_file_location.erase(dex_orig_pos, strlen("base.apk") + 1);
1008       size_t apk_orig_pos = dex_file_location.rfind('/');
1009       if (apk_orig_pos != std::string::npos) {
1010         dex_orig_name = dex_file_location.substr(++apk_orig_pos);
1011       }
1012     }
1013 
1014     std::string out_dex_path(options_.export_dex_location_);
1015     if (out_dex_path.back() != '/') {
1016       out_dex_path.append("/");
1017     }
1018     out_dex_path.append(dex_orig_name);
1019     out_dex_path.append("_export.dex");
1020     if (out_dex_path.length() > PATH_MAX) {
1021       return false;
1022     }
1023 
1024     std::unique_ptr<File> file(OS::CreateEmptyFile(out_dex_path.c_str()));
1025     if (file.get() == nullptr) {
1026       os << "Failed to open output dex file " << out_dex_path;
1027       return false;
1028     }
1029 
1030     bool success = file->WriteFully(dex_file->Begin(), fsize);
1031     if (!success) {
1032       os << "Failed to write dex file";
1033       file->Erase();
1034       return false;
1035     }
1036 
1037     if (file->FlushCloseOrErase() != 0) {
1038       os << "Flush and close failed";
1039       return false;
1040     }
1041 
1042     os << StringPrintf("Dex file exported at %s (%zd bytes)\n", out_dex_path.c_str(), fsize);
1043     os << std::flush;
1044 
1045     return true;
1046   }
1047 
DumpOatClass(VariableIndentationOutputStream * vios,const OatFile::OatClass & oat_class,const DexFile & dex_file,const ClassAccessor & class_accessor,bool * stop_analysis)1048   bool DumpOatClass(VariableIndentationOutputStream* vios,
1049                     const OatFile::OatClass& oat_class,
1050                     const DexFile& dex_file,
1051                     const ClassAccessor& class_accessor,
1052                     bool* stop_analysis) {
1053     bool success = true;
1054     bool addr_found = false;
1055     uint32_t class_method_index = 0;
1056     for (const ClassAccessor::Method& method : class_accessor.GetMethods()) {
1057       if (!DumpOatMethod(vios,
1058                          dex_file.GetClassDef(class_accessor.GetClassDefIndex()),
1059                          class_method_index,
1060                          oat_class,
1061                          dex_file,
1062                          method.GetIndex(),
1063                          method.GetCodeItem(),
1064                          method.GetAccessFlags(),
1065                          &addr_found)) {
1066         success = false;
1067       }
1068       if (addr_found) {
1069         *stop_analysis = true;
1070         return success;
1071       }
1072       class_method_index++;
1073     }
1074     vios->Stream() << std::flush;
1075     return success;
1076   }
1077 
1078   static constexpr uint32_t kPrologueBytes = 16;
1079 
1080   // When this was picked, the largest arm method was 55,256 bytes and arm64 was 50,412 bytes.
1081   static constexpr uint32_t kMaxCodeSize = 100 * 1000;
1082 
DumpOatMethod(VariableIndentationOutputStream * vios,const dex::ClassDef & class_def,uint32_t class_method_index,const OatFile::OatClass & oat_class,const DexFile & dex_file,uint32_t dex_method_idx,const dex::CodeItem * code_item,uint32_t method_access_flags,bool * addr_found)1083   bool DumpOatMethod(VariableIndentationOutputStream* vios,
1084                      const dex::ClassDef& class_def,
1085                      uint32_t class_method_index,
1086                      const OatFile::OatClass& oat_class,
1087                      const DexFile& dex_file,
1088                      uint32_t dex_method_idx,
1089                      const dex::CodeItem* code_item,
1090                      uint32_t method_access_flags,
1091                      bool* addr_found) {
1092     bool success = true;
1093 
1094     CodeItemDataAccessor code_item_accessor(dex_file, code_item);
1095 
1096     // TODO: Support regex
1097     std::string method_name = dex_file.GetMethodName(dex_file.GetMethodId(dex_method_idx));
1098     if (method_name.find(options_.method_filter_) == std::string::npos) {
1099       return success;
1100     }
1101 
1102     std::string pretty_method = dex_file.PrettyMethod(dex_method_idx, true);
1103     vios->Stream() << StringPrintf("%d: %s (dex_method_idx=%d)\n",
1104                                    class_method_index, pretty_method.c_str(),
1105                                    dex_method_idx);
1106     if (options_.list_methods_) {
1107       return success;
1108     }
1109 
1110     uint32_t oat_method_offsets_offset = oat_class.GetOatMethodOffsetsOffset(class_method_index);
1111     const OatMethodOffsets* oat_method_offsets = oat_class.GetOatMethodOffsets(class_method_index);
1112     const OatFile::OatMethod oat_method = oat_class.GetOatMethod(class_method_index);
1113     uint32_t code_offset = oat_method.GetCodeOffset();
1114     uint32_t code_size = oat_method.GetQuickCodeSize();
1115     if (resolved_addr2instr_ != 0) {
1116       if (resolved_addr2instr_ > code_offset + code_size) {
1117         return success;
1118       } else {
1119         *addr_found = true;  // stop analyzing file at next iteration
1120       }
1121     }
1122 
1123     // Everything below is indented at least once.
1124     ScopedIndentation indent1(vios);
1125 
1126     {
1127       vios->Stream() << "DEX CODE:\n";
1128       ScopedIndentation indent2(vios);
1129       if (code_item_accessor.HasCodeItem()) {
1130         uint32_t max_pc = code_item_accessor.InsnsSizeInCodeUnits();
1131         for (const DexInstructionPcPair& inst : code_item_accessor) {
1132           if (inst.DexPc() + inst->SizeInCodeUnits() > max_pc) {
1133             LOG(WARNING) << "GLITCH: run-away instruction at idx=0x" << std::hex << inst.DexPc();
1134             break;
1135           }
1136           vios->Stream() << StringPrintf("0x%04x: ", inst.DexPc()) << inst->DumpHexLE(5)
1137                          << StringPrintf("\t| %s\n", inst->DumpString(&dex_file).c_str());
1138         }
1139       }
1140     }
1141 
1142     std::unique_ptr<StackHandleScope<1>> hs;
1143     std::unique_ptr<verifier::MethodVerifier> verifier;
1144     if (Runtime::Current() != nullptr) {
1145       // We need to have the handle scope stay live until after the verifier since the verifier has
1146       // a handle to the dex cache from hs.
1147       hs.reset(new StackHandleScope<1>(Thread::Current()));
1148       vios->Stream() << "VERIFIER TYPE ANALYSIS:\n";
1149       ScopedIndentation indent2(vios);
1150       verifier.reset(DumpVerifier(vios, hs.get(),
1151                                   dex_method_idx, &dex_file, class_def, code_item,
1152                                   method_access_flags));
1153     }
1154     {
1155       vios->Stream() << "OatMethodOffsets ";
1156       if (options_.absolute_addresses_) {
1157         vios->Stream() << StringPrintf("%p ", oat_method_offsets);
1158       }
1159       vios->Stream() << StringPrintf("(offset=0x%08x)\n", oat_method_offsets_offset);
1160       if (oat_method_offsets_offset > oat_file_.Size()) {
1161         vios->Stream() << StringPrintf(
1162             "WARNING: oat method offsets offset 0x%08x is past end of file 0x%08zx.\n",
1163             oat_method_offsets_offset, oat_file_.Size());
1164         // If we can't read OatMethodOffsets, the rest of the data is dangerous to read.
1165         vios->Stream() << std::flush;
1166         return false;
1167       }
1168 
1169       ScopedIndentation indent2(vios);
1170       vios->Stream() << StringPrintf("code_offset: 0x%08x ", code_offset);
1171       uint32_t aligned_code_begin = AlignCodeOffset(oat_method.GetCodeOffset());
1172       if (aligned_code_begin > oat_file_.Size()) {
1173         vios->Stream() << StringPrintf("WARNING: "
1174                                        "code offset 0x%08x is past end of file 0x%08zx.\n",
1175                                        aligned_code_begin, oat_file_.Size());
1176         success = false;
1177       }
1178       vios->Stream() << "\n";
1179     }
1180     {
1181       vios->Stream() << "OatQuickMethodHeader ";
1182       uint32_t method_header_offset = oat_method.GetOatQuickMethodHeaderOffset();
1183       const OatQuickMethodHeader* method_header = oat_method.GetOatQuickMethodHeader();
1184       if (AddStatsObject(method_header)) {
1185         stats_["QuickMethodHeader"].AddBytes(sizeof(*method_header));
1186       }
1187       if (options_.absolute_addresses_) {
1188         vios->Stream() << StringPrintf("%p ", method_header);
1189       }
1190       vios->Stream() << StringPrintf("(offset=0x%08x)\n", method_header_offset);
1191       if (method_header_offset > oat_file_.Size() ||
1192           sizeof(OatQuickMethodHeader) > oat_file_.Size() - method_header_offset) {
1193         vios->Stream() << StringPrintf(
1194             "WARNING: oat quick method header at offset 0x%08x is past end of file 0x%08zx.\n",
1195             method_header_offset, oat_file_.Size());
1196         // If we can't read the OatQuickMethodHeader, the rest of the data is dangerous to read.
1197         vios->Stream() << std::flush;
1198         return false;
1199       }
1200 
1201       ScopedIndentation indent2(vios);
1202       vios->Stream() << "vmap_table: ";
1203       if (options_.absolute_addresses_) {
1204         vios->Stream() << StringPrintf("%p ", oat_method.GetVmapTable());
1205       }
1206       uint32_t vmap_table_offset =
1207           (method_header == nullptr) ? 0 : method_header->GetCodeInfoOffset();
1208       vios->Stream() << StringPrintf("(offset=0x%08x)\n", vmap_table_offset);
1209 
1210       size_t vmap_table_offset_limit =
1211           IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)
1212               ? oat_file_.GetVdexFile()->Size()
1213               : method_header->GetCode() - oat_file_.Begin();
1214       if (vmap_table_offset >= vmap_table_offset_limit) {
1215         vios->Stream() << StringPrintf("WARNING: "
1216                                        "vmap table offset 0x%08x is past end of file 0x%08zx. ",
1217                                        vmap_table_offset,
1218                                        vmap_table_offset_limit);
1219         success = false;
1220       } else if (options_.dump_vmap_) {
1221         DumpVmapData(vios, oat_method, code_item_accessor);
1222       }
1223     }
1224     {
1225       vios->Stream() << "QuickMethodFrameInfo\n";
1226 
1227       ScopedIndentation indent2(vios);
1228       vios->Stream()
1229           << StringPrintf("frame_size_in_bytes: %zd\n", oat_method.GetFrameSizeInBytes());
1230       vios->Stream() << StringPrintf("core_spill_mask: 0x%08x ", oat_method.GetCoreSpillMask());
1231       DumpSpillMask(vios->Stream(), oat_method.GetCoreSpillMask(), false);
1232       vios->Stream() << "\n";
1233       vios->Stream() << StringPrintf("fp_spill_mask: 0x%08x ", oat_method.GetFpSpillMask());
1234       DumpSpillMask(vios->Stream(), oat_method.GetFpSpillMask(), true);
1235       vios->Stream() << "\n";
1236     }
1237     {
1238       // Based on spill masks from QuickMethodFrameInfo so placed
1239       // after it is dumped, but useful for understanding quick
1240       // code, so dumped here.
1241       ScopedIndentation indent2(vios);
1242       DumpVregLocations(vios->Stream(), oat_method, code_item_accessor);
1243     }
1244     {
1245       vios->Stream() << "CODE: ";
1246       {
1247         const void* code = oat_method.GetQuickCode();
1248         uint32_t aligned_code_begin = AlignCodeOffset(code_offset);
1249         uint64_t aligned_code_end = aligned_code_begin + code_size;
1250         if (AddStatsObject(code)) {
1251           stats_["Code"].AddBytes(code_size);
1252         }
1253 
1254         if (options_.absolute_addresses_) {
1255           vios->Stream() << StringPrintf("%p ", code);
1256         }
1257         vios->Stream() << StringPrintf("(code_offset=0x%08x size=%u)%s\n",
1258                                        code_offset,
1259                                        code_size,
1260                                        code != nullptr ? "..." : "");
1261 
1262         ScopedIndentation indent2(vios);
1263         if (aligned_code_begin > oat_file_.Size()) {
1264           vios->Stream() << StringPrintf("WARNING: "
1265                                          "start of code at 0x%08x is past end of file 0x%08zx.",
1266                                          aligned_code_begin, oat_file_.Size());
1267           success = false;
1268         } else if (aligned_code_end > oat_file_.Size()) {
1269           vios->Stream() << StringPrintf(
1270               "WARNING: "
1271               "end of code at 0x%08" PRIx64 " is past end of file 0x%08zx. "
1272               "code size is 0x%08x.\n",
1273               aligned_code_end,
1274               oat_file_.Size(),
1275               code_size);
1276           success = false;
1277           if (options_.disassemble_code_) {
1278             if (aligned_code_begin + kPrologueBytes <= oat_file_.Size()) {
1279               DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
1280             }
1281           }
1282         } else if (code_size > kMaxCodeSize) {
1283           vios->Stream() << StringPrintf(
1284               "WARNING: "
1285               "code size %d is bigger than max expected threshold of %d. "
1286               "code size is 0x%08x.\n",
1287               code_size,
1288               kMaxCodeSize,
1289               code_size);
1290           success = false;
1291           if (options_.disassemble_code_) {
1292             if (aligned_code_begin + kPrologueBytes <= oat_file_.Size()) {
1293               DumpCode(vios, oat_method, code_item_accessor, true, kPrologueBytes);
1294             }
1295           }
1296         } else if (options_.disassemble_code_) {
1297           DumpCode(vios, oat_method, code_item_accessor, !success, 0);
1298         }
1299       }
1300     }
1301     vios->Stream() << std::flush;
1302     return success;
1303   }
1304 
DumpSpillMask(std::ostream & os,uint32_t spill_mask,bool is_float)1305   void DumpSpillMask(std::ostream& os, uint32_t spill_mask, bool is_float) {
1306     if (spill_mask == 0) {
1307       return;
1308     }
1309     os << "(";
1310     for (size_t i = 0; i < 32; i++) {
1311       if ((spill_mask & (1 << i)) != 0) {
1312         if (is_float) {
1313           os << "fr" << i;
1314         } else {
1315           os << "r" << i;
1316         }
1317         spill_mask ^= 1 << i;  // clear bit
1318         if (spill_mask != 0) {
1319           os << ", ";
1320         } else {
1321           break;
1322         }
1323       }
1324     }
1325     os << ")";
1326   }
1327 
1328   // Display data stored at the the vmap offset of an oat method.
DumpVmapData(VariableIndentationOutputStream * vios,const OatFile::OatMethod & oat_method,const CodeItemDataAccessor & code_item_accessor)1329   void DumpVmapData(VariableIndentationOutputStream* vios,
1330                     const OatFile::OatMethod& oat_method,
1331                     const CodeItemDataAccessor& code_item_accessor) {
1332     if (IsMethodGeneratedByOptimizingCompiler(oat_method, code_item_accessor)) {
1333       // The optimizing compiler outputs its CodeInfo data in the vmap table.
1334       const uint8_t* raw_code_info = oat_method.GetVmapTable();
1335       if (raw_code_info != nullptr) {
1336         CodeInfo code_info(raw_code_info);
1337         DCHECK(code_item_accessor.HasCodeItem());
1338         ScopedIndentation indent1(vios);
1339         DumpCodeInfo(vios, code_info, oat_method);
1340       }
1341     } else if (IsMethodGeneratedByDexToDexCompiler(oat_method, code_item_accessor)) {
1342       // We don't encode the size in the table, so just emit that we have quickened
1343       // information.
1344       ScopedIndentation indent(vios);
1345       vios->Stream() << "quickened data\n";
1346     } else {
1347       // Otherwise, there is nothing to display.
1348     }
1349   }
1350 
1351   // Display a CodeInfo object emitted by the optimizing compiler.
DumpCodeInfo(VariableIndentationOutputStream * vios,const CodeInfo & code_info,const OatFile::OatMethod & oat_method)1352   void DumpCodeInfo(VariableIndentationOutputStream* vios,
1353                     const CodeInfo& code_info,
1354                     const OatFile::OatMethod& oat_method) {
1355     code_info.Dump(vios,
1356                    oat_method.GetCodeOffset(),
1357                    options_.dump_code_info_stack_maps_,
1358                    instruction_set_);
1359   }
1360 
GetOutVROffset(uint16_t out_num,InstructionSet isa)1361   static int GetOutVROffset(uint16_t out_num, InstructionSet isa) {
1362     // According to stack model, the first out is above the Method referernce.
1363     return static_cast<size_t>(InstructionSetPointerSize(isa)) + out_num * sizeof(uint32_t);
1364   }
1365 
GetVRegOffsetFromQuickCode(const CodeItemDataAccessor & code_item_accessor,uint32_t core_spills,uint32_t fp_spills,size_t frame_size,int reg,InstructionSet isa)1366   static uint32_t GetVRegOffsetFromQuickCode(const CodeItemDataAccessor& code_item_accessor,
1367                                              uint32_t core_spills,
1368                                              uint32_t fp_spills,
1369                                              size_t frame_size,
1370                                              int reg,
1371                                              InstructionSet isa) {
1372     PointerSize pointer_size = InstructionSetPointerSize(isa);
1373     if (kIsDebugBuild) {
1374       auto* runtime = Runtime::Current();
1375       if (runtime != nullptr) {
1376         CHECK_EQ(runtime->GetClassLinker()->GetImagePointerSize(), pointer_size);
1377       }
1378     }
1379     DCHECK_ALIGNED(frame_size, kStackAlignment);
1380     DCHECK_NE(reg, -1);
1381     int spill_size = POPCOUNT(core_spills) * GetBytesPerGprSpillLocation(isa)
1382         + POPCOUNT(fp_spills) * GetBytesPerFprSpillLocation(isa)
1383         + sizeof(uint32_t);  // Filler.
1384     int num_regs = code_item_accessor.RegistersSize() - code_item_accessor.InsSize();
1385     int temp_threshold = code_item_accessor.RegistersSize();
1386     const int max_num_special_temps = 1;
1387     if (reg == temp_threshold) {
1388       // The current method pointer corresponds to special location on stack.
1389       return 0;
1390     } else if (reg >= temp_threshold + max_num_special_temps) {
1391       /*
1392        * Special temporaries may have custom locations and the logic above deals with that.
1393        * However, non-special temporaries are placed relative to the outs.
1394        */
1395       int temps_start = code_item_accessor.OutsSize() * sizeof(uint32_t)
1396           + static_cast<size_t>(pointer_size) /* art method */;
1397       int relative_offset = (reg - (temp_threshold + max_num_special_temps)) * sizeof(uint32_t);
1398       return temps_start + relative_offset;
1399     } else if (reg < num_regs) {
1400       int locals_start = frame_size - spill_size - num_regs * sizeof(uint32_t);
1401       return locals_start + (reg * sizeof(uint32_t));
1402     } else {
1403       // Handle ins.
1404       return frame_size + ((reg - num_regs) * sizeof(uint32_t))
1405           + static_cast<size_t>(pointer_size) /* art method */;
1406     }
1407   }
1408 
DumpVregLocations(std::ostream & os,const OatFile::OatMethod & oat_method,const CodeItemDataAccessor & code_item_accessor)1409   void DumpVregLocations(std::ostream& os, const OatFile::OatMethod& oat_method,
1410                          const CodeItemDataAccessor& code_item_accessor) {
1411     if (code_item_accessor.HasCodeItem()) {
1412       size_t num_locals_ins = code_item_accessor.RegistersSize();
1413       size_t num_ins = code_item_accessor.InsSize();
1414       size_t num_locals = num_locals_ins - num_ins;
1415       size_t num_outs = code_item_accessor.OutsSize();
1416 
1417       os << "vr_stack_locations:";
1418       for (size_t reg = 0; reg <= num_locals_ins; reg++) {
1419         // For readability, delimit the different kinds of VRs.
1420         if (reg == num_locals_ins) {
1421           os << "\n\tmethod*:";
1422         } else if (reg == num_locals && num_ins > 0) {
1423           os << "\n\tins:";
1424         } else if (reg == 0 && num_locals > 0) {
1425           os << "\n\tlocals:";
1426         }
1427 
1428         uint32_t offset = GetVRegOffsetFromQuickCode(code_item_accessor,
1429                                                      oat_method.GetCoreSpillMask(),
1430                                                      oat_method.GetFpSpillMask(),
1431                                                      oat_method.GetFrameSizeInBytes(),
1432                                                      reg,
1433                                                      GetInstructionSet());
1434         os << " v" << reg << "[sp + #" << offset << "]";
1435       }
1436 
1437       for (size_t out_reg = 0; out_reg < num_outs; out_reg++) {
1438         if (out_reg == 0) {
1439           os << "\n\touts:";
1440         }
1441 
1442         uint32_t offset = GetOutVROffset(out_reg, GetInstructionSet());
1443         os << " v" << out_reg << "[sp + #" << offset << "]";
1444       }
1445 
1446       os << "\n";
1447     }
1448   }
1449 
1450   // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1451   // the optimizing compiler?
IsMethodGeneratedByOptimizingCompiler(const OatFile::OatMethod & oat_method,const CodeItemDataAccessor & code_item_accessor)1452   static bool IsMethodGeneratedByOptimizingCompiler(
1453       const OatFile::OatMethod& oat_method,
1454       const CodeItemDataAccessor& code_item_accessor) {
1455     // If the native GC map is null and the Dex `code_item` is not
1456     // null, then this method has been compiled with the optimizing
1457     // compiler.
1458     return oat_method.GetQuickCode() != nullptr &&
1459            oat_method.GetVmapTable() != nullptr &&
1460            code_item_accessor.HasCodeItem();
1461   }
1462 
1463   // Has `oat_method` -- corresponding to the Dex `code_item` -- been compiled by
1464   // the dextodex compiler?
IsMethodGeneratedByDexToDexCompiler(const OatFile::OatMethod & oat_method,const CodeItemDataAccessor & code_item_accessor)1465   static bool IsMethodGeneratedByDexToDexCompiler(
1466       const OatFile::OatMethod& oat_method,
1467       const CodeItemDataAccessor& code_item_accessor) {
1468     // If the quick code is null, the Dex `code_item` is not
1469     // null, and the vmap table is not null, then this method has been compiled
1470     // with the dextodex compiler.
1471     return oat_method.GetQuickCode() == nullptr &&
1472            oat_method.GetVmapTable() != nullptr &&
1473            code_item_accessor.HasCodeItem();
1474   }
1475 
DumpVerifier(VariableIndentationOutputStream * vios,StackHandleScope<1> * hs,uint32_t dex_method_idx,const DexFile * dex_file,const dex::ClassDef & class_def,const dex::CodeItem * code_item,uint32_t method_access_flags)1476   verifier::MethodVerifier* DumpVerifier(VariableIndentationOutputStream* vios,
1477                                          StackHandleScope<1>* hs,
1478                                          uint32_t dex_method_idx,
1479                                          const DexFile* dex_file,
1480                                          const dex::ClassDef& class_def,
1481                                          const dex::CodeItem* code_item,
1482                                          uint32_t method_access_flags) {
1483     if ((method_access_flags & kAccNative) == 0) {
1484       ScopedObjectAccess soa(Thread::Current());
1485       Runtime* const runtime = Runtime::Current();
1486       DCHECK(options_.class_loader_ != nullptr);
1487       Handle<mirror::DexCache> dex_cache = hs->NewHandle(
1488           runtime->GetClassLinker()->RegisterDexFile(*dex_file, options_.class_loader_->Get()));
1489       CHECK(dex_cache != nullptr);
1490       ArtMethod* method = runtime->GetClassLinker()->ResolveMethodWithoutInvokeType(
1491           dex_method_idx, dex_cache, *options_.class_loader_);
1492       if (method == nullptr) {
1493         soa.Self()->ClearException();
1494         return nullptr;
1495       }
1496       return verifier::MethodVerifier::VerifyMethodAndDump(
1497           soa.Self(), vios, dex_method_idx, dex_file, dex_cache, *options_.class_loader_,
1498           class_def, code_item, method, method_access_flags, /* api_level= */ 0);
1499     }
1500 
1501     return nullptr;
1502   }
1503 
DumpCode(VariableIndentationOutputStream * vios,const OatFile::OatMethod & oat_method,const CodeItemDataAccessor & code_item_accessor,bool bad_input,size_t code_size)1504   void DumpCode(VariableIndentationOutputStream* vios,
1505                 const OatFile::OatMethod& oat_method,
1506                 const CodeItemDataAccessor& code_item_accessor,
1507                 bool bad_input, size_t code_size) {
1508     const void* quick_code = oat_method.GetQuickCode();
1509 
1510     if (code_size == 0) {
1511       code_size = oat_method.GetQuickCodeSize();
1512     }
1513     if (code_size == 0 || quick_code == nullptr) {
1514       vios->Stream() << "NO CODE!\n";
1515       return;
1516     } else if (!bad_input && IsMethodGeneratedByOptimizingCompiler(oat_method,
1517                                                                    code_item_accessor)) {
1518       // The optimizing compiler outputs its CodeInfo data in the vmap table.
1519       CodeInfo code_info(oat_method.GetVmapTable());
1520       if (AddStatsObject(oat_method.GetVmapTable())) {
1521         code_info.CollectSizeStats(oat_method.GetVmapTable(), stats_["CodeInfo"]);
1522       }
1523       std::unordered_map<uint32_t, std::vector<StackMap>> stack_maps;
1524       for (const StackMap& it : code_info.GetStackMaps()) {
1525         stack_maps[it.GetNativePcOffset(instruction_set_)].push_back(it);
1526       }
1527 
1528       const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1529       size_t offset = 0;
1530       while (offset < code_size) {
1531         offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
1532         auto it = stack_maps.find(offset);
1533         if (it != stack_maps.end()) {
1534           ScopedIndentation indent1(vios);
1535           for (StackMap stack_map : it->second) {
1536             stack_map.Dump(vios, code_info, oat_method.GetCodeOffset(), instruction_set_);
1537           }
1538           stack_maps.erase(it);
1539         }
1540       }
1541       DCHECK_EQ(stack_maps.size(), 0u);  // Check that all stack maps have been printed.
1542     } else {
1543       const uint8_t* quick_native_pc = reinterpret_cast<const uint8_t*>(quick_code);
1544       size_t offset = 0;
1545       while (offset < code_size) {
1546         offset += disassembler_->Dump(vios->Stream(), quick_native_pc + offset);
1547       }
1548     }
1549   }
1550 
GetBootImageLiveObjectsDataRange(gc::Heap * heap) const1551   std::pair<const uint8_t*, const uint8_t*> GetBootImageLiveObjectsDataRange(gc::Heap* heap) const
1552       REQUIRES_SHARED(Locks::mutator_lock_) {
1553     const std::vector<gc::space::ImageSpace*>& boot_image_spaces = heap->GetBootImageSpaces();
1554     const ImageHeader& main_header = boot_image_spaces[0]->GetImageHeader();
1555     ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1556         ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1557             main_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kBootImageLiveObjects));
1558     DCHECK(boot_image_live_objects != nullptr);
1559     DCHECK(heap->ObjectIsInBootImageSpace(boot_image_live_objects));
1560     const uint8_t* boot_image_live_objects_address =
1561         reinterpret_cast<const uint8_t*>(boot_image_live_objects.Ptr());
1562     uint32_t begin_offset = mirror::ObjectArray<mirror::Object>::OffsetOfElement(0).Uint32Value();
1563     uint32_t end_offset = mirror::ObjectArray<mirror::Object>::OffsetOfElement(
1564         boot_image_live_objects->GetLength()).Uint32Value();
1565     return std::make_pair(boot_image_live_objects_address + begin_offset,
1566                           boot_image_live_objects_address + end_offset);
1567   }
1568 
DumpDataBimgRelRoEntries(std::ostream & os)1569   void DumpDataBimgRelRoEntries(std::ostream& os) {
1570     os << ".data.bimg.rel.ro: ";
1571     if (oat_file_.GetBootImageRelocations().empty()) {
1572       os << "empty.\n\n";
1573       return;
1574     }
1575 
1576     os << oat_file_.GetBootImageRelocations().size() << " entries.\n";
1577     Runtime* runtime = Runtime::Current();
1578     if (runtime != nullptr && !runtime->GetHeap()->GetBootImageSpaces().empty()) {
1579       const std::vector<gc::space::ImageSpace*>& boot_image_spaces =
1580           runtime->GetHeap()->GetBootImageSpaces();
1581       ScopedObjectAccess soa(Thread::Current());
1582       auto live_objects = GetBootImageLiveObjectsDataRange(runtime->GetHeap());
1583       const uint8_t* live_objects_begin = live_objects.first;
1584       const uint8_t* live_objects_end = live_objects.second;
1585       for (const uint32_t& object_offset : oat_file_.GetBootImageRelocations()) {
1586         uint32_t entry_index = &object_offset - oat_file_.GetBootImageRelocations().data();
1587         uint32_t entry_offset = entry_index * sizeof(oat_file_.GetBootImageRelocations()[0]);
1588         os << StringPrintf("  0x%x: 0x%08x", entry_offset, object_offset);
1589         uint8_t* address = boot_image_spaces[0]->Begin() + object_offset;
1590         bool found = false;
1591         for (gc::space::ImageSpace* space : boot_image_spaces) {
1592           uint64_t local_offset = address - space->Begin();
1593           if (local_offset < space->GetImageHeader().GetImageSize()) {
1594             if (space->GetImageHeader().GetObjectsSection().Contains(local_offset)) {
1595               if (address >= live_objects_begin && address < live_objects_end) {
1596                 size_t index =
1597                     (address - live_objects_begin) / sizeof(mirror::HeapReference<mirror::Object>);
1598                 os << StringPrintf("   0x%08x BootImageLiveObject[%zu]",
1599                                    object_offset,
1600                                    index);
1601               } else {
1602                 ObjPtr<mirror::Object> o = reinterpret_cast<mirror::Object*>(address);
1603                 if (o->IsString()) {
1604                   os << "   String: " << o->AsString()->ToModifiedUtf8();
1605                 } else if (o->IsClass()) {
1606                   os << "   Class: " << o->AsClass()->PrettyDescriptor();
1607                 } else {
1608                   os << StringPrintf("   0x%08x %s",
1609                                      object_offset,
1610                                      o->GetClass()->PrettyDescriptor().c_str());
1611                 }
1612               }
1613             } else if (space->GetImageHeader().GetMethodsSection().Contains(local_offset)) {
1614               ArtMethod* m = reinterpret_cast<ArtMethod*>(address);
1615               os << "   ArtMethod: " << m->PrettyMethod();
1616             } else {
1617               os << StringPrintf("   0x%08x <unexpected section in %s>",
1618                                  object_offset,
1619                                  space->GetImageFilename().c_str());
1620             }
1621             found = true;
1622             break;
1623           }
1624         }
1625         if (!found) {
1626           os << StringPrintf("   0x%08x <outside boot image spaces>", object_offset);
1627         }
1628         os << "\n";
1629       }
1630     } else {
1631       for (const uint32_t& object_offset : oat_file_.GetBootImageRelocations()) {
1632         uint32_t entry_index = &object_offset - oat_file_.GetBootImageRelocations().data();
1633         uint32_t entry_offset = entry_index * sizeof(oat_file_.GetBootImageRelocations()[0]);
1634         os << StringPrintf("  0x%x: 0x%08x\n", entry_offset, object_offset);
1635       }
1636     }
1637     os << "\n";
1638   }
1639 
1640   template <typename NameGetter>
DumpBssEntries(std::ostream & os,const char * slot_type,const IndexBssMapping * mapping,uint32_t number_of_indexes,size_t slot_size,NameGetter name)1641   void DumpBssEntries(std::ostream& os,
1642                       const char* slot_type,
1643                       const IndexBssMapping* mapping,
1644                       uint32_t number_of_indexes,
1645                       size_t slot_size,
1646                       NameGetter name) {
1647     os << ".bss mapping for " << slot_type << ": ";
1648     if (mapping == nullptr) {
1649       os << "empty.\n";
1650       return;
1651     }
1652     size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
1653     size_t num_valid_indexes = 0u;
1654     for (const IndexBssMappingEntry& entry : *mapping) {
1655       num_valid_indexes += 1u + POPCOUNT(entry.GetMask(index_bits));
1656     }
1657     os << mapping->size() << " entries for " << num_valid_indexes << " valid indexes.\n";
1658     os << std::hex;
1659     for (const IndexBssMappingEntry& entry : *mapping) {
1660       uint32_t index = entry.GetIndex(index_bits);
1661       uint32_t mask = entry.GetMask(index_bits);
1662       size_t bss_offset = entry.bss_offset - POPCOUNT(mask) * slot_size;
1663       for (uint32_t n : LowToHighBits(mask)) {
1664         size_t current_index = index - (32u - index_bits) + n;
1665         os << "  0x" << bss_offset << ": " << slot_type << ": " << name(current_index) << "\n";
1666         bss_offset += slot_size;
1667       }
1668       DCHECK_EQ(bss_offset, entry.bss_offset);
1669       os << "  0x" << bss_offset << ": " << slot_type << ": " << name(index) << "\n";
1670     }
1671     os << std::dec;
1672   }
1673 
1674   const OatFile& oat_file_;
1675   const std::vector<const OatDexFile*> oat_dex_files_;
1676   const OatDumperOptions& options_;
1677   uint32_t resolved_addr2instr_;
1678   const InstructionSet instruction_set_;
1679   std::set<uintptr_t> offsets_;
1680   Disassembler* disassembler_;
1681   Stats stats_;
1682   std::unordered_set<const void*> seen_stats_objects_;
1683 };
1684 
1685 class ImageDumper {
1686  public:
ImageDumper(std::ostream * os,gc::space::ImageSpace & image_space,const ImageHeader & image_header,OatDumperOptions * oat_dumper_options)1687   ImageDumper(std::ostream* os,
1688               gc::space::ImageSpace& image_space,
1689               const ImageHeader& image_header,
1690               OatDumperOptions* oat_dumper_options)
1691       : os_(os),
1692         vios_(os),
1693         indent1_(&vios_),
1694         image_space_(image_space),
1695         image_header_(image_header),
1696         oat_dumper_options_(oat_dumper_options) {}
1697 
Dump()1698   bool Dump() REQUIRES_SHARED(Locks::mutator_lock_) {
1699     std::ostream& os = *os_;
1700     std::ostream& indent_os = vios_.Stream();
1701 
1702     os << "MAGIC: " << image_header_.GetMagic() << "\n\n";
1703 
1704     os << "IMAGE LOCATION: " << image_space_.GetImageLocation() << "\n\n";
1705 
1706     os << "IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetImageBegin()) << "\n";
1707     os << "IMAGE SIZE: " << image_header_.GetImageSize() << "\n";
1708     os << "IMAGE CHECKSUM: " << std::hex << image_header_.GetImageChecksum() << std::dec << "\n\n";
1709 
1710     os << "OAT CHECKSUM: " << StringPrintf("0x%08x\n\n", image_header_.GetOatChecksum()) << "\n";
1711     os << "OAT FILE BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatFileBegin()) << "\n";
1712     os << "OAT DATA BEGIN:" << reinterpret_cast<void*>(image_header_.GetOatDataBegin()) << "\n";
1713     os << "OAT DATA END:" << reinterpret_cast<void*>(image_header_.GetOatDataEnd()) << "\n";
1714     os << "OAT FILE END:" << reinterpret_cast<void*>(image_header_.GetOatFileEnd()) << "\n\n";
1715 
1716     os << "BOOT IMAGE BEGIN: " << reinterpret_cast<void*>(image_header_.GetBootImageBegin())
1717         << "\n";
1718     os << "BOOT IMAGE SIZE: " << image_header_.GetBootImageSize() << "\n\n";
1719 
1720     for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1721       auto section = static_cast<ImageHeader::ImageSections>(i);
1722       os << "IMAGE SECTION " << section << ": " << image_header_.GetImageSection(section) << "\n\n";
1723     }
1724 
1725     {
1726       os << "ROOTS: " << reinterpret_cast<void*>(image_header_.GetImageRoots().Ptr()) << "\n";
1727       static_assert(arraysize(image_roots_descriptions_) ==
1728           static_cast<size_t>(ImageHeader::kImageRootsMax), "sizes must match");
1729       DCHECK_LE(image_header_.GetImageRoots()->GetLength(), ImageHeader::kImageRootsMax);
1730       for (int32_t i = 0, size = image_header_.GetImageRoots()->GetLength(); i != size; ++i) {
1731         ImageHeader::ImageRoot image_root = static_cast<ImageHeader::ImageRoot>(i);
1732         const char* image_root_description = image_roots_descriptions_[i];
1733         ObjPtr<mirror::Object> image_root_object = image_header_.GetImageRoot(image_root);
1734         indent_os << StringPrintf("%s: %p\n", image_root_description, image_root_object.Ptr());
1735         if (image_root_object != nullptr && image_root_object->IsObjectArray()) {
1736           ObjPtr<mirror::ObjectArray<mirror::Object>> image_root_object_array
1737               = image_root_object->AsObjectArray<mirror::Object>();
1738           ScopedIndentation indent2(&vios_);
1739           for (int j = 0; j < image_root_object_array->GetLength(); j++) {
1740             ObjPtr<mirror::Object> value = image_root_object_array->Get(j);
1741             size_t run = 0;
1742             for (int32_t k = j + 1; k < image_root_object_array->GetLength(); k++) {
1743               if (value == image_root_object_array->Get(k)) {
1744                 run++;
1745               } else {
1746                 break;
1747               }
1748             }
1749             if (run == 0) {
1750               indent_os << StringPrintf("%d: ", j);
1751             } else {
1752               indent_os << StringPrintf("%d to %zd: ", j, j + run);
1753               j = j + run;
1754             }
1755             if (value != nullptr) {
1756               PrettyObjectValue(indent_os, value->GetClass(), value);
1757             } else {
1758               indent_os << j << ": null\n";
1759             }
1760           }
1761         }
1762       }
1763     }
1764 
1765     {
1766       os << "METHOD ROOTS\n";
1767       static_assert(arraysize(image_methods_descriptions_) ==
1768           static_cast<size_t>(ImageHeader::kImageMethodsCount), "sizes must match");
1769       for (int i = 0; i < ImageHeader::kImageMethodsCount; i++) {
1770         auto image_root = static_cast<ImageHeader::ImageMethod>(i);
1771         const char* description = image_methods_descriptions_[i];
1772         auto* image_method = image_header_.GetImageMethod(image_root);
1773         indent_os << StringPrintf("%s: %p\n", description, image_method);
1774       }
1775     }
1776     os << "\n";
1777 
1778     Runtime* const runtime = Runtime::Current();
1779     std::string image_filename = image_space_.GetImageFilename();
1780     std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_filename);
1781     os << "OAT LOCATION: " << oat_location;
1782     os << "\n";
1783     std::string error_msg;
1784     const OatFile* oat_file = image_space_.GetOatFile();
1785     if (oat_file == nullptr) {
1786       oat_file = runtime->GetOatFileManager().FindOpenedOatFileFromOatLocation(oat_location);
1787     }
1788     if (oat_file == nullptr) {
1789       oat_file = OatFile::Open(/*zip_fd=*/ -1,
1790                                oat_location,
1791                                oat_location,
1792                                /*executable=*/ false,
1793                                /*low_4gb=*/ false,
1794                                &error_msg);
1795     }
1796     if (oat_file == nullptr) {
1797       os << "OAT FILE NOT FOUND: " << error_msg << "\n";
1798       return EXIT_FAILURE;
1799     }
1800     os << "\n";
1801 
1802     stats_.oat_file_bytes = oat_file->Size();
1803     stats_.oat_file_stats.AddBytes(oat_file->Size());
1804 
1805     oat_dumper_.reset(new OatDumper(*oat_file, *oat_dumper_options_));
1806 
1807     for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1808       CHECK(oat_dex_file != nullptr);
1809       stats_.oat_dex_file_sizes.push_back(std::make_pair(oat_dex_file->GetDexFileLocation(),
1810                                                          oat_dex_file->FileSize()));
1811     }
1812 
1813     os << "OBJECTS:\n" << std::flush;
1814 
1815     // Loop through the image space and dump its objects.
1816     gc::Heap* heap = runtime->GetHeap();
1817     Thread* self = Thread::Current();
1818     {
1819       {
1820         WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1821         heap->FlushAllocStack();
1822       }
1823       // Since FlushAllocStack() above resets the (active) allocation
1824       // stack. Need to revoke the thread-local allocation stacks that
1825       // point into it.
1826       ScopedThreadSuspension sts(self, kNative);
1827       ScopedSuspendAll ssa(__FUNCTION__);
1828       heap->RevokeAllThreadLocalAllocationStacks(self);
1829     }
1830     {
1831       auto dump_visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1832         DumpObject(obj);
1833       };
1834       ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1835       // Dump the normal objects before ArtMethods.
1836       image_space_.GetLiveBitmap()->Walk(dump_visitor);
1837       indent_os << "\n";
1838       // TODO: Dump fields.
1839       // Dump methods after.
1840       image_header_.VisitPackedArtMethods([&](ArtMethod& method)
1841           REQUIRES_SHARED(Locks::mutator_lock_) {
1842         std::ostream& indent_os = vios_.Stream();
1843         indent_os << &method << " " << " ArtMethod: " << method.PrettyMethod() << "\n";
1844         DumpMethod(&method, indent_os);
1845         indent_os << "\n";
1846       },  image_space_.Begin(), image_header_.GetPointerSize());
1847       // Dump the large objects separately.
1848       heap->GetLargeObjectsSpace()->GetLiveBitmap()->Walk(dump_visitor);
1849       indent_os << "\n";
1850     }
1851     os << "STATS:\n" << std::flush;
1852     std::unique_ptr<File> file(OS::OpenFileForReading(image_filename.c_str()));
1853     size_t data_size = image_header_.GetDataSize();  // stored size in file.
1854     if (file == nullptr) {
1855       LOG(WARNING) << "Failed to find image in " << image_filename;
1856     } else {
1857       size_t file_bytes = file->GetLength();
1858       // If the image is compressed, adjust to decompressed size.
1859       size_t uncompressed_size = image_header_.GetImageSize() - sizeof(ImageHeader);
1860       if (!image_header_.HasCompressedBlock()) {
1861         DCHECK_EQ(uncompressed_size, data_size) << "Sizes should match for uncompressed image";
1862       }
1863       file_bytes += uncompressed_size - data_size;
1864       stats_.art_file_stats.AddBytes(file_bytes);
1865       stats_.art_file_stats["Header"].AddBytes(sizeof(ImageHeader));
1866     }
1867 
1868     size_t pointer_size = static_cast<size_t>(image_header_.GetPointerSize());
1869     CHECK_ALIGNED(image_header_.GetFieldsSection().Offset(), 4);
1870     CHECK_ALIGNED_PARAM(image_header_.GetMethodsSection().Offset(), pointer_size);
1871     CHECK_ALIGNED(image_header_.GetInternedStringsSection().Offset(), 8);
1872     CHECK_ALIGNED(image_header_.GetImageBitmapSection().Offset(), kPageSize);
1873 
1874     for (size_t i = 0; i < ImageHeader::ImageSections::kSectionCount; i++) {
1875       ImageHeader::ImageSections index = ImageHeader::ImageSections(i);
1876       const char* name = ImageHeader::GetImageSectionName(index);
1877       stats_.art_file_stats[name].AddBytes(image_header_.GetImageSection(index).Size());
1878     }
1879 
1880     stats_.object_stats.AddBytes(image_header_.GetObjectsSection().Size());
1881     stats_.Dump(os);
1882     os << "\n";
1883 
1884     os << std::flush;
1885 
1886     return oat_dumper_->Dump(os);
1887   }
1888 
1889  private:
PrettyObjectValue(std::ostream & os,ObjPtr<mirror::Class> type,ObjPtr<mirror::Object> value)1890   static void PrettyObjectValue(std::ostream& os,
1891                                 ObjPtr<mirror::Class> type,
1892                                 ObjPtr<mirror::Object> value)
1893       REQUIRES_SHARED(Locks::mutator_lock_) {
1894     CHECK(type != nullptr);
1895     if (value == nullptr) {
1896       os << StringPrintf("null   %s\n", type->PrettyDescriptor().c_str());
1897     } else if (type->IsStringClass()) {
1898       ObjPtr<mirror::String> string = value->AsString();
1899       os << StringPrintf("%p   String: %s\n",
1900                          string.Ptr(),
1901                          PrintableString(string->ToModifiedUtf8().c_str()).c_str());
1902     } else if (type->IsClassClass()) {
1903       ObjPtr<mirror::Class> klass = value->AsClass();
1904       os << StringPrintf("%p   Class: %s\n",
1905                          klass.Ptr(),
1906                          mirror::Class::PrettyDescriptor(klass).c_str());
1907     } else {
1908       os << StringPrintf("%p   %s\n", value.Ptr(), type->PrettyDescriptor().c_str());
1909     }
1910   }
1911 
PrintField(std::ostream & os,ArtField * field,ObjPtr<mirror::Object> obj)1912   static void PrintField(std::ostream& os, ArtField* field, ObjPtr<mirror::Object> obj)
1913       REQUIRES_SHARED(Locks::mutator_lock_) {
1914     os << StringPrintf("%s: ", field->GetName());
1915     switch (field->GetTypeAsPrimitiveType()) {
1916       case Primitive::kPrimLong:
1917         os << StringPrintf("%" PRId64 " (0x%" PRIx64 ")\n", field->Get64(obj), field->Get64(obj));
1918         break;
1919       case Primitive::kPrimDouble:
1920         os << StringPrintf("%f (%a)\n", field->GetDouble(obj), field->GetDouble(obj));
1921         break;
1922       case Primitive::kPrimFloat:
1923         os << StringPrintf("%f (%a)\n", field->GetFloat(obj), field->GetFloat(obj));
1924         break;
1925       case Primitive::kPrimInt:
1926         os << StringPrintf("%d (0x%x)\n", field->Get32(obj), field->Get32(obj));
1927         break;
1928       case Primitive::kPrimChar:
1929         os << StringPrintf("%u (0x%x)\n", field->GetChar(obj), field->GetChar(obj));
1930         break;
1931       case Primitive::kPrimShort:
1932         os << StringPrintf("%d (0x%x)\n", field->GetShort(obj), field->GetShort(obj));
1933         break;
1934       case Primitive::kPrimBoolean:
1935         os << StringPrintf("%s (0x%x)\n", field->GetBoolean(obj) ? "true" : "false",
1936             field->GetBoolean(obj));
1937         break;
1938       case Primitive::kPrimByte:
1939         os << StringPrintf("%d (0x%x)\n", field->GetByte(obj), field->GetByte(obj));
1940         break;
1941       case Primitive::kPrimNot: {
1942         // Get the value, don't compute the type unless it is non-null as we don't want
1943         // to cause class loading.
1944         ObjPtr<mirror::Object> value = field->GetObj(obj);
1945         if (value == nullptr) {
1946           os << StringPrintf("null   %s\n", PrettyDescriptor(field->GetTypeDescriptor()).c_str());
1947         } else {
1948           // Grab the field type without causing resolution.
1949           ObjPtr<mirror::Class> field_type = field->LookupResolvedType();
1950           if (field_type != nullptr) {
1951             PrettyObjectValue(os, field_type, value);
1952           } else {
1953             os << StringPrintf("%p   %s\n",
1954                                value.Ptr(),
1955                                PrettyDescriptor(field->GetTypeDescriptor()).c_str());
1956           }
1957         }
1958         break;
1959       }
1960       default:
1961         os << "unexpected field type: " << field->GetTypeDescriptor() << "\n";
1962         break;
1963     }
1964   }
1965 
DumpFields(std::ostream & os,mirror::Object * obj,ObjPtr<mirror::Class> klass)1966   static void DumpFields(std::ostream& os, mirror::Object* obj, ObjPtr<mirror::Class> klass)
1967       REQUIRES_SHARED(Locks::mutator_lock_) {
1968     ObjPtr<mirror::Class> super = klass->GetSuperClass();
1969     if (super != nullptr) {
1970       DumpFields(os, obj, super);
1971     }
1972     for (ArtField& field : klass->GetIFields()) {
1973       PrintField(os, &field, obj);
1974     }
1975   }
1976 
InDumpSpace(const mirror::Object * object)1977   bool InDumpSpace(const mirror::Object* object) {
1978     return image_space_.Contains(object);
1979   }
1980 
GetQuickOatCodeBegin(ArtMethod * m)1981   const void* GetQuickOatCodeBegin(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
1982     const void* quick_code = m->GetEntryPointFromQuickCompiledCodePtrSize(
1983         image_header_.GetPointerSize());
1984     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1985     if (class_linker->IsQuickResolutionStub(quick_code) ||
1986         class_linker->IsQuickToInterpreterBridge(quick_code) ||
1987         class_linker->IsNterpTrampoline(quick_code) ||
1988         class_linker->IsQuickGenericJniStub(quick_code) ||
1989         class_linker->IsJniDlsymLookupStub(quick_code) ||
1990         class_linker->IsJniDlsymLookupCriticalStub(quick_code)) {
1991       quick_code = oat_dumper_->GetQuickOatCode(m);
1992     }
1993     if (oat_dumper_->GetInstructionSet() == InstructionSet::kThumb2) {
1994       quick_code = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(quick_code) & ~0x1);
1995     }
1996     return quick_code;
1997   }
1998 
GetQuickOatCodeSize(ArtMethod * m)1999   uint32_t GetQuickOatCodeSize(ArtMethod* m)
2000       REQUIRES_SHARED(Locks::mutator_lock_) {
2001     const uint32_t* oat_code_begin = reinterpret_cast<const uint32_t*>(GetQuickOatCodeBegin(m));
2002     if (oat_code_begin == nullptr) {
2003       return 0;
2004     }
2005     OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2006         reinterpret_cast<uintptr_t>(oat_code_begin) - sizeof(OatQuickMethodHeader));
2007     return method_header->GetCodeSize();
2008   }
2009 
GetQuickOatCodeEnd(ArtMethod * m)2010   const void* GetQuickOatCodeEnd(ArtMethod* m)
2011       REQUIRES_SHARED(Locks::mutator_lock_) {
2012     const uint8_t* oat_code_begin = reinterpret_cast<const uint8_t*>(GetQuickOatCodeBegin(m));
2013     if (oat_code_begin == nullptr) {
2014       return nullptr;
2015     }
2016     return oat_code_begin + GetQuickOatCodeSize(m);
2017   }
2018 
DumpObject(mirror::Object * obj)2019   void DumpObject(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2020     DCHECK(obj != nullptr);
2021     if (!InDumpSpace(obj)) {
2022       return;
2023     }
2024 
2025     std::ostream& os = vios_.Stream();
2026 
2027     ObjPtr<mirror::Class> obj_class = obj->GetClass();
2028     if (obj_class->IsArrayClass()) {
2029       os << StringPrintf("%p: %s length:%d\n", obj, obj_class->PrettyDescriptor().c_str(),
2030                          obj->AsArray()->GetLength());
2031     } else if (obj->IsClass()) {
2032       ObjPtr<mirror::Class> klass = obj->AsClass();
2033       os << StringPrintf("%p: java.lang.Class \"%s\" (",
2034                          obj,
2035                          mirror::Class::PrettyDescriptor(klass).c_str())
2036          << klass->GetStatus() << ")\n";
2037     } else if (obj_class->IsStringClass()) {
2038       os << StringPrintf("%p: java.lang.String %s\n",
2039                          obj,
2040                          PrintableString(obj->AsString()->ToModifiedUtf8().c_str()).c_str());
2041     } else {
2042       os << StringPrintf("%p: %s\n", obj, obj_class->PrettyDescriptor().c_str());
2043     }
2044     ScopedIndentation indent1(&vios_);
2045     DumpFields(os, obj, obj_class);
2046     if (obj->IsObjectArray()) {
2047       ObjPtr<mirror::ObjectArray<mirror::Object>> obj_array = obj->AsObjectArray<mirror::Object>();
2048       for (int32_t i = 0, length = obj_array->GetLength(); i < length; i++) {
2049         ObjPtr<mirror::Object> value = obj_array->Get(i);
2050         size_t run = 0;
2051         for (int32_t j = i + 1; j < length; j++) {
2052           if (value == obj_array->Get(j)) {
2053             run++;
2054           } else {
2055             break;
2056           }
2057         }
2058         if (run == 0) {
2059           os << StringPrintf("%d: ", i);
2060         } else {
2061           os << StringPrintf("%d to %zd: ", i, i + run);
2062           i = i + run;
2063         }
2064         ObjPtr<mirror::Class> value_class =
2065             (value == nullptr) ? obj_class->GetComponentType() : value->GetClass();
2066         PrettyObjectValue(os, value_class, value);
2067       }
2068     } else if (obj->IsClass()) {
2069       ObjPtr<mirror::Class> klass = obj->AsClass();
2070 
2071       if (kBitstringSubtypeCheckEnabled) {
2072         os << "SUBTYPE_CHECK_BITS: ";
2073         SubtypeCheck<ObjPtr<mirror::Class>>::Dump(klass, os);
2074         os << "\n";
2075       }
2076 
2077       if (klass->NumStaticFields() != 0) {
2078         os << "STATICS:\n";
2079         ScopedIndentation indent2(&vios_);
2080         for (ArtField& field : klass->GetSFields()) {
2081           PrintField(os, &field, field.GetDeclaringClass());
2082         }
2083       }
2084     }
2085     std::string temp;
2086     const char* desc = obj_class->GetDescriptor(&temp);
2087     desc = stats_.descriptors.emplace(desc).first->c_str();  // Dedup and keep alive.
2088     stats_.object_stats[desc].AddBytes(obj->SizeOf());
2089   }
2090 
DumpMethod(ArtMethod * method,std::ostream & indent_os)2091   void DumpMethod(ArtMethod* method, std::ostream& indent_os)
2092       REQUIRES_SHARED(Locks::mutator_lock_) {
2093     DCHECK(method != nullptr);
2094     const PointerSize pointer_size = image_header_.GetPointerSize();
2095     if (method->IsNative()) {
2096       const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
2097       bool first_occurrence;
2098       uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2099       ComputeOatSize(quick_oat_code_begin, &first_occurrence);
2100       if (first_occurrence) {
2101         stats_.oat_file_stats["native_code"].AddBytes(quick_oat_code_size);
2102       }
2103       if (quick_oat_code_begin != method->GetEntryPointFromQuickCompiledCodePtrSize(
2104           image_header_.GetPointerSize())) {
2105         indent_os << StringPrintf("OAT CODE: %p\n", quick_oat_code_begin);
2106       }
2107     } else if (method->IsAbstract() || method->IsClassInitializer()) {
2108       // Don't print information for these.
2109     } else if (method->IsRuntimeMethod()) {
2110       if (method == Runtime::Current()->GetResolutionMethod()) {
2111         const void* resolution_trampoline =
2112             method->GetEntryPointFromQuickCompiledCodePtrSize(image_header_.GetPointerSize());
2113         indent_os << StringPrintf("Resolution trampoline: %p\n", resolution_trampoline);
2114         const void* critical_native_resolution_trampoline =
2115             method->GetEntryPointFromJniPtrSize(image_header_.GetPointerSize());
2116         indent_os << StringPrintf("Resolution trampoline for @CriticalNative: %p\n",
2117                                   critical_native_resolution_trampoline);
2118       } else {
2119         ImtConflictTable* table = method->GetImtConflictTable(image_header_.GetPointerSize());
2120         if (table != nullptr) {
2121           indent_os << "IMT conflict table " << table << " method: ";
2122           for (size_t i = 0, count = table->NumEntries(pointer_size); i < count; ++i) {
2123             indent_os << ArtMethod::PrettyMethod(table->GetImplementationMethod(i, pointer_size))
2124                       << " ";
2125           }
2126         }
2127       }
2128     } else {
2129       CodeItemDataAccessor code_item_accessor(method->DexInstructionData());
2130       size_t dex_instruction_bytes = code_item_accessor.InsnsSizeInCodeUnits() * 2;
2131       stats_.dex_instruction_bytes += dex_instruction_bytes;
2132 
2133       const void* quick_oat_code_begin = GetQuickOatCodeBegin(method);
2134       const void* quick_oat_code_end = GetQuickOatCodeEnd(method);
2135 
2136       bool first_occurrence;
2137       size_t vmap_table_bytes = 0u;
2138       if (quick_oat_code_begin != nullptr) {
2139         OatQuickMethodHeader* method_header = reinterpret_cast<OatQuickMethodHeader*>(
2140             reinterpret_cast<uintptr_t>(quick_oat_code_begin) - sizeof(OatQuickMethodHeader));
2141         vmap_table_bytes = ComputeOatSize(method_header->GetOptimizedCodeInfoPtr(),
2142                                           &first_occurrence);
2143         if (first_occurrence) {
2144           stats_.vmap_table_bytes += vmap_table_bytes;
2145         }
2146       }
2147 
2148       uint32_t quick_oat_code_size = GetQuickOatCodeSize(method);
2149       ComputeOatSize(quick_oat_code_begin, &first_occurrence);
2150       if (first_occurrence) {
2151         stats_.managed_code_bytes += quick_oat_code_size;
2152         art::Stats& managed_code_stats = stats_.oat_file_stats["managed_code"];
2153         managed_code_stats.AddBytes(quick_oat_code_size);
2154         if (method->IsConstructor()) {
2155           if (method->IsStatic()) {
2156             managed_code_stats["class_initializer"].AddBytes(quick_oat_code_size);
2157           } else if (dex_instruction_bytes > kLargeConstructorDexBytes) {
2158             managed_code_stats["large_initializer"].AddBytes(quick_oat_code_size);
2159           }
2160         } else if (dex_instruction_bytes > kLargeMethodDexBytes) {
2161           managed_code_stats["large_method"].AddBytes(quick_oat_code_size);
2162         }
2163       }
2164       stats_.managed_code_bytes_ignoring_deduplication += quick_oat_code_size;
2165 
2166       uint32_t method_access_flags = method->GetAccessFlags();
2167 
2168       indent_os << StringPrintf("OAT CODE: %p-%p\n", quick_oat_code_begin, quick_oat_code_end);
2169       indent_os << StringPrintf("SIZE: Dex Instructions=%zd StackMaps=%zd AccessFlags=0x%x\n",
2170                                 dex_instruction_bytes,
2171                                 vmap_table_bytes,
2172                                 method_access_flags);
2173 
2174       size_t total_size = dex_instruction_bytes +
2175           vmap_table_bytes + quick_oat_code_size + ArtMethod::Size(image_header_.GetPointerSize());
2176 
2177       double expansion =
2178       static_cast<double>(quick_oat_code_size) / static_cast<double>(dex_instruction_bytes);
2179       stats_.ComputeOutliers(total_size, expansion, method);
2180     }
2181   }
2182 
2183   std::set<const void*> already_seen_;
2184   // Compute the size of the given data within the oat file and whether this is the first time
2185   // this data has been requested
ComputeOatSize(const void * oat_data,bool * first_occurrence)2186   size_t ComputeOatSize(const void* oat_data, bool* first_occurrence) {
2187     if (already_seen_.count(oat_data) == 0) {
2188       *first_occurrence = true;
2189       already_seen_.insert(oat_data);
2190     } else {
2191       *first_occurrence = false;
2192     }
2193     return oat_dumper_->ComputeSize(oat_data);
2194   }
2195 
2196  public:
2197   struct Stats {
2198     art::Stats art_file_stats;
2199     art::Stats oat_file_stats;
2200     art::Stats object_stats;
2201     std::set<std::string> descriptors;
2202 
2203     size_t oat_file_bytes = 0u;
2204     size_t managed_code_bytes = 0u;
2205     size_t managed_code_bytes_ignoring_deduplication = 0u;
2206 
2207     size_t vmap_table_bytes = 0u;
2208 
2209     size_t dex_instruction_bytes = 0u;
2210 
2211     std::vector<ArtMethod*> method_outlier;
2212     std::vector<size_t> method_outlier_size;
2213     std::vector<double> method_outlier_expansion;
2214     std::vector<std::pair<std::string, size_t>> oat_dex_file_sizes;
2215 
Statsart::ImageDumper::Stats2216     Stats() {}
2217 
PercentOfOatBytesart::ImageDumper::Stats2218     double PercentOfOatBytes(size_t size) {
2219       return (static_cast<double>(size) / static_cast<double>(oat_file_bytes)) * 100;
2220     }
2221 
ComputeOutliersart::ImageDumper::Stats2222     void ComputeOutliers(size_t total_size, double expansion, ArtMethod* method) {
2223       method_outlier_size.push_back(total_size);
2224       method_outlier_expansion.push_back(expansion);
2225       method_outlier.push_back(method);
2226     }
2227 
DumpOutliersart::ImageDumper::Stats2228     void DumpOutliers(std::ostream& os)
2229         REQUIRES_SHARED(Locks::mutator_lock_) {
2230       size_t sum_of_sizes = 0;
2231       size_t sum_of_sizes_squared = 0;
2232       size_t sum_of_expansion = 0;
2233       size_t sum_of_expansion_squared = 0;
2234       size_t n = method_outlier_size.size();
2235       if (n <= 1) {
2236         return;
2237       }
2238       for (size_t i = 0; i < n; i++) {
2239         size_t cur_size = method_outlier_size[i];
2240         sum_of_sizes += cur_size;
2241         sum_of_sizes_squared += cur_size * cur_size;
2242         double cur_expansion = method_outlier_expansion[i];
2243         sum_of_expansion += cur_expansion;
2244         sum_of_expansion_squared += cur_expansion * cur_expansion;
2245       }
2246       size_t size_mean = sum_of_sizes / n;
2247       size_t size_variance = (sum_of_sizes_squared - sum_of_sizes * size_mean) / (n - 1);
2248       double expansion_mean = sum_of_expansion / n;
2249       double expansion_variance =
2250           (sum_of_expansion_squared - sum_of_expansion * expansion_mean) / (n - 1);
2251 
2252       // Dump methods whose size is a certain number of standard deviations from the mean
2253       size_t dumped_values = 0;
2254       size_t skipped_values = 0;
2255       for (size_t i = 100; i > 0; i--) {  // i is the current number of standard deviations
2256         size_t cur_size_variance = i * i * size_variance;
2257         bool first = true;
2258         for (size_t j = 0; j < n; j++) {
2259           size_t cur_size = method_outlier_size[j];
2260           if (cur_size > size_mean) {
2261             size_t cur_var = cur_size - size_mean;
2262             cur_var = cur_var * cur_var;
2263             if (cur_var > cur_size_variance) {
2264               if (dumped_values > 20) {
2265                 if (i == 1) {
2266                   skipped_values++;
2267                 } else {
2268                   i = 2;  // jump to counting for 1 standard deviation
2269                   break;
2270                 }
2271               } else {
2272                 if (first) {
2273                   os << "\nBig methods (size > " << i << " standard deviations the norm):\n";
2274                   first = false;
2275                 }
2276                 os << ArtMethod::PrettyMethod(method_outlier[j]) << " requires storage of "
2277                     << PrettySize(cur_size) << "\n";
2278                 method_outlier_size[j] = 0;  // don't consider this method again
2279                 dumped_values++;
2280               }
2281             }
2282           }
2283         }
2284       }
2285       if (skipped_values > 0) {
2286         os << "... skipped " << skipped_values
2287            << " methods with size > 1 standard deviation from the norm\n";
2288       }
2289       os << std::flush;
2290 
2291       // Dump methods whose expansion is a certain number of standard deviations from the mean
2292       dumped_values = 0;
2293       skipped_values = 0;
2294       for (size_t i = 10; i > 0; i--) {  // i is the current number of standard deviations
2295         double cur_expansion_variance = i * i * expansion_variance;
2296         bool first = true;
2297         for (size_t j = 0; j < n; j++) {
2298           double cur_expansion = method_outlier_expansion[j];
2299           if (cur_expansion > expansion_mean) {
2300             size_t cur_var = cur_expansion - expansion_mean;
2301             cur_var = cur_var * cur_var;
2302             if (cur_var > cur_expansion_variance) {
2303               if (dumped_values > 20) {
2304                 if (i == 1) {
2305                   skipped_values++;
2306                 } else {
2307                   i = 2;  // jump to counting for 1 standard deviation
2308                   break;
2309                 }
2310               } else {
2311                 if (first) {
2312                   os << "\nLarge expansion methods (size > " << i
2313                       << " standard deviations the norm):\n";
2314                   first = false;
2315                 }
2316                 os << ArtMethod::PrettyMethod(method_outlier[j]) << " expanded code by "
2317                    << cur_expansion << "\n";
2318                 method_outlier_expansion[j] = 0.0;  // don't consider this method again
2319                 dumped_values++;
2320               }
2321             }
2322           }
2323         }
2324       }
2325       if (skipped_values > 0) {
2326         os << "... skipped " << skipped_values
2327            << " methods with expansion > 1 standard deviation from the norm\n";
2328       }
2329       os << "\n" << std::flush;
2330     }
2331 
Dumpart::ImageDumper::Stats2332     void Dump(std::ostream& os)
2333         REQUIRES_SHARED(Locks::mutator_lock_) {
2334       VariableIndentationOutputStream vios(&os);
2335       art_file_stats.DumpSizes(vios, "ArtFile");
2336       os << "\n" << std::flush;
2337       object_stats.DumpSizes(vios, "Objects");
2338       os << "\n" << std::flush;
2339       oat_file_stats.DumpSizes(vios, "OatFile");
2340       os << "\n" << std::flush;
2341 
2342       for (const std::pair<std::string, size_t>& oat_dex_file_size : oat_dex_file_sizes) {
2343         os << StringPrintf("%s = %zd (%2.0f%% of oat file bytes)\n",
2344                            oat_dex_file_size.first.c_str(), oat_dex_file_size.second,
2345                            PercentOfOatBytes(oat_dex_file_size.second));
2346       }
2347 
2348       os << "\n" << StringPrintf("vmap_table_bytes       = %7zd (%2.0f%% of oat file bytes)\n\n",
2349                                  vmap_table_bytes, PercentOfOatBytes(vmap_table_bytes))
2350          << std::flush;
2351 
2352       os << StringPrintf("dex_instruction_bytes = %zd\n", dex_instruction_bytes)
2353          << StringPrintf("managed_code_bytes expansion = %.2f (ignoring deduplication %.2f)\n\n",
2354                          static_cast<double>(managed_code_bytes) /
2355                              static_cast<double>(dex_instruction_bytes),
2356                          static_cast<double>(managed_code_bytes_ignoring_deduplication) /
2357                              static_cast<double>(dex_instruction_bytes))
2358          << std::flush;
2359 
2360       DumpOutliers(os);
2361     }
2362   } stats_;
2363 
2364  private:
2365   enum {
2366     // Number of bytes for a constructor to be considered large. Based on the 1000 basic block
2367     // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2368     kLargeConstructorDexBytes = 4000,
2369     // Number of bytes for a method to be considered large. Based on the 4000 basic block
2370     // threshold, we assume 2 bytes per instruction and 2 instructions per block.
2371     kLargeMethodDexBytes = 16000
2372   };
2373 
2374   // For performance, use the *os_ directly for anything that doesn't need indentation
2375   // and prepare an indentation stream with default indentation 1.
2376   std::ostream* os_;
2377   VariableIndentationOutputStream vios_;
2378   ScopedIndentation indent1_;
2379 
2380   gc::space::ImageSpace& image_space_;
2381   const ImageHeader& image_header_;
2382   std::unique_ptr<OatDumper> oat_dumper_;
2383   OatDumperOptions* oat_dumper_options_;
2384 
2385   DISALLOW_COPY_AND_ASSIGN(ImageDumper);
2386 };
2387 
DumpImage(gc::space::ImageSpace * image_space,OatDumperOptions * options,std::ostream * os)2388 static int DumpImage(gc::space::ImageSpace* image_space,
2389                      OatDumperOptions* options,
2390                      std::ostream* os) REQUIRES_SHARED(Locks::mutator_lock_) {
2391   const ImageHeader& image_header = image_space->GetImageHeader();
2392   if (!image_header.IsValid()) {
2393     LOG(ERROR) << "Invalid image header " << image_space->GetImageLocation();
2394     return EXIT_FAILURE;
2395   }
2396   ImageDumper image_dumper(os, *image_space, image_header, options);
2397   if (!image_dumper.Dump()) {
2398     return EXIT_FAILURE;
2399   }
2400   return EXIT_SUCCESS;
2401 }
2402 
DumpImages(Runtime * runtime,OatDumperOptions * options,std::ostream * os)2403 static int DumpImages(Runtime* runtime, OatDumperOptions* options, std::ostream* os) {
2404   // Dumping the image, no explicit class loader.
2405   ScopedNullHandle<mirror::ClassLoader> null_class_loader;
2406   options->class_loader_ = &null_class_loader;
2407 
2408   ScopedObjectAccess soa(Thread::Current());
2409   if (options->app_image_ != nullptr) {
2410     if (options->app_oat_ == nullptr) {
2411       LOG(ERROR) << "Can not dump app image without app oat file";
2412       return EXIT_FAILURE;
2413     }
2414     // We can't know if the app image is 32 bits yet, but it contains pointers into the oat file.
2415     // We need to map the oat file in the low 4gb or else the fixup wont be able to fit oat file
2416     // pointers into 32 bit pointer sized ArtMethods.
2417     std::string error_msg;
2418     std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
2419                                                     options->app_oat_,
2420                                                     options->app_oat_,
2421                                                     /*executable=*/ false,
2422                                                     /*low_4gb=*/ true,
2423                                                     &error_msg));
2424     if (oat_file == nullptr) {
2425       LOG(ERROR) << "Failed to open oat file " << options->app_oat_ << " with error " << error_msg;
2426       return EXIT_FAILURE;
2427     }
2428     std::unique_ptr<gc::space::ImageSpace> space(
2429         gc::space::ImageSpace::CreateFromAppImage(options->app_image_, oat_file.get(), &error_msg));
2430     if (space == nullptr) {
2431       LOG(ERROR) << "Failed to open app image " << options->app_image_ << " with error "
2432                  << error_msg;
2433       return EXIT_FAILURE;
2434     }
2435     // Open dex files for the image.
2436     std::vector<std::unique_ptr<const DexFile>> dex_files;
2437     if (!runtime->GetClassLinker()->OpenImageDexFiles(space.get(), &dex_files, &error_msg)) {
2438       LOG(ERROR) << "Failed to open app image dex files " << options->app_image_ << " with error "
2439                  << error_msg;
2440       return EXIT_FAILURE;
2441     }
2442     // Dump the actual image.
2443     int result = DumpImage(space.get(), options, os);
2444     if (result != EXIT_SUCCESS) {
2445       return result;
2446     }
2447     // Fall through to dump the boot images.
2448   }
2449 
2450   gc::Heap* heap = runtime->GetHeap();
2451   if (!heap->HasBootImageSpace()) {
2452     LOG(ERROR) << "No image spaces";
2453     return EXIT_FAILURE;
2454   }
2455   for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
2456     int result = DumpImage(image_space, options, os);
2457     if (result != EXIT_SUCCESS) {
2458       return result;
2459     }
2460   }
2461   return EXIT_SUCCESS;
2462 }
2463 
InstallOatFile(Runtime * runtime,std::unique_ptr<OatFile> oat_file,std::vector<const DexFile * > * class_path)2464 static jobject InstallOatFile(Runtime* runtime,
2465                               std::unique_ptr<OatFile> oat_file,
2466                               std::vector<const DexFile*>* class_path)
2467     REQUIRES_SHARED(Locks::mutator_lock_) {
2468   Thread* self = Thread::Current();
2469   CHECK(self != nullptr);
2470   // Need well-known-classes.
2471   WellKnownClasses::Init(self->GetJniEnv());
2472 
2473   // Open dex files.
2474   OatFile* oat_file_ptr = oat_file.get();
2475   ClassLinker* class_linker = runtime->GetClassLinker();
2476   runtime->GetOatFileManager().RegisterOatFile(std::move(oat_file));
2477   for (const OatDexFile* odf : oat_file_ptr->GetOatDexFiles()) {
2478     std::string error_msg;
2479     const DexFile* const dex_file = OpenDexFile(odf, &error_msg);
2480     CHECK(dex_file != nullptr) << error_msg;
2481     class_path->push_back(dex_file);
2482   }
2483 
2484   // Need a class loader. Fake that we're a compiler.
2485   // Note: this will run initializers through the unstarted runtime, so make sure it's
2486   //       initialized.
2487   interpreter::UnstartedRuntime::Initialize();
2488 
2489   jobject class_loader = class_linker->CreatePathClassLoader(self, *class_path);
2490 
2491   // Need to register dex files to get a working dex cache.
2492   for (const DexFile* dex_file : *class_path) {
2493     ObjPtr<mirror::DexCache> dex_cache = class_linker->RegisterDexFile(
2494         *dex_file, self->DecodeJObject(class_loader)->AsClassLoader());
2495     CHECK(dex_cache != nullptr);
2496   }
2497 
2498   return class_loader;
2499 }
2500 
DumpOatWithRuntime(Runtime * runtime,std::unique_ptr<OatFile> oat_file,OatDumperOptions * options,std::ostream * os)2501 static int DumpOatWithRuntime(Runtime* runtime,
2502                               std::unique_ptr<OatFile> oat_file,
2503                               OatDumperOptions* options,
2504                               std::ostream* os) {
2505   CHECK(runtime != nullptr && oat_file != nullptr && options != nullptr);
2506   ScopedObjectAccess soa(Thread::Current());
2507 
2508   OatFile* oat_file_ptr = oat_file.get();
2509   std::vector<const DexFile*> class_path;
2510   jobject class_loader = InstallOatFile(runtime, std::move(oat_file), &class_path);
2511 
2512   // Use the class loader while dumping.
2513   StackHandleScope<1> scope(soa.Self());
2514   Handle<mirror::ClassLoader> loader_handle = scope.NewHandle(
2515       soa.Decode<mirror::ClassLoader>(class_loader));
2516   options->class_loader_ = &loader_handle;
2517 
2518   OatDumper oat_dumper(*oat_file_ptr, *options);
2519   bool success = oat_dumper.Dump(*os);
2520   return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2521 }
2522 
DumpOatWithoutRuntime(OatFile * oat_file,OatDumperOptions * options,std::ostream * os)2523 static int DumpOatWithoutRuntime(OatFile* oat_file, OatDumperOptions* options, std::ostream* os) {
2524   CHECK(oat_file != nullptr && options != nullptr);
2525   // No image = no class loader.
2526   ScopedNullHandle<mirror::ClassLoader> null_class_loader;
2527   options->class_loader_ = &null_class_loader;
2528 
2529   OatDumper oat_dumper(*oat_file, *options);
2530   bool success = oat_dumper.Dump(*os);
2531   return (success) ? EXIT_SUCCESS : EXIT_FAILURE;
2532 }
2533 
DumpOat(Runtime * runtime,const char * oat_filename,const char * dex_filename,OatDumperOptions * options,std::ostream * os)2534 static int DumpOat(Runtime* runtime,
2535                    const char* oat_filename,
2536                    const char* dex_filename,
2537                    OatDumperOptions* options,
2538                    std::ostream* os) {
2539   if (dex_filename == nullptr) {
2540     LOG(WARNING) << "No dex filename provided, "
2541                  << "oatdump might fail if the oat file does not contain the dex code.";
2542   }
2543   std::string dex_filename_str((dex_filename != nullptr) ? dex_filename : "");
2544   ArrayRef<const std::string> dex_filenames(&dex_filename_str,
2545                                             /*size=*/ (dex_filename != nullptr) ? 1u : 0u);
2546   std::string error_msg;
2547   std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
2548                                                   oat_filename,
2549                                                   oat_filename,
2550                                                   /*executable=*/ false,
2551                                                   /*low_4gb=*/ false,
2552                                                   dex_filenames,
2553                                                   /*reservation=*/ nullptr,
2554                                                   &error_msg));
2555   if (oat_file == nullptr) {
2556     LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
2557     return EXIT_FAILURE;
2558   }
2559 
2560   if (runtime != nullptr) {
2561     return DumpOatWithRuntime(runtime, std::move(oat_file), options, os);
2562   } else {
2563     return DumpOatWithoutRuntime(oat_file.get(), options, os);
2564   }
2565 }
2566 
SymbolizeOat(const char * oat_filename,const char * dex_filename,std::string & output_name,bool no_bits)2567 static int SymbolizeOat(const char* oat_filename,
2568                         const char* dex_filename,
2569                         std::string& output_name,
2570                         bool no_bits) {
2571   std::string dex_filename_str((dex_filename != nullptr) ? dex_filename : "");
2572   ArrayRef<const std::string> dex_filenames(&dex_filename_str,
2573                                             /*size=*/ (dex_filename != nullptr) ? 1u : 0u);
2574   std::string error_msg;
2575   std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
2576                                                   oat_filename,
2577                                                   oat_filename,
2578                                                   /*executable=*/ false,
2579                                                   /*low_4gb=*/ false,
2580                                                   dex_filenames,
2581                                                   /*reservation=*/ nullptr,
2582                                                   &error_msg));
2583   if (oat_file == nullptr) {
2584     LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
2585     return EXIT_FAILURE;
2586   }
2587 
2588   bool result;
2589   // Try to produce an ELF file of the same type. This is finicky, as we have used 32-bit ELF
2590   // files for 64-bit code in the past.
2591   if (Is64BitInstructionSet(oat_file->GetOatHeader().GetInstructionSet())) {
2592     OatSymbolizer<ElfTypes64> oat_symbolizer(oat_file.get(), output_name, no_bits);
2593     result = oat_symbolizer.Symbolize();
2594   } else {
2595     OatSymbolizer<ElfTypes32> oat_symbolizer(oat_file.get(), output_name, no_bits);
2596     result = oat_symbolizer.Symbolize();
2597   }
2598   if (!result) {
2599     LOG(ERROR) << "Failed to symbolize";
2600     return EXIT_FAILURE;
2601   }
2602 
2603   return EXIT_SUCCESS;
2604 }
2605 
2606 class IMTDumper {
2607  public:
Dump(Runtime * runtime,const std::string & imt_file,bool dump_imt_stats,const char * oat_filename,const char * dex_filename)2608   static bool Dump(Runtime* runtime,
2609                    const std::string& imt_file,
2610                    bool dump_imt_stats,
2611                    const char* oat_filename,
2612                    const char* dex_filename) {
2613     Thread* self = Thread::Current();
2614 
2615     ScopedObjectAccess soa(self);
2616     StackHandleScope<1> scope(self);
2617     MutableHandle<mirror::ClassLoader> class_loader = scope.NewHandle<mirror::ClassLoader>(nullptr);
2618     std::vector<const DexFile*> class_path;
2619 
2620     if (oat_filename != nullptr) {
2621     std::string dex_filename_str((dex_filename != nullptr) ? dex_filename : "");
2622     ArrayRef<const std::string> dex_filenames(&dex_filename_str,
2623                                               /*size=*/ (dex_filename != nullptr) ? 1u : 0u);
2624       std::string error_msg;
2625       std::unique_ptr<OatFile> oat_file(OatFile::Open(/*zip_fd=*/ -1,
2626                                                       oat_filename,
2627                                                       oat_filename,
2628                                                       /*executable=*/ false,
2629                                                       /*low_4gb=*/false,
2630                                                       dex_filenames,
2631                                                       /*reservation=*/ nullptr,
2632                                                       &error_msg));
2633       if (oat_file == nullptr) {
2634         LOG(ERROR) << "Failed to open oat file from '" << oat_filename << "': " << error_msg;
2635         return false;
2636       }
2637 
2638       class_loader.Assign(soa.Decode<mirror::ClassLoader>(
2639           InstallOatFile(runtime, std::move(oat_file), &class_path)));
2640     } else {
2641       class_loader.Assign(nullptr);  // Boot classloader. Just here for explicit documentation.
2642       class_path = runtime->GetClassLinker()->GetBootClassPath();
2643     }
2644 
2645     if (!imt_file.empty()) {
2646       return DumpImt(runtime, imt_file, class_loader);
2647     }
2648 
2649     if (dump_imt_stats) {
2650       return DumpImtStats(runtime, class_path, class_loader);
2651     }
2652 
2653     LOG(FATAL) << "Should not reach here";
2654     UNREACHABLE();
2655   }
2656 
2657  private:
DumpImt(Runtime * runtime,const std::string & imt_file,Handle<mirror::ClassLoader> h_class_loader)2658   static bool DumpImt(Runtime* runtime,
2659                       const std::string& imt_file,
2660                       Handle<mirror::ClassLoader> h_class_loader)
2661       REQUIRES_SHARED(Locks::mutator_lock_) {
2662     std::vector<std::string> lines = ReadCommentedInputFromFile(imt_file);
2663     std::unordered_set<std::string> prepared;
2664 
2665     for (const std::string& line : lines) {
2666       // A line should be either a class descriptor, in which case we will dump the complete IMT,
2667       // or a class descriptor and an interface method, in which case we will lookup the method,
2668       // determine its IMT slot, and check the class' IMT.
2669       size_t first_space = line.find(' ');
2670       if (first_space == std::string::npos) {
2671         DumpIMTForClass(runtime, line, h_class_loader, &prepared);
2672       } else {
2673         DumpIMTForMethod(runtime,
2674                          line.substr(0, first_space),
2675                          line.substr(first_space + 1, std::string::npos),
2676                          h_class_loader,
2677                          &prepared);
2678       }
2679       std::cerr << std::endl;
2680     }
2681 
2682     return true;
2683   }
2684 
DumpImtStats(Runtime * runtime,const std::vector<const DexFile * > & dex_files,Handle<mirror::ClassLoader> h_class_loader)2685   static bool DumpImtStats(Runtime* runtime,
2686                            const std::vector<const DexFile*>& dex_files,
2687                            Handle<mirror::ClassLoader> h_class_loader)
2688       REQUIRES_SHARED(Locks::mutator_lock_) {
2689     size_t without_imt = 0;
2690     size_t with_imt = 0;
2691     std::map<size_t, size_t> histogram;
2692 
2693     ClassLinker* class_linker = runtime->GetClassLinker();
2694     const PointerSize pointer_size = class_linker->GetImagePointerSize();
2695     std::unordered_set<std::string> prepared;
2696 
2697     Thread* self = Thread::Current();
2698     StackHandleScope<1> scope(self);
2699     MutableHandle<mirror::Class> h_klass(scope.NewHandle<mirror::Class>(nullptr));
2700 
2701     for (const DexFile* dex_file : dex_files) {
2702       for (uint32_t class_def_index = 0;
2703            class_def_index != dex_file->NumClassDefs();
2704            ++class_def_index) {
2705         const dex::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
2706         const char* descriptor = dex_file->GetClassDescriptor(class_def);
2707         h_klass.Assign(class_linker->FindClass(self, descriptor, h_class_loader));
2708         if (h_klass == nullptr) {
2709           std::cerr << "Warning: could not load " << descriptor << std::endl;
2710           continue;
2711         }
2712 
2713         if (HasNoIMT(runtime, h_klass, pointer_size, &prepared)) {
2714           without_imt++;
2715           continue;
2716         }
2717 
2718         ImTable* im_table = PrepareAndGetImTable(runtime, h_klass, pointer_size, &prepared);
2719         if (im_table == nullptr) {
2720           // Should not happen, but accept.
2721           without_imt++;
2722           continue;
2723         }
2724 
2725         with_imt++;
2726         for (size_t imt_index = 0; imt_index != ImTable::kSize; ++imt_index) {
2727           ArtMethod* ptr = im_table->Get(imt_index, pointer_size);
2728           if (ptr->IsRuntimeMethod()) {
2729             if (ptr->IsImtUnimplementedMethod()) {
2730               histogram[0]++;
2731             } else {
2732               ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
2733               histogram[current_table->NumEntries(pointer_size)]++;
2734             }
2735           } else {
2736             histogram[1]++;
2737           }
2738         }
2739       }
2740     }
2741 
2742     std::cerr << "IMT stats:"
2743               << std::endl << std::endl;
2744 
2745     std::cerr << "  " << with_imt << " classes with IMT."
2746               << std::endl << std::endl;
2747     std::cerr << "  " << without_imt << " classes without IMT (or copy from Object)."
2748               << std::endl << std::endl;
2749 
2750     double sum_one = 0;
2751     size_t count_one = 0;
2752 
2753     std::cerr << "  " << "IMT histogram" << std::endl;
2754     for (auto& bucket : histogram) {
2755       std::cerr << "    " << bucket.first << " " << bucket.second << std::endl;
2756       if (bucket.first > 0) {
2757         sum_one += bucket.second * bucket.first;
2758         count_one += bucket.second;
2759       }
2760     }
2761 
2762     double count_zero = count_one + histogram[0];
2763     std::cerr << "   Stats:" << std::endl;
2764     std::cerr << "     Average depth (including empty): " << (sum_one / count_zero) << std::endl;
2765     std::cerr << "     Average depth (excluding empty): " << (sum_one / count_one) << std::endl;
2766 
2767     return true;
2768   }
2769 
2770   // Return whether the given class has no IMT (or the one shared with java.lang.Object).
HasNoIMT(Runtime * runtime,Handle<mirror::Class> klass,const PointerSize pointer_size,std::unordered_set<std::string> * prepared)2771   static bool HasNoIMT(Runtime* runtime,
2772                        Handle<mirror::Class> klass,
2773                        const PointerSize pointer_size,
2774                        std::unordered_set<std::string>* prepared)
2775       REQUIRES_SHARED(Locks::mutator_lock_) {
2776     if (klass->IsObjectClass() || !klass->ShouldHaveImt()) {
2777       return true;
2778     }
2779 
2780     if (klass->GetImt(pointer_size) == nullptr) {
2781       PrepareClass(runtime, klass, prepared);
2782     }
2783 
2784     ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>();
2785     DCHECK(object_class->IsObjectClass());
2786 
2787     bool result = klass->GetImt(pointer_size) == object_class->GetImt(pointer_size);
2788 
2789     if (klass->GetIfTable()->Count() == 0) {
2790       DCHECK(result);
2791     }
2792 
2793     return result;
2794   }
2795 
PrintTable(ImtConflictTable * table,PointerSize pointer_size)2796   static void PrintTable(ImtConflictTable* table, PointerSize pointer_size)
2797       REQUIRES_SHARED(Locks::mutator_lock_) {
2798     if (table == nullptr) {
2799       std::cerr << "    <No IMT?>" << std::endl;
2800       return;
2801     }
2802     size_t table_index = 0;
2803     for (;;) {
2804       ArtMethod* ptr = table->GetInterfaceMethod(table_index, pointer_size);
2805       if (ptr == nullptr) {
2806         return;
2807       }
2808       table_index++;
2809       std::cerr << "    " << ptr->PrettyMethod(true) << std::endl;
2810     }
2811   }
2812 
PrepareAndGetImTable(Runtime * runtime,Thread * self,Handle<mirror::ClassLoader> h_loader,const std::string & class_name,const PointerSize pointer_size,ObjPtr<mirror::Class> * klass_out,std::unordered_set<std::string> * prepared)2813   static ImTable* PrepareAndGetImTable(Runtime* runtime,
2814                                        Thread* self,
2815                                        Handle<mirror::ClassLoader> h_loader,
2816                                        const std::string& class_name,
2817                                        const PointerSize pointer_size,
2818                                        /*out*/ ObjPtr<mirror::Class>* klass_out,
2819                                        /*inout*/ std::unordered_set<std::string>* prepared)
2820       REQUIRES_SHARED(Locks::mutator_lock_) {
2821     if (class_name.empty()) {
2822       return nullptr;
2823     }
2824 
2825     std::string descriptor;
2826     if (class_name[0] == 'L') {
2827       descriptor = class_name;
2828     } else {
2829       descriptor = DotToDescriptor(class_name.c_str());
2830     }
2831 
2832     ObjPtr<mirror::Class> klass =
2833         runtime->GetClassLinker()->FindClass(self, descriptor.c_str(), h_loader);
2834 
2835     if (klass == nullptr) {
2836       self->ClearException();
2837       std::cerr << "Did not find " <<  class_name << std::endl;
2838       *klass_out = nullptr;
2839       return nullptr;
2840     }
2841 
2842     StackHandleScope<1> scope(Thread::Current());
2843     Handle<mirror::Class> h_klass = scope.NewHandle<mirror::Class>(klass);
2844 
2845     ImTable* ret = PrepareAndGetImTable(runtime, h_klass, pointer_size, prepared);
2846     *klass_out = h_klass.Get();
2847     return ret;
2848   }
2849 
PrepareAndGetImTable(Runtime * runtime,Handle<mirror::Class> h_klass,const PointerSize pointer_size,std::unordered_set<std::string> * prepared)2850   static ImTable* PrepareAndGetImTable(Runtime* runtime,
2851                                        Handle<mirror::Class> h_klass,
2852                                        const PointerSize pointer_size,
2853                                        /*inout*/ std::unordered_set<std::string>* prepared)
2854       REQUIRES_SHARED(Locks::mutator_lock_) {
2855     PrepareClass(runtime, h_klass, prepared);
2856     return h_klass->GetImt(pointer_size);
2857   }
2858 
DumpIMTForClass(Runtime * runtime,const std::string & class_name,Handle<mirror::ClassLoader> h_loader,std::unordered_set<std::string> * prepared)2859   static void DumpIMTForClass(Runtime* runtime,
2860                               const std::string& class_name,
2861                               Handle<mirror::ClassLoader> h_loader,
2862                               std::unordered_set<std::string>* prepared)
2863       REQUIRES_SHARED(Locks::mutator_lock_) {
2864     const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
2865     ObjPtr<mirror::Class> klass;
2866     ImTable* imt = PrepareAndGetImTable(runtime,
2867                                         Thread::Current(),
2868                                         h_loader,
2869                                         class_name,
2870                                         pointer_size,
2871                                         &klass,
2872                                         prepared);
2873     if (imt == nullptr) {
2874       return;
2875     }
2876 
2877     std::cerr << class_name << std::endl << " IMT:" << std::endl;
2878     for (size_t index = 0; index < ImTable::kSize; ++index) {
2879       std::cerr << "  " << index << ":" << std::endl;
2880       ArtMethod* ptr = imt->Get(index, pointer_size);
2881       if (ptr->IsRuntimeMethod()) {
2882         if (ptr->IsImtUnimplementedMethod()) {
2883           std::cerr << "    <empty>" << std::endl;
2884         } else {
2885           ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
2886           PrintTable(current_table, pointer_size);
2887         }
2888       } else {
2889         std::cerr << "    " << ptr->PrettyMethod(true) << std::endl;
2890       }
2891     }
2892 
2893     std::cerr << " Interfaces:" << std::endl;
2894     // Run through iftable, find methods that slot here, see if they fit.
2895     ObjPtr<mirror::IfTable> if_table = klass->GetIfTable();
2896     for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
2897       ObjPtr<mirror::Class> iface = if_table->GetInterface(i);
2898       std::string iface_name;
2899       std::cerr << "  " << iface->GetDescriptor(&iface_name) << std::endl;
2900 
2901       for (ArtMethod& iface_method : iface->GetVirtualMethods(pointer_size)) {
2902         uint32_t class_hash, name_hash, signature_hash;
2903         ImTable::GetImtHashComponents(&iface_method, &class_hash, &name_hash, &signature_hash);
2904         uint32_t imt_slot = ImTable::GetImtIndex(&iface_method);
2905         std::cerr << "    " << iface_method.PrettyMethod(true)
2906             << " slot=" << imt_slot
2907             << std::hex
2908             << " class_hash=0x" << class_hash
2909             << " name_hash=0x" << name_hash
2910             << " signature_hash=0x" << signature_hash
2911             << std::dec
2912             << std::endl;
2913       }
2914     }
2915   }
2916 
DumpIMTForMethod(Runtime * runtime,const std::string & class_name,const std::string & method,Handle<mirror::ClassLoader> h_loader,std::unordered_set<std::string> * prepared)2917   static void DumpIMTForMethod(Runtime* runtime,
2918                                const std::string& class_name,
2919                                const std::string& method,
2920                                Handle<mirror::ClassLoader> h_loader,
2921                                /*inout*/ std::unordered_set<std::string>* prepared)
2922       REQUIRES_SHARED(Locks::mutator_lock_) {
2923     const PointerSize pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
2924     ObjPtr<mirror::Class> klass;
2925     ImTable* imt = PrepareAndGetImTable(runtime,
2926                                         Thread::Current(),
2927                                         h_loader,
2928                                         class_name,
2929                                         pointer_size,
2930                                         &klass,
2931                                         prepared);
2932     if (imt == nullptr) {
2933       return;
2934     }
2935 
2936     std::cerr << class_name << " <" << method << ">" << std::endl;
2937     for (size_t index = 0; index < ImTable::kSize; ++index) {
2938       ArtMethod* ptr = imt->Get(index, pointer_size);
2939       if (ptr->IsRuntimeMethod()) {
2940         if (ptr->IsImtUnimplementedMethod()) {
2941           continue;
2942         }
2943 
2944         ImtConflictTable* current_table = ptr->GetImtConflictTable(pointer_size);
2945         if (current_table == nullptr) {
2946           continue;
2947         }
2948 
2949         size_t table_index = 0;
2950         for (;;) {
2951           ArtMethod* ptr2 = current_table->GetInterfaceMethod(table_index, pointer_size);
2952           if (ptr2 == nullptr) {
2953             break;
2954           }
2955           table_index++;
2956 
2957           std::string p_name = ptr2->PrettyMethod(true);
2958           if (android::base::StartsWith(p_name, method.c_str())) {
2959             std::cerr << "  Slot "
2960                       << index
2961                       << " ("
2962                       << current_table->NumEntries(pointer_size)
2963                       << ")"
2964                       << std::endl;
2965             PrintTable(current_table, pointer_size);
2966             return;
2967           }
2968         }
2969       } else {
2970         std::string p_name = ptr->PrettyMethod(true);
2971         if (android::base::StartsWith(p_name, method.c_str())) {
2972           std::cerr << "  Slot " << index << " (1)" << std::endl;
2973           std::cerr << "    " << p_name << std::endl;
2974         } else {
2975           // Run through iftable, find methods that slot here, see if they fit.
2976           ObjPtr<mirror::IfTable> if_table = klass->GetIfTable();
2977           for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
2978             ObjPtr<mirror::Class> iface = if_table->GetInterface(i);
2979             size_t num_methods = iface->NumDeclaredVirtualMethods();
2980             if (num_methods > 0) {
2981               for (ArtMethod& iface_method : iface->GetMethods(pointer_size)) {
2982                 if (ImTable::GetImtIndex(&iface_method) == index) {
2983                   std::string i_name = iface_method.PrettyMethod(true);
2984                   if (android::base::StartsWith(i_name, method.c_str())) {
2985                     std::cerr << "  Slot " << index << " (1)" << std::endl;
2986                     std::cerr << "    " << p_name << " (" << i_name << ")" << std::endl;
2987                   }
2988                 }
2989               }
2990             }
2991           }
2992         }
2993       }
2994     }
2995   }
2996 
2997   // Read lines from the given stream, dropping comments and empty lines
ReadCommentedInputStream(std::istream & in_stream)2998   static std::vector<std::string> ReadCommentedInputStream(std::istream& in_stream) {
2999     std::vector<std::string> output;
3000     while (in_stream.good()) {
3001       std::string dot;
3002       std::getline(in_stream, dot);
3003       if (android::base::StartsWith(dot, "#") || dot.empty()) {
3004         continue;
3005       }
3006       output.push_back(dot);
3007     }
3008     return output;
3009   }
3010 
3011   // Read lines from the given file, dropping comments and empty lines.
ReadCommentedInputFromFile(const std::string & input_filename)3012   static std::vector<std::string> ReadCommentedInputFromFile(const std::string& input_filename) {
3013     std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
3014     if (input_file.get() == nullptr) {
3015       LOG(ERROR) << "Failed to open input file " << input_filename;
3016       return std::vector<std::string>();
3017     }
3018     std::vector<std::string> result = ReadCommentedInputStream(*input_file);
3019     input_file->close();
3020     return result;
3021   }
3022 
3023   // Prepare a class, i.e., ensure it has a filled IMT. Will do so recursively for superclasses,
3024   // and note in the given set that the work was done.
PrepareClass(Runtime * runtime,Handle<mirror::Class> h_klass,std::unordered_set<std::string> * done)3025   static void PrepareClass(Runtime* runtime,
3026                            Handle<mirror::Class> h_klass,
3027                            /*inout*/ std::unordered_set<std::string>* done)
3028       REQUIRES_SHARED(Locks::mutator_lock_) {
3029     if (!h_klass->ShouldHaveImt()) {
3030       return;
3031     }
3032 
3033     std::string name;
3034     name = h_klass->GetDescriptor(&name);
3035 
3036     if (done->find(name) != done->end()) {
3037       return;
3038     }
3039     done->insert(name);
3040 
3041     if (h_klass->HasSuperClass()) {
3042       StackHandleScope<1> h(Thread::Current());
3043       PrepareClass(runtime, h.NewHandle<mirror::Class>(h_klass->GetSuperClass()), done);
3044     }
3045 
3046     if (!h_klass->IsTemp()) {
3047       runtime->GetClassLinker()->FillIMTAndConflictTables(h_klass.Get());
3048     }
3049   }
3050 };
3051 
3052 struct OatdumpArgs : public CmdlineArgs {
3053  protected:
3054   using Base = CmdlineArgs;
3055 
ParseCustomart::OatdumpArgs3056   ParseStatus ParseCustom(const char* raw_option,
3057                           size_t raw_option_length,
3058                           std::string* error_msg) override {
3059     DCHECK_EQ(strlen(raw_option), raw_option_length);
3060     {
3061       ParseStatus base_parse = Base::ParseCustom(raw_option, raw_option_length, error_msg);
3062       if (base_parse != kParseUnknownArgument) {
3063         return base_parse;
3064       }
3065     }
3066 
3067     std::string_view option(raw_option, raw_option_length);
3068     if (StartsWith(option, "--oat-file=")) {
3069       oat_filename_ = raw_option + strlen("--oat-file=");
3070     } else if (StartsWith(option, "--dex-file=")) {
3071       dex_filename_ = raw_option + strlen("--dex-file=");
3072     } else if (StartsWith(option, "--image=")) {
3073       image_location_ = raw_option + strlen("--image=");
3074     } else if (option == "--no-dump:vmap") {
3075       dump_vmap_ = false;
3076     } else if (option =="--dump:code_info_stack_maps") {
3077       dump_code_info_stack_maps_ = true;
3078     } else if (option == "--no-disassemble") {
3079       disassemble_code_ = false;
3080     } else if (option =="--header-only") {
3081       dump_header_only_ = true;
3082     } else if (StartsWith(option, "--symbolize=")) {
3083       oat_filename_ = raw_option + strlen("--symbolize=");
3084       symbolize_ = true;
3085     } else if (StartsWith(option, "--only-keep-debug")) {
3086       only_keep_debug_ = true;
3087     } else if (StartsWith(option, "--class-filter=")) {
3088       class_filter_ = raw_option + strlen("--class-filter=");
3089     } else if (StartsWith(option, "--method-filter=")) {
3090       method_filter_ = raw_option + strlen("--method-filter=");
3091     } else if (StartsWith(option, "--list-classes")) {
3092       list_classes_ = true;
3093     } else if (StartsWith(option, "--list-methods")) {
3094       list_methods_ = true;
3095     } else if (StartsWith(option, "--export-dex-to=")) {
3096       export_dex_location_ = raw_option + strlen("--export-dex-to=");
3097     } else if (StartsWith(option, "--addr2instr=")) {
3098       if (!android::base::ParseUint(raw_option + strlen("--addr2instr="), &addr2instr_)) {
3099         *error_msg = "Address conversion failed";
3100         return kParseError;
3101       }
3102     } else if (StartsWith(option, "--app-image=")) {
3103       app_image_ = raw_option + strlen("--app-image=");
3104     } else if (StartsWith(option, "--app-oat=")) {
3105       app_oat_ = raw_option + strlen("--app-oat=");
3106     } else if (StartsWith(option, "--dump-imt=")) {
3107       imt_dump_ = std::string(option.substr(strlen("--dump-imt=")));
3108     } else if (option == "--dump-imt-stats") {
3109       imt_stat_dump_ = true;
3110     } else {
3111       return kParseUnknownArgument;
3112     }
3113 
3114     return kParseOk;
3115   }
3116 
ParseChecksart::OatdumpArgs3117   ParseStatus ParseChecks(std::string* error_msg) override {
3118     // Infer boot image location from the image location if possible.
3119     if (boot_image_location_ == nullptr) {
3120       boot_image_location_ = image_location_;
3121     }
3122 
3123     // Perform the parent checks.
3124     ParseStatus parent_checks = Base::ParseChecks(error_msg);
3125     if (parent_checks != kParseOk) {
3126       return parent_checks;
3127     }
3128 
3129     // Perform our own checks.
3130     if (image_location_ == nullptr && oat_filename_ == nullptr) {
3131       *error_msg = "Either --image or --oat-file must be specified";
3132       return kParseError;
3133     } else if (image_location_ != nullptr && oat_filename_ != nullptr) {
3134       *error_msg = "Either --image or --oat-file must be specified but not both";
3135       return kParseError;
3136     }
3137 
3138     return kParseOk;
3139   }
3140 
GetUsageart::OatdumpArgs3141   std::string GetUsage() const override {
3142     std::string usage;
3143 
3144     usage +=
3145         "Usage: oatdump [options] ...\n"
3146         "    Example: oatdump --image=$ANDROID_PRODUCT_OUT/system/framework/boot.art\n"
3147         "    Example: adb shell oatdump --image=/system/framework/boot.art\n"
3148         "\n"
3149         // Either oat-file or image is required.
3150         "  --oat-file=<file.oat>: specifies an input oat filename.\n"
3151         "      Example: --oat-file=/system/framework/arm64/boot.oat\n"
3152         "\n"
3153         "  --image=<file.art>: specifies an input image location.\n"
3154         "      Example: --image=/system/framework/boot.art\n"
3155         "\n"
3156         "  --app-image=<file.art>: specifies an input app image. Must also have a specified\n"
3157         " boot image (with --image) and app oat file (with --app-oat).\n"
3158         "      Example: --app-image=app.art\n"
3159         "\n"
3160         "  --app-oat=<file.odex>: specifies an input app oat.\n"
3161         "      Example: --app-oat=app.odex\n"
3162         "\n";
3163 
3164     usage += Base::GetUsage();
3165 
3166     usage +=  // Optional.
3167         "  --no-dump:vmap may be used to disable vmap dumping.\n"
3168         "      Example: --no-dump:vmap\n"
3169         "\n"
3170         "  --dump:code_info_stack_maps enables dumping of stack maps in CodeInfo sections.\n"
3171         "      Example: --dump:code_info_stack_maps\n"
3172         "\n"
3173         "  --no-disassemble may be used to disable disassembly.\n"
3174         "      Example: --no-disassemble\n"
3175         "\n"
3176         "  --header-only may be used to print only the oat header.\n"
3177         "      Example: --header-only\n"
3178         "\n"
3179         "  --list-classes may be used to list target file classes (can be used with filters).\n"
3180         "      Example: --list-classes\n"
3181         "      Example: --list-classes --class-filter=com.example.foo\n"
3182         "\n"
3183         "  --list-methods may be used to list target file methods (can be used with filters).\n"
3184         "      Example: --list-methods\n"
3185         "      Example: --list-methods --class-filter=com.example --method-filter=foo\n"
3186         "\n"
3187         "  --symbolize=<file.oat>: output a copy of file.oat with elf symbols included.\n"
3188         "      Example: --symbolize=/system/framework/boot.oat\n"
3189         "\n"
3190         "  --only-keep-debug<file.oat>: Modifies the behaviour of --symbolize so that\n"
3191         "      .rodata and .text sections are omitted in the output file to save space.\n"
3192         "      Example: --symbolize=/system/framework/boot.oat --only-keep-debug\n"
3193         "\n"
3194         "  --class-filter=<class name>: only dumps classes that contain the filter.\n"
3195         "      Example: --class-filter=com.example.foo\n"
3196         "\n"
3197         "  --method-filter=<method name>: only dumps methods that contain the filter.\n"
3198         "      Example: --method-filter=foo\n"
3199         "\n"
3200         "  --export-dex-to=<directory>: may be used to export oat embedded dex files.\n"
3201         "      Example: --export-dex-to=/data/local/tmp\n"
3202         "\n"
3203         "  --addr2instr=<address>: output matching method disassembled code from relative\n"
3204         "                          address (e.g. PC from crash dump)\n"
3205         "      Example: --addr2instr=0x00001a3b\n"
3206         "\n"
3207         "  --dump-imt=<file.txt>: output IMT collisions (if any) for the given receiver\n"
3208         "                         types and interface methods in the given file. The file\n"
3209         "                         is read line-wise, where each line should either be a class\n"
3210         "                         name or descriptor, or a class name/descriptor and a prefix\n"
3211         "                         of a complete method name (separated by a whitespace).\n"
3212         "      Example: --dump-imt=imt.txt\n"
3213         "\n"
3214         "  --dump-imt-stats: output IMT statistics for the given boot image\n"
3215         "      Example: --dump-imt-stats"
3216         "\n";
3217 
3218     return usage;
3219   }
3220 
3221  public:
3222   const char* oat_filename_ = nullptr;
3223   const char* dex_filename_ = nullptr;
3224   const char* class_filter_ = "";
3225   const char* method_filter_ = "";
3226   const char* image_location_ = nullptr;
3227   std::string elf_filename_prefix_;
3228   std::string imt_dump_;
3229   bool dump_vmap_ = true;
3230   bool dump_code_info_stack_maps_ = false;
3231   bool disassemble_code_ = true;
3232   bool symbolize_ = false;
3233   bool only_keep_debug_ = false;
3234   bool list_classes_ = false;
3235   bool list_methods_ = false;
3236   bool dump_header_only_ = false;
3237   bool imt_stat_dump_ = false;
3238   uint32_t addr2instr_ = 0;
3239   const char* export_dex_location_ = nullptr;
3240   const char* app_image_ = nullptr;
3241   const char* app_oat_ = nullptr;
3242 };
3243 
3244 struct OatdumpMain : public CmdlineMain<OatdumpArgs> {
NeedsRuntimeart::OatdumpMain3245   bool NeedsRuntime() override {
3246     CHECK(args_ != nullptr);
3247 
3248     // If we are only doing the oat file, disable absolute_addresses. Keep them for image dumping.
3249     bool absolute_addresses = (args_->oat_filename_ == nullptr);
3250 
3251     oat_dumper_options_.reset(new OatDumperOptions(
3252         args_->dump_vmap_,
3253         args_->dump_code_info_stack_maps_,
3254         args_->disassemble_code_,
3255         absolute_addresses,
3256         args_->class_filter_,
3257         args_->method_filter_,
3258         args_->list_classes_,
3259         args_->list_methods_,
3260         args_->dump_header_only_,
3261         args_->export_dex_location_,
3262         args_->app_image_,
3263         args_->app_oat_,
3264         args_->addr2instr_));
3265 
3266     return (args_->boot_image_location_ != nullptr ||
3267             args_->image_location_ != nullptr ||
3268             !args_->imt_dump_.empty()) &&
3269           !args_->symbolize_;
3270   }
3271 
ExecuteWithoutRuntimeart::OatdumpMain3272   bool ExecuteWithoutRuntime() override {
3273     CHECK(args_ != nullptr);
3274     CHECK(args_->oat_filename_ != nullptr);
3275 
3276     MemMap::Init();
3277 
3278     if (args_->symbolize_) {
3279       // ELF has special kind of section called SHT_NOBITS which allows us to create
3280       // sections which exist but their data is omitted from the ELF file to save space.
3281       // This is what "strip --only-keep-debug" does when it creates separate ELF file
3282       // with only debug data. We use it in similar way to exclude .rodata and .text.
3283       bool no_bits = args_->only_keep_debug_;
3284       return SymbolizeOat(args_->oat_filename_, args_->dex_filename_, args_->output_name_, no_bits)
3285           == EXIT_SUCCESS;
3286     } else {
3287       return DumpOat(nullptr,
3288                      args_->oat_filename_,
3289                      args_->dex_filename_,
3290                      oat_dumper_options_.get(),
3291                      args_->os_) == EXIT_SUCCESS;
3292     }
3293   }
3294 
ExecuteWithRuntimeart::OatdumpMain3295   bool ExecuteWithRuntime(Runtime* runtime) override {
3296     CHECK(args_ != nullptr);
3297 
3298     if (!args_->imt_dump_.empty() || args_->imt_stat_dump_) {
3299       return IMTDumper::Dump(runtime,
3300                              args_->imt_dump_,
3301                              args_->imt_stat_dump_,
3302                              args_->oat_filename_,
3303                              args_->dex_filename_);
3304     }
3305 
3306     if (args_->oat_filename_ != nullptr) {
3307       return DumpOat(runtime,
3308                      args_->oat_filename_,
3309                      args_->dex_filename_,
3310                      oat_dumper_options_.get(),
3311                      args_->os_) == EXIT_SUCCESS;
3312     }
3313 
3314     return DumpImages(runtime, oat_dumper_options_.get(), args_->os_) == EXIT_SUCCESS;
3315   }
3316 
3317   std::unique_ptr<OatDumperOptions> oat_dumper_options_;
3318 };
3319 
3320 }  // namespace art
3321 
main(int argc,char ** argv)3322 int main(int argc, char** argv) {
3323   // Output all logging to stderr.
3324   android::base::SetLogger(android::base::StderrLogger);
3325 
3326   art::OatdumpMain main;
3327   return main.Main(argc, argv);
3328 }
3329