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