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