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