1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This program is a utility that works like binutils "objdump", that is, it 10 // dumps out a plethora of information about an object file depending on the 11 // flags. 12 // 13 // The flags and output of this program should be near identical to those of 14 // binutils objdump. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm-objdump.h" 19 #include "COFFDump.h" 20 #include "ELFDump.h" 21 #include "MachODump.h" 22 #include "WasmDump.h" 23 #include "XCOFFDump.h" 24 #include "llvm/ADT/IndexedMap.h" 25 #include "llvm/ADT/Optional.h" 26 #include "llvm/ADT/SmallSet.h" 27 #include "llvm/ADT/STLExtras.h" 28 #include "llvm/ADT/SetOperations.h" 29 #include "llvm/ADT/StringExtras.h" 30 #include "llvm/ADT/StringSet.h" 31 #include "llvm/ADT/Triple.h" 32 #include "llvm/CodeGen/FaultMaps.h" 33 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 34 #include "llvm/DebugInfo/Symbolize/Symbolize.h" 35 #include "llvm/Demangle/Demangle.h" 36 #include "llvm/MC/MCAsmInfo.h" 37 #include "llvm/MC/MCContext.h" 38 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 39 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h" 40 #include "llvm/MC/MCInst.h" 41 #include "llvm/MC/MCInstPrinter.h" 42 #include "llvm/MC/MCInstrAnalysis.h" 43 #include "llvm/MC/MCInstrInfo.h" 44 #include "llvm/MC/MCObjectFileInfo.h" 45 #include "llvm/MC/MCRegisterInfo.h" 46 #include "llvm/MC/MCSubtargetInfo.h" 47 #include "llvm/MC/MCTargetOptions.h" 48 #include "llvm/Object/Archive.h" 49 #include "llvm/Object/COFF.h" 50 #include "llvm/Object/COFFImportFile.h" 51 #include "llvm/Object/ELFObjectFile.h" 52 #include "llvm/Object/MachO.h" 53 #include "llvm/Object/MachOUniversal.h" 54 #include "llvm/Object/ObjectFile.h" 55 #include "llvm/Object/Wasm.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CommandLine.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/Errc.h" 60 #include "llvm/Support/FileSystem.h" 61 #include "llvm/Support/Format.h" 62 #include "llvm/Support/FormatVariadic.h" 63 #include "llvm/Support/GraphWriter.h" 64 #include "llvm/Support/Host.h" 65 #include "llvm/Support/InitLLVM.h" 66 #include "llvm/Support/MemoryBuffer.h" 67 #include "llvm/Support/SourceMgr.h" 68 #include "llvm/Support/StringSaver.h" 69 #include "llvm/Support/TargetRegistry.h" 70 #include "llvm/Support/TargetSelect.h" 71 #include "llvm/Support/WithColor.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include <algorithm> 74 #include <cctype> 75 #include <cstring> 76 #include <system_error> 77 #include <unordered_map> 78 #include <utility> 79 80 using namespace llvm; 81 using namespace llvm::object; 82 using namespace llvm::objdump; 83 84 #define DEBUG_TYPE "objdump" 85 86 static cl::OptionCategory ObjdumpCat("llvm-objdump Options"); 87 88 static cl::opt<uint64_t> AdjustVMA( 89 "adjust-vma", 90 cl::desc("Increase the displayed address by the specified offset"), 91 cl::value_desc("offset"), cl::init(0), cl::cat(ObjdumpCat)); 92 93 static cl::opt<bool> 94 AllHeaders("all-headers", 95 cl::desc("Display all available header information"), 96 cl::cat(ObjdumpCat)); 97 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"), 98 cl::NotHidden, cl::Grouping, 99 cl::aliasopt(AllHeaders)); 100 101 static cl::opt<std::string> 102 ArchName("arch-name", 103 cl::desc("Target arch to disassemble for, " 104 "see -version for available targets"), 105 cl::cat(ObjdumpCat)); 106 107 cl::opt<bool> 108 objdump::ArchiveHeaders("archive-headers", 109 cl::desc("Display archive header information"), 110 cl::cat(ObjdumpCat)); 111 static cl::alias ArchiveHeadersShort("a", 112 cl::desc("Alias for --archive-headers"), 113 cl::NotHidden, cl::Grouping, 114 cl::aliasopt(ArchiveHeaders)); 115 116 cl::opt<bool> objdump::Demangle("demangle", cl::desc("Demangle symbols names"), 117 cl::init(false), cl::cat(ObjdumpCat)); 118 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"), 119 cl::NotHidden, cl::Grouping, 120 cl::aliasopt(Demangle)); 121 122 cl::opt<bool> objdump::Disassemble( 123 "disassemble", 124 cl::desc("Display assembler mnemonics for the machine instructions"), 125 cl::cat(ObjdumpCat)); 126 static cl::alias DisassembleShort("d", cl::desc("Alias for --disassemble"), 127 cl::NotHidden, cl::Grouping, 128 cl::aliasopt(Disassemble)); 129 130 cl::opt<bool> objdump::DisassembleAll( 131 "disassemble-all", 132 cl::desc("Display assembler mnemonics for the machine instructions"), 133 cl::cat(ObjdumpCat)); 134 static cl::alias DisassembleAllShort("D", 135 cl::desc("Alias for --disassemble-all"), 136 cl::NotHidden, cl::Grouping, 137 cl::aliasopt(DisassembleAll)); 138 139 cl::opt<bool> objdump::SymbolDescription( 140 "symbol-description", 141 cl::desc("Add symbol description for disassembly. This " 142 "option is for XCOFF files only"), 143 cl::init(false), cl::cat(ObjdumpCat)); 144 145 static cl::list<std::string> 146 DisassembleSymbols("disassemble-symbols", cl::CommaSeparated, 147 cl::desc("List of symbols to disassemble. " 148 "Accept demangled names when --demangle is " 149 "specified, otherwise accept mangled names"), 150 cl::cat(ObjdumpCat)); 151 152 static cl::opt<bool> DisassembleZeroes( 153 "disassemble-zeroes", 154 cl::desc("Do not skip blocks of zeroes when disassembling"), 155 cl::cat(ObjdumpCat)); 156 static cl::alias 157 DisassembleZeroesShort("z", cl::desc("Alias for --disassemble-zeroes"), 158 cl::NotHidden, cl::Grouping, 159 cl::aliasopt(DisassembleZeroes)); 160 161 static cl::list<std::string> 162 DisassemblerOptions("disassembler-options", 163 cl::desc("Pass target specific disassembler options"), 164 cl::value_desc("options"), cl::CommaSeparated, 165 cl::cat(ObjdumpCat)); 166 static cl::alias 167 DisassemblerOptionsShort("M", cl::desc("Alias for --disassembler-options"), 168 cl::NotHidden, cl::Grouping, cl::Prefix, 169 cl::CommaSeparated, 170 cl::aliasopt(DisassemblerOptions)); 171 172 cl::opt<DIDumpType> objdump::DwarfDumpType( 173 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"), 174 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")), 175 cl::cat(ObjdumpCat)); 176 177 static cl::opt<bool> DynamicRelocations( 178 "dynamic-reloc", 179 cl::desc("Display the dynamic relocation entries in the file"), 180 cl::cat(ObjdumpCat)); 181 static cl::alias DynamicRelocationShort("R", 182 cl::desc("Alias for --dynamic-reloc"), 183 cl::NotHidden, cl::Grouping, 184 cl::aliasopt(DynamicRelocations)); 185 186 static cl::opt<bool> 187 FaultMapSection("fault-map-section", 188 cl::desc("Display contents of faultmap section"), 189 cl::cat(ObjdumpCat)); 190 191 static cl::opt<bool> 192 FileHeaders("file-headers", 193 cl::desc("Display the contents of the overall file header"), 194 cl::cat(ObjdumpCat)); 195 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"), 196 cl::NotHidden, cl::Grouping, 197 cl::aliasopt(FileHeaders)); 198 199 cl::opt<bool> 200 objdump::SectionContents("full-contents", 201 cl::desc("Display the content of each section"), 202 cl::cat(ObjdumpCat)); 203 static cl::alias SectionContentsShort("s", 204 cl::desc("Alias for --full-contents"), 205 cl::NotHidden, cl::Grouping, 206 cl::aliasopt(SectionContents)); 207 208 static cl::list<std::string> InputFilenames(cl::Positional, 209 cl::desc("<input object files>"), 210 cl::ZeroOrMore, 211 cl::cat(ObjdumpCat)); 212 213 static cl::opt<bool> 214 PrintLines("line-numbers", 215 cl::desc("Display source line numbers with " 216 "disassembly. Implies disassemble object"), 217 cl::cat(ObjdumpCat)); 218 static cl::alias PrintLinesShort("l", cl::desc("Alias for --line-numbers"), 219 cl::NotHidden, cl::Grouping, 220 cl::aliasopt(PrintLines)); 221 222 static cl::opt<bool> MachOOpt("macho", 223 cl::desc("Use MachO specific object file parser"), 224 cl::cat(ObjdumpCat)); 225 static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden, 226 cl::Grouping, cl::aliasopt(MachOOpt)); 227 228 cl::opt<std::string> objdump::MCPU( 229 "mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), 230 cl::value_desc("cpu-name"), cl::init(""), cl::cat(ObjdumpCat)); 231 232 cl::list<std::string> objdump::MAttrs("mattr", cl::CommaSeparated, 233 cl::desc("Target specific attributes"), 234 cl::value_desc("a1,+a2,-a3,..."), 235 cl::cat(ObjdumpCat)); 236 237 cl::opt<bool> objdump::NoShowRawInsn( 238 "no-show-raw-insn", 239 cl::desc( 240 "When disassembling instructions, do not print the instruction bytes."), 241 cl::cat(ObjdumpCat)); 242 243 cl::opt<bool> objdump::NoLeadingAddr("no-leading-addr", 244 cl::desc("Print no leading address"), 245 cl::cat(ObjdumpCat)); 246 247 static cl::opt<bool> RawClangAST( 248 "raw-clang-ast", 249 cl::desc("Dump the raw binary contents of the clang AST section"), 250 cl::cat(ObjdumpCat)); 251 252 cl::opt<bool> 253 objdump::Relocations("reloc", 254 cl::desc("Display the relocation entries in the file"), 255 cl::cat(ObjdumpCat)); 256 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"), 257 cl::NotHidden, cl::Grouping, 258 cl::aliasopt(Relocations)); 259 260 cl::opt<bool> 261 objdump::PrintImmHex("print-imm-hex", 262 cl::desc("Use hex format for immediate values"), 263 cl::cat(ObjdumpCat)); 264 265 cl::opt<bool> 266 objdump::PrivateHeaders("private-headers", 267 cl::desc("Display format specific file headers"), 268 cl::cat(ObjdumpCat)); 269 static cl::alias PrivateHeadersShort("p", 270 cl::desc("Alias for --private-headers"), 271 cl::NotHidden, cl::Grouping, 272 cl::aliasopt(PrivateHeaders)); 273 274 cl::list<std::string> 275 objdump::FilterSections("section", 276 cl::desc("Operate on the specified sections only. " 277 "With -macho dump segment,section"), 278 cl::cat(ObjdumpCat)); 279 static cl::alias FilterSectionsj("j", cl::desc("Alias for --section"), 280 cl::NotHidden, cl::Grouping, cl::Prefix, 281 cl::aliasopt(FilterSections)); 282 283 cl::opt<bool> objdump::SectionHeaders( 284 "section-headers", 285 cl::desc("Display summaries of the headers for each section."), 286 cl::cat(ObjdumpCat)); 287 static cl::alias SectionHeadersShort("headers", 288 cl::desc("Alias for --section-headers"), 289 cl::NotHidden, 290 cl::aliasopt(SectionHeaders)); 291 static cl::alias SectionHeadersShorter("h", 292 cl::desc("Alias for --section-headers"), 293 cl::NotHidden, cl::Grouping, 294 cl::aliasopt(SectionHeaders)); 295 296 static cl::opt<bool> 297 ShowLMA("show-lma", 298 cl::desc("Display LMA column when dumping ELF section headers"), 299 cl::cat(ObjdumpCat)); 300 301 static cl::opt<bool> PrintSource( 302 "source", 303 cl::desc( 304 "Display source inlined with disassembly. Implies disassemble object"), 305 cl::cat(ObjdumpCat)); 306 static cl::alias PrintSourceShort("S", cl::desc("Alias for -source"), 307 cl::NotHidden, cl::Grouping, 308 cl::aliasopt(PrintSource)); 309 310 static cl::opt<uint64_t> 311 StartAddress("start-address", cl::desc("Disassemble beginning at address"), 312 cl::value_desc("address"), cl::init(0), cl::cat(ObjdumpCat)); 313 static cl::opt<uint64_t> StopAddress("stop-address", 314 cl::desc("Stop disassembly at address"), 315 cl::value_desc("address"), 316 cl::init(UINT64_MAX), cl::cat(ObjdumpCat)); 317 318 cl::opt<bool> objdump::SymbolTable("syms", cl::desc("Display the symbol table"), 319 cl::cat(ObjdumpCat)); 320 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"), 321 cl::NotHidden, cl::Grouping, 322 cl::aliasopt(SymbolTable)); 323 324 static cl::opt<bool> DynamicSymbolTable( 325 "dynamic-syms", 326 cl::desc("Display the contents of the dynamic symbol table"), 327 cl::cat(ObjdumpCat)); 328 static cl::alias DynamicSymbolTableShort("T", 329 cl::desc("Alias for --dynamic-syms"), 330 cl::NotHidden, cl::Grouping, 331 cl::aliasopt(DynamicSymbolTable)); 332 333 cl::opt<std::string> objdump::TripleName( 334 "triple", 335 cl::desc( 336 "Target triple to disassemble for, see -version for available targets"), 337 cl::cat(ObjdumpCat)); 338 339 cl::opt<bool> objdump::UnwindInfo("unwind-info", 340 cl::desc("Display unwind information"), 341 cl::cat(ObjdumpCat)); 342 static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), 343 cl::NotHidden, cl::Grouping, 344 cl::aliasopt(UnwindInfo)); 345 346 static cl::opt<bool> 347 Wide("wide", cl::desc("Ignored for compatibility with GNU objdump"), 348 cl::cat(ObjdumpCat)); 349 static cl::alias WideShort("w", cl::Grouping, cl::aliasopt(Wide)); 350 351 enum DebugVarsFormat { 352 DVDisabled, 353 DVUnicode, 354 DVASCII, 355 }; 356 357 static cl::opt<DebugVarsFormat> DbgVariables( 358 "debug-vars", cl::init(DVDisabled), 359 cl::desc("Print the locations (in registers or memory) of " 360 "source-level variables alongside disassembly"), 361 cl::ValueOptional, 362 cl::values(clEnumValN(DVUnicode, "", "unicode"), 363 clEnumValN(DVUnicode, "unicode", "unicode"), 364 clEnumValN(DVASCII, "ascii", "unicode")), 365 cl::cat(ObjdumpCat)); 366 367 static cl::opt<int> 368 DbgIndent("debug-vars-indent", cl::init(40), 369 cl::desc("Distance to indent the source-level variable display, " 370 "relative to the start of the disassembly"), 371 cl::cat(ObjdumpCat)); 372 373 static cl::extrahelp 374 HelpResponse("\nPass @FILE as argument to read options from FILE.\n"); 375 376 static StringSet<> DisasmSymbolSet; 377 StringSet<> objdump::FoundSectionSet; 378 static StringRef ToolName; 379 380 namespace { 381 struct FilterResult { 382 // True if the section should not be skipped. 383 bool Keep; 384 385 // True if the index counter should be incremented, even if the section should 386 // be skipped. For example, sections may be skipped if they are not included 387 // in the --section flag, but we still want those to count toward the section 388 // count. 389 bool IncrementIndex; 390 }; 391 } // namespace 392 393 static FilterResult checkSectionFilter(object::SectionRef S) { 394 if (FilterSections.empty()) 395 return {/*Keep=*/true, /*IncrementIndex=*/true}; 396 397 Expected<StringRef> SecNameOrErr = S.getName(); 398 if (!SecNameOrErr) { 399 consumeError(SecNameOrErr.takeError()); 400 return {/*Keep=*/false, /*IncrementIndex=*/false}; 401 } 402 StringRef SecName = *SecNameOrErr; 403 404 // StringSet does not allow empty key so avoid adding sections with 405 // no name (such as the section with index 0) here. 406 if (!SecName.empty()) 407 FoundSectionSet.insert(SecName); 408 409 // Only show the section if it's in the FilterSections list, but always 410 // increment so the indexing is stable. 411 return {/*Keep=*/is_contained(FilterSections, SecName), 412 /*IncrementIndex=*/true}; 413 } 414 415 SectionFilter objdump::ToolSectionFilter(object::ObjectFile const &O, 416 uint64_t *Idx) { 417 // Start at UINT64_MAX so that the first index returned after an increment is 418 // zero (after the unsigned wrap). 419 if (Idx) 420 *Idx = UINT64_MAX; 421 return SectionFilter( 422 [Idx](object::SectionRef S) { 423 FilterResult Result = checkSectionFilter(S); 424 if (Idx != nullptr && Result.IncrementIndex) 425 *Idx += 1; 426 return Result.Keep; 427 }, 428 O); 429 } 430 431 std::string objdump::getFileNameForError(const object::Archive::Child &C, 432 unsigned Index) { 433 Expected<StringRef> NameOrErr = C.getName(); 434 if (NameOrErr) 435 return std::string(NameOrErr.get()); 436 // If we have an error getting the name then we print the index of the archive 437 // member. Since we are already in an error state, we just ignore this error. 438 consumeError(NameOrErr.takeError()); 439 return "<file index: " + std::to_string(Index) + ">"; 440 } 441 442 void objdump::reportWarning(Twine Message, StringRef File) { 443 // Output order between errs() and outs() matters especially for archive 444 // files where the output is per member object. 445 outs().flush(); 446 WithColor::warning(errs(), ToolName) 447 << "'" << File << "': " << Message << "\n"; 448 } 449 450 LLVM_ATTRIBUTE_NORETURN void objdump::reportError(StringRef File, 451 Twine Message) { 452 outs().flush(); 453 WithColor::error(errs(), ToolName) << "'" << File << "': " << Message << "\n"; 454 exit(1); 455 } 456 457 LLVM_ATTRIBUTE_NORETURN void objdump::reportError(Error E, StringRef FileName, 458 StringRef ArchiveName, 459 StringRef ArchitectureName) { 460 assert(E); 461 outs().flush(); 462 WithColor::error(errs(), ToolName); 463 if (ArchiveName != "") 464 errs() << ArchiveName << "(" << FileName << ")"; 465 else 466 errs() << "'" << FileName << "'"; 467 if (!ArchitectureName.empty()) 468 errs() << " (for architecture " << ArchitectureName << ")"; 469 errs() << ": "; 470 logAllUnhandledErrors(std::move(E), errs()); 471 exit(1); 472 } 473 474 static void reportCmdLineWarning(Twine Message) { 475 WithColor::warning(errs(), ToolName) << Message << "\n"; 476 } 477 478 LLVM_ATTRIBUTE_NORETURN static void reportCmdLineError(Twine Message) { 479 WithColor::error(errs(), ToolName) << Message << "\n"; 480 exit(1); 481 } 482 483 static void warnOnNoMatchForSections() { 484 SetVector<StringRef> MissingSections; 485 for (StringRef S : FilterSections) { 486 if (FoundSectionSet.count(S)) 487 return; 488 // User may specify a unnamed section. Don't warn for it. 489 if (!S.empty()) 490 MissingSections.insert(S); 491 } 492 493 // Warn only if no section in FilterSections is matched. 494 for (StringRef S : MissingSections) 495 reportCmdLineWarning("section '" + S + 496 "' mentioned in a -j/--section option, but not " 497 "found in any input file"); 498 } 499 500 static const Target *getTarget(const ObjectFile *Obj) { 501 // Figure out the target triple. 502 Triple TheTriple("unknown-unknown-unknown"); 503 if (TripleName.empty()) { 504 TheTriple = Obj->makeTriple(); 505 } else { 506 TheTriple.setTriple(Triple::normalize(TripleName)); 507 auto Arch = Obj->getArch(); 508 if (Arch == Triple::arm || Arch == Triple::armeb) 509 Obj->setARMSubArch(TheTriple); 510 } 511 512 // Get the target specific parser. 513 std::string Error; 514 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 515 Error); 516 if (!TheTarget) 517 reportError(Obj->getFileName(), "can't find target: " + Error); 518 519 // Update the triple name and return the found target. 520 TripleName = TheTriple.getTriple(); 521 return TheTarget; 522 } 523 524 bool objdump::isRelocAddressLess(RelocationRef A, RelocationRef B) { 525 return A.getOffset() < B.getOffset(); 526 } 527 528 static Error getRelocationValueString(const RelocationRef &Rel, 529 SmallVectorImpl<char> &Result) { 530 const ObjectFile *Obj = Rel.getObject(); 531 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj)) 532 return getELFRelocationValueString(ELF, Rel, Result); 533 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) 534 return getCOFFRelocationValueString(COFF, Rel, Result); 535 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj)) 536 return getWasmRelocationValueString(Wasm, Rel, Result); 537 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj)) 538 return getMachORelocationValueString(MachO, Rel, Result); 539 if (auto *XCOFF = dyn_cast<XCOFFObjectFile>(Obj)) 540 return getXCOFFRelocationValueString(XCOFF, Rel, Result); 541 llvm_unreachable("unknown object file format"); 542 } 543 544 /// Indicates whether this relocation should hidden when listing 545 /// relocations, usually because it is the trailing part of a multipart 546 /// relocation that will be printed as part of the leading relocation. 547 static bool getHidden(RelocationRef RelRef) { 548 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject()); 549 if (!MachO) 550 return false; 551 552 unsigned Arch = MachO->getArch(); 553 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 554 uint64_t Type = MachO->getRelocationType(Rel); 555 556 // On arches that use the generic relocations, GENERIC_RELOC_PAIR 557 // is always hidden. 558 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) 559 return Type == MachO::GENERIC_RELOC_PAIR; 560 561 if (Arch == Triple::x86_64) { 562 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows 563 // an X86_64_RELOC_SUBTRACTOR. 564 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { 565 DataRefImpl RelPrev = Rel; 566 RelPrev.d.a--; 567 uint64_t PrevType = MachO->getRelocationType(RelPrev); 568 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR) 569 return true; 570 } 571 } 572 573 return false; 574 } 575 576 namespace { 577 578 /// Get the column at which we want to start printing the instruction 579 /// disassembly, taking into account anything which appears to the left of it. 580 unsigned getInstStartColumn(const MCSubtargetInfo &STI) { 581 return NoShowRawInsn ? 16 : STI.getTargetTriple().isX86() ? 40 : 24; 582 } 583 584 /// Stores a single expression representing the location of a source-level 585 /// variable, along with the PC range for which that expression is valid. 586 struct LiveVariable { 587 DWARFLocationExpression LocExpr; 588 const char *VarName; 589 DWARFUnit *Unit; 590 const DWARFDie FuncDie; 591 592 LiveVariable(const DWARFLocationExpression &LocExpr, const char *VarName, 593 DWARFUnit *Unit, const DWARFDie FuncDie) 594 : LocExpr(LocExpr), VarName(VarName), Unit(Unit), FuncDie(FuncDie) {} 595 596 bool liveAtAddress(object::SectionedAddress Addr) { 597 if (LocExpr.Range == None) 598 return false; 599 return LocExpr.Range->SectionIndex == Addr.SectionIndex && 600 LocExpr.Range->LowPC <= Addr.Address && 601 LocExpr.Range->HighPC > Addr.Address; 602 } 603 604 void print(raw_ostream &OS, const MCRegisterInfo &MRI) const { 605 DataExtractor Data({LocExpr.Expr.data(), LocExpr.Expr.size()}, 606 Unit->getContext().isLittleEndian(), 0); 607 DWARFExpression Expression(Data, Unit->getAddressByteSize()); 608 Expression.printCompact(OS, MRI); 609 } 610 }; 611 612 /// Helper class for printing source variable locations alongside disassembly. 613 class LiveVariablePrinter { 614 // Information we want to track about one column in which we are printing a 615 // variable live range. 616 struct Column { 617 unsigned VarIdx = NullVarIdx; 618 bool LiveIn = false; 619 bool LiveOut = false; 620 bool MustDrawLabel = false; 621 622 bool isActive() const { return VarIdx != NullVarIdx; } 623 624 static constexpr unsigned NullVarIdx = std::numeric_limits<unsigned>::max(); 625 }; 626 627 // All live variables we know about in the object/image file. 628 std::vector<LiveVariable> LiveVariables; 629 630 // The columns we are currently drawing. 631 IndexedMap<Column> ActiveCols; 632 633 const MCRegisterInfo &MRI; 634 const MCSubtargetInfo &STI; 635 636 void addVariable(DWARFDie FuncDie, DWARFDie VarDie) { 637 uint64_t FuncLowPC, FuncHighPC, SectionIndex; 638 FuncDie.getLowAndHighPC(FuncLowPC, FuncHighPC, SectionIndex); 639 const char *VarName = VarDie.getName(DINameKind::ShortName); 640 DWARFUnit *U = VarDie.getDwarfUnit(); 641 642 Expected<DWARFLocationExpressionsVector> Locs = 643 VarDie.getLocations(dwarf::DW_AT_location); 644 if (!Locs) { 645 // If the variable doesn't have any locations, just ignore it. We don't 646 // report an error or warning here as that could be noisy on optimised 647 // code. 648 consumeError(Locs.takeError()); 649 return; 650 } 651 652 for (const DWARFLocationExpression &LocExpr : *Locs) { 653 if (LocExpr.Range) { 654 LiveVariables.emplace_back(LocExpr, VarName, U, FuncDie); 655 } else { 656 // If the LocExpr does not have an associated range, it is valid for 657 // the whole of the function. 658 // TODO: technically it is not valid for any range covered by another 659 // LocExpr, does that happen in reality? 660 DWARFLocationExpression WholeFuncExpr{ 661 DWARFAddressRange(FuncLowPC, FuncHighPC, SectionIndex), 662 LocExpr.Expr}; 663 LiveVariables.emplace_back(WholeFuncExpr, VarName, U, FuncDie); 664 } 665 } 666 } 667 668 void addFunction(DWARFDie D) { 669 for (const DWARFDie &Child : D.children()) { 670 if (Child.getTag() == dwarf::DW_TAG_variable || 671 Child.getTag() == dwarf::DW_TAG_formal_parameter) 672 addVariable(D, Child); 673 else 674 addFunction(Child); 675 } 676 } 677 678 // Get the column number (in characters) at which the first live variable 679 // line should be printed. 680 unsigned getIndentLevel() const { 681 return DbgIndent + getInstStartColumn(STI); 682 } 683 684 // Indent to the first live-range column to the right of the currently 685 // printed line, and return the index of that column. 686 // TODO: formatted_raw_ostream uses "column" to mean a number of characters 687 // since the last \n, and we use it to mean the number of slots in which we 688 // put live variable lines. Pick a less overloaded word. 689 unsigned moveToFirstVarColumn(formatted_raw_ostream &OS) { 690 // Logical column number: column zero is the first column we print in, each 691 // logical column is 2 physical columns wide. 692 unsigned FirstUnprintedLogicalColumn = 693 std::max((int)(OS.getColumn() - getIndentLevel() + 1) / 2, 0); 694 // Physical column number: the actual column number in characters, with 695 // zero being the left-most side of the screen. 696 unsigned FirstUnprintedPhysicalColumn = 697 getIndentLevel() + FirstUnprintedLogicalColumn * 2; 698 699 if (FirstUnprintedPhysicalColumn > OS.getColumn()) 700 OS.PadToColumn(FirstUnprintedPhysicalColumn); 701 702 return FirstUnprintedLogicalColumn; 703 } 704 705 unsigned findFreeColumn() { 706 for (unsigned ColIdx = 0; ColIdx < ActiveCols.size(); ++ColIdx) 707 if (!ActiveCols[ColIdx].isActive()) 708 return ColIdx; 709 710 size_t OldSize = ActiveCols.size(); 711 ActiveCols.grow(std::max<size_t>(OldSize * 2, 1)); 712 return OldSize; 713 } 714 715 public: 716 LiveVariablePrinter(const MCRegisterInfo &MRI, const MCSubtargetInfo &STI) 717 : LiveVariables(), ActiveCols(Column()), MRI(MRI), STI(STI) {} 718 719 void dump() const { 720 for (const LiveVariable &LV : LiveVariables) { 721 dbgs() << LV.VarName << " @ " << LV.LocExpr.Range << ": "; 722 LV.print(dbgs(), MRI); 723 dbgs() << "\n"; 724 } 725 } 726 727 void addCompileUnit(DWARFDie D) { 728 if (D.getTag() == dwarf::DW_TAG_subprogram) 729 addFunction(D); 730 else 731 for (const DWARFDie &Child : D.children()) 732 addFunction(Child); 733 } 734 735 /// Update to match the state of the instruction between ThisAddr and 736 /// NextAddr. In the common case, any live range active at ThisAddr is 737 /// live-in to the instruction, and any live range active at NextAddr is 738 /// live-out of the instruction. If IncludeDefinedVars is false, then live 739 /// ranges starting at NextAddr will be ignored. 740 void update(object::SectionedAddress ThisAddr, 741 object::SectionedAddress NextAddr, bool IncludeDefinedVars) { 742 // First, check variables which have already been assigned a column, so 743 // that we don't change their order. 744 SmallSet<unsigned, 8> CheckedVarIdxs; 745 for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx) { 746 if (!ActiveCols[ColIdx].isActive()) 747 continue; 748 CheckedVarIdxs.insert(ActiveCols[ColIdx].VarIdx); 749 LiveVariable &LV = LiveVariables[ActiveCols[ColIdx].VarIdx]; 750 ActiveCols[ColIdx].LiveIn = LV.liveAtAddress(ThisAddr); 751 ActiveCols[ColIdx].LiveOut = LV.liveAtAddress(NextAddr); 752 LLVM_DEBUG(dbgs() << "pass 1, " << ThisAddr.Address << "-" 753 << NextAddr.Address << ", " << LV.VarName << ", Col " 754 << ColIdx << ": LiveIn=" << ActiveCols[ColIdx].LiveIn 755 << ", LiveOut=" << ActiveCols[ColIdx].LiveOut << "\n"); 756 757 if (!ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut) 758 ActiveCols[ColIdx].VarIdx = Column::NullVarIdx; 759 } 760 761 // Next, look for variables which don't already have a column, but which 762 // are now live. 763 if (IncludeDefinedVars) { 764 for (unsigned VarIdx = 0, End = LiveVariables.size(); VarIdx < End; 765 ++VarIdx) { 766 if (CheckedVarIdxs.count(VarIdx)) 767 continue; 768 LiveVariable &LV = LiveVariables[VarIdx]; 769 bool LiveIn = LV.liveAtAddress(ThisAddr); 770 bool LiveOut = LV.liveAtAddress(NextAddr); 771 if (!LiveIn && !LiveOut) 772 continue; 773 774 unsigned ColIdx = findFreeColumn(); 775 LLVM_DEBUG(dbgs() << "pass 2, " << ThisAddr.Address << "-" 776 << NextAddr.Address << ", " << LV.VarName << ", Col " 777 << ColIdx << ": LiveIn=" << LiveIn 778 << ", LiveOut=" << LiveOut << "\n"); 779 ActiveCols[ColIdx].VarIdx = VarIdx; 780 ActiveCols[ColIdx].LiveIn = LiveIn; 781 ActiveCols[ColIdx].LiveOut = LiveOut; 782 ActiveCols[ColIdx].MustDrawLabel = true; 783 } 784 } 785 } 786 787 enum class LineChar { 788 RangeStart, 789 RangeMid, 790 RangeEnd, 791 LabelVert, 792 LabelCornerNew, 793 LabelCornerActive, 794 LabelHoriz, 795 }; 796 const char *getLineChar(LineChar C) const { 797 bool IsASCII = DbgVariables == DVASCII; 798 switch (C) { 799 case LineChar::RangeStart: 800 return IsASCII ? "^" : u8"\u2548"; 801 case LineChar::RangeMid: 802 return IsASCII ? "|" : u8"\u2503"; 803 case LineChar::RangeEnd: 804 return IsASCII ? "v" : u8"\u253b"; 805 case LineChar::LabelVert: 806 return IsASCII ? "|" : u8"\u2502"; 807 case LineChar::LabelCornerNew: 808 return IsASCII ? "/" : u8"\u250c"; 809 case LineChar::LabelCornerActive: 810 return IsASCII ? "|" : u8"\u2520"; 811 case LineChar::LabelHoriz: 812 return IsASCII ? "-" : u8"\u2500"; 813 } 814 llvm_unreachable("Unhandled LineChar enum"); 815 } 816 817 /// Print live ranges to the right of an existing line. This assumes the 818 /// line is not an instruction, so doesn't start or end any live ranges, so 819 /// we only need to print active ranges or empty columns. If AfterInst is 820 /// true, this is being printed after the last instruction fed to update(), 821 /// otherwise this is being printed before it. 822 void printAfterOtherLine(formatted_raw_ostream &OS, bool AfterInst) { 823 if (ActiveCols.size()) { 824 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS); 825 for (size_t ColIdx = FirstUnprintedColumn, End = ActiveCols.size(); 826 ColIdx < End; ++ColIdx) { 827 if (ActiveCols[ColIdx].isActive()) { 828 if ((AfterInst && ActiveCols[ColIdx].LiveOut) || 829 (!AfterInst && ActiveCols[ColIdx].LiveIn)) 830 OS << getLineChar(LineChar::RangeMid); 831 else if (!AfterInst && ActiveCols[ColIdx].LiveOut) 832 OS << getLineChar(LineChar::LabelVert); 833 else 834 OS << " "; 835 } 836 OS << " "; 837 } 838 } 839 OS << "\n"; 840 } 841 842 /// Print any live variable range info needed to the right of a 843 /// non-instruction line of disassembly. This is where we print the variable 844 /// names and expressions, with thin line-drawing characters connecting them 845 /// to the live range which starts at the next instruction. If MustPrint is 846 /// true, we have to print at least one line (with the continuation of any 847 /// already-active live ranges) because something has already been printed 848 /// earlier on this line. 849 void printBetweenInsts(formatted_raw_ostream &OS, bool MustPrint) { 850 bool PrintedSomething = false; 851 for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx) { 852 if (ActiveCols[ColIdx].isActive() && ActiveCols[ColIdx].MustDrawLabel) { 853 // First we need to print the live range markers for any active 854 // columns to the left of this one. 855 OS.PadToColumn(getIndentLevel()); 856 for (unsigned ColIdx2 = 0; ColIdx2 < ColIdx; ++ColIdx2) { 857 if (ActiveCols[ColIdx2].isActive()) { 858 if (ActiveCols[ColIdx2].MustDrawLabel && 859 !ActiveCols[ColIdx2].LiveIn) 860 OS << getLineChar(LineChar::LabelVert) << " "; 861 else 862 OS << getLineChar(LineChar::RangeMid) << " "; 863 } else 864 OS << " "; 865 } 866 867 // Then print the variable name and location of the new live range, 868 // with box drawing characters joining it to the live range line. 869 OS << getLineChar(ActiveCols[ColIdx].LiveIn 870 ? LineChar::LabelCornerActive 871 : LineChar::LabelCornerNew) 872 << getLineChar(LineChar::LabelHoriz) << " "; 873 WithColor(OS, raw_ostream::GREEN) 874 << LiveVariables[ActiveCols[ColIdx].VarIdx].VarName; 875 OS << " = "; 876 { 877 WithColor ExprColor(OS, raw_ostream::CYAN); 878 LiveVariables[ActiveCols[ColIdx].VarIdx].print(OS, MRI); 879 } 880 881 // If there are any columns to the right of the expression we just 882 // printed, then continue their live range lines. 883 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS); 884 for (unsigned ColIdx2 = FirstUnprintedColumn, End = ActiveCols.size(); 885 ColIdx2 < End; ++ColIdx2) { 886 if (ActiveCols[ColIdx2].isActive() && ActiveCols[ColIdx2].LiveIn) 887 OS << getLineChar(LineChar::RangeMid) << " "; 888 else 889 OS << " "; 890 } 891 892 OS << "\n"; 893 PrintedSomething = true; 894 } 895 } 896 897 for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx) 898 if (ActiveCols[ColIdx].isActive()) 899 ActiveCols[ColIdx].MustDrawLabel = false; 900 901 // If we must print something (because we printed a line/column number), 902 // but don't have any new variables to print, then print a line which 903 // just continues any existing live ranges. 904 if (MustPrint && !PrintedSomething) 905 printAfterOtherLine(OS, false); 906 } 907 908 /// Print the live variable ranges to the right of a disassembled instruction. 909 void printAfterInst(formatted_raw_ostream &OS) { 910 if (!ActiveCols.size()) 911 return; 912 unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS); 913 for (unsigned ColIdx = FirstUnprintedColumn, End = ActiveCols.size(); 914 ColIdx < End; ++ColIdx) { 915 if (!ActiveCols[ColIdx].isActive()) 916 OS << " "; 917 else if (ActiveCols[ColIdx].LiveIn && ActiveCols[ColIdx].LiveOut) 918 OS << getLineChar(LineChar::RangeMid) << " "; 919 else if (ActiveCols[ColIdx].LiveOut) 920 OS << getLineChar(LineChar::RangeStart) << " "; 921 else if (ActiveCols[ColIdx].LiveIn) 922 OS << getLineChar(LineChar::RangeEnd) << " "; 923 else 924 llvm_unreachable("var must be live in or out!"); 925 } 926 } 927 }; 928 929 class SourcePrinter { 930 protected: 931 DILineInfo OldLineInfo; 932 const ObjectFile *Obj = nullptr; 933 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer; 934 // File name to file contents of source. 935 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache; 936 // Mark the line endings of the cached source. 937 std::unordered_map<std::string, std::vector<StringRef>> LineCache; 938 // Keep track of missing sources. 939 StringSet<> MissingSources; 940 // Only emit 'no debug info' warning once. 941 bool WarnedNoDebugInfo; 942 943 private: 944 bool cacheSource(const DILineInfo& LineInfoFile); 945 946 void printLines(formatted_raw_ostream &OS, const DILineInfo &LineInfo, 947 StringRef Delimiter, LiveVariablePrinter &LVP); 948 949 void printSources(formatted_raw_ostream &OS, const DILineInfo &LineInfo, 950 StringRef ObjectFilename, StringRef Delimiter, 951 LiveVariablePrinter &LVP); 952 953 public: 954 SourcePrinter() = default; 955 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) 956 : Obj(Obj), WarnedNoDebugInfo(false) { 957 symbolize::LLVMSymbolizer::Options SymbolizerOpts; 958 SymbolizerOpts.PrintFunctions = 959 DILineInfoSpecifier::FunctionNameKind::LinkageName; 960 SymbolizerOpts.Demangle = Demangle; 961 SymbolizerOpts.DefaultArch = std::string(DefaultArch); 962 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts)); 963 } 964 virtual ~SourcePrinter() = default; 965 virtual void printSourceLine(formatted_raw_ostream &OS, 966 object::SectionedAddress Address, 967 StringRef ObjectFilename, 968 LiveVariablePrinter &LVP, 969 StringRef Delimiter = "; "); 970 }; 971 972 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) { 973 std::unique_ptr<MemoryBuffer> Buffer; 974 if (LineInfo.Source) { 975 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source); 976 } else { 977 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName); 978 if (!BufferOrError) { 979 if (MissingSources.insert(LineInfo.FileName).second) 980 reportWarning("failed to find source " + LineInfo.FileName, 981 Obj->getFileName()); 982 return false; 983 } 984 Buffer = std::move(*BufferOrError); 985 } 986 // Chomp the file to get lines 987 const char *BufferStart = Buffer->getBufferStart(), 988 *BufferEnd = Buffer->getBufferEnd(); 989 std::vector<StringRef> &Lines = LineCache[LineInfo.FileName]; 990 const char *Start = BufferStart; 991 for (const char *I = BufferStart; I != BufferEnd; ++I) 992 if (*I == '\n') { 993 Lines.emplace_back(Start, I - Start - (BufferStart < I && I[-1] == '\r')); 994 Start = I + 1; 995 } 996 if (Start < BufferEnd) 997 Lines.emplace_back(Start, BufferEnd - Start); 998 SourceCache[LineInfo.FileName] = std::move(Buffer); 999 return true; 1000 } 1001 1002 void SourcePrinter::printSourceLine(formatted_raw_ostream &OS, 1003 object::SectionedAddress Address, 1004 StringRef ObjectFilename, 1005 LiveVariablePrinter &LVP, 1006 StringRef Delimiter) { 1007 if (!Symbolizer) 1008 return; 1009 1010 DILineInfo LineInfo = DILineInfo(); 1011 auto ExpectedLineInfo = Symbolizer->symbolizeCode(*Obj, Address); 1012 std::string ErrorMessage; 1013 if (!ExpectedLineInfo) 1014 ErrorMessage = toString(ExpectedLineInfo.takeError()); 1015 else 1016 LineInfo = *ExpectedLineInfo; 1017 1018 if (LineInfo.FileName == DILineInfo::BadString) { 1019 if (!WarnedNoDebugInfo) { 1020 std::string Warning = 1021 "failed to parse debug information for " + ObjectFilename.str(); 1022 if (!ErrorMessage.empty()) 1023 Warning += ": " + ErrorMessage; 1024 reportWarning(Warning, ObjectFilename); 1025 WarnedNoDebugInfo = true; 1026 } 1027 } 1028 1029 if (PrintLines) 1030 printLines(OS, LineInfo, Delimiter, LVP); 1031 if (PrintSource) 1032 printSources(OS, LineInfo, ObjectFilename, Delimiter, LVP); 1033 OldLineInfo = LineInfo; 1034 } 1035 1036 void SourcePrinter::printLines(formatted_raw_ostream &OS, 1037 const DILineInfo &LineInfo, StringRef Delimiter, 1038 LiveVariablePrinter &LVP) { 1039 bool PrintFunctionName = LineInfo.FunctionName != DILineInfo::BadString && 1040 LineInfo.FunctionName != OldLineInfo.FunctionName; 1041 if (PrintFunctionName) { 1042 OS << Delimiter << LineInfo.FunctionName; 1043 // If demangling is successful, FunctionName will end with "()". Print it 1044 // only if demangling did not run or was unsuccessful. 1045 if (!StringRef(LineInfo.FunctionName).endswith("()")) 1046 OS << "()"; 1047 OS << ":\n"; 1048 } 1049 if (LineInfo.FileName != DILineInfo::BadString && LineInfo.Line != 0 && 1050 (OldLineInfo.Line != LineInfo.Line || 1051 OldLineInfo.FileName != LineInfo.FileName || PrintFunctionName)) { 1052 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line; 1053 LVP.printBetweenInsts(OS, true); 1054 } 1055 } 1056 1057 void SourcePrinter::printSources(formatted_raw_ostream &OS, 1058 const DILineInfo &LineInfo, 1059 StringRef ObjectFilename, StringRef Delimiter, 1060 LiveVariablePrinter &LVP) { 1061 if (LineInfo.FileName == DILineInfo::BadString || LineInfo.Line == 0 || 1062 (OldLineInfo.Line == LineInfo.Line && 1063 OldLineInfo.FileName == LineInfo.FileName)) 1064 return; 1065 1066 if (SourceCache.find(LineInfo.FileName) == SourceCache.end()) 1067 if (!cacheSource(LineInfo)) 1068 return; 1069 auto LineBuffer = LineCache.find(LineInfo.FileName); 1070 if (LineBuffer != LineCache.end()) { 1071 if (LineInfo.Line > LineBuffer->second.size()) { 1072 reportWarning( 1073 formatv( 1074 "debug info line number {0} exceeds the number of lines in {1}", 1075 LineInfo.Line, LineInfo.FileName), 1076 ObjectFilename); 1077 return; 1078 } 1079 // Vector begins at 0, line numbers are non-zero 1080 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1]; 1081 LVP.printBetweenInsts(OS, true); 1082 } 1083 } 1084 1085 static bool isAArch64Elf(const ObjectFile *Obj) { 1086 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); 1087 return Elf && Elf->getEMachine() == ELF::EM_AARCH64; 1088 } 1089 1090 static bool isArmElf(const ObjectFile *Obj) { 1091 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); 1092 return Elf && Elf->getEMachine() == ELF::EM_ARM; 1093 } 1094 1095 static bool hasMappingSymbols(const ObjectFile *Obj) { 1096 return isArmElf(Obj) || isAArch64Elf(Obj); 1097 } 1098 1099 static void printRelocation(formatted_raw_ostream &OS, StringRef FileName, 1100 const RelocationRef &Rel, uint64_t Address, 1101 bool Is64Bits) { 1102 StringRef Fmt = Is64Bits ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": "; 1103 SmallString<16> Name; 1104 SmallString<32> Val; 1105 Rel.getTypeName(Name); 1106 if (Error E = getRelocationValueString(Rel, Val)) 1107 reportError(std::move(E), FileName); 1108 OS << format(Fmt.data(), Address) << Name << "\t" << Val; 1109 } 1110 1111 class PrettyPrinter { 1112 public: 1113 virtual ~PrettyPrinter() = default; 1114 virtual void 1115 printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 1116 object::SectionedAddress Address, formatted_raw_ostream &OS, 1117 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 1118 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 1119 LiveVariablePrinter &LVP) { 1120 if (SP && (PrintSource || PrintLines)) 1121 SP->printSourceLine(OS, Address, ObjectFilename, LVP); 1122 LVP.printBetweenInsts(OS, false); 1123 1124 size_t Start = OS.tell(); 1125 if (!NoLeadingAddr) 1126 OS << format("%8" PRIx64 ":", Address.Address); 1127 if (!NoShowRawInsn) { 1128 OS << ' '; 1129 dumpBytes(Bytes, OS); 1130 } 1131 1132 // The output of printInst starts with a tab. Print some spaces so that 1133 // the tab has 1 column and advances to the target tab stop. 1134 unsigned TabStop = getInstStartColumn(STI); 1135 unsigned Column = OS.tell() - Start; 1136 OS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8); 1137 1138 if (MI) { 1139 // See MCInstPrinter::printInst. On targets where a PC relative immediate 1140 // is relative to the next instruction and the length of a MCInst is 1141 // difficult to measure (x86), this is the address of the next 1142 // instruction. 1143 uint64_t Addr = 1144 Address.Address + (STI.getTargetTriple().isX86() ? Bytes.size() : 0); 1145 IP.printInst(MI, Addr, "", STI, OS); 1146 } else 1147 OS << "\t<unknown>"; 1148 } 1149 }; 1150 PrettyPrinter PrettyPrinterInst; 1151 1152 class HexagonPrettyPrinter : public PrettyPrinter { 1153 public: 1154 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address, 1155 formatted_raw_ostream &OS) { 1156 uint32_t opcode = 1157 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0]; 1158 if (!NoLeadingAddr) 1159 OS << format("%8" PRIx64 ":", Address); 1160 if (!NoShowRawInsn) { 1161 OS << "\t"; 1162 dumpBytes(Bytes.slice(0, 4), OS); 1163 OS << format("\t%08" PRIx32, opcode); 1164 } 1165 } 1166 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 1167 object::SectionedAddress Address, formatted_raw_ostream &OS, 1168 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 1169 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 1170 LiveVariablePrinter &LVP) override { 1171 if (SP && (PrintSource || PrintLines)) 1172 SP->printSourceLine(OS, Address, ObjectFilename, LVP, ""); 1173 if (!MI) { 1174 printLead(Bytes, Address.Address, OS); 1175 OS << " <unknown>"; 1176 return; 1177 } 1178 std::string Buffer; 1179 { 1180 raw_string_ostream TempStream(Buffer); 1181 IP.printInst(MI, Address.Address, "", STI, TempStream); 1182 } 1183 StringRef Contents(Buffer); 1184 // Split off bundle attributes 1185 auto PacketBundle = Contents.rsplit('\n'); 1186 // Split off first instruction from the rest 1187 auto HeadTail = PacketBundle.first.split('\n'); 1188 auto Preamble = " { "; 1189 auto Separator = ""; 1190 1191 // Hexagon's packets require relocations to be inline rather than 1192 // clustered at the end of the packet. 1193 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin(); 1194 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end(); 1195 auto PrintReloc = [&]() -> void { 1196 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) { 1197 if (RelCur->getOffset() == Address.Address) { 1198 printRelocation(OS, ObjectFilename, *RelCur, Address.Address, false); 1199 return; 1200 } 1201 ++RelCur; 1202 } 1203 }; 1204 1205 while (!HeadTail.first.empty()) { 1206 OS << Separator; 1207 Separator = "\n"; 1208 if (SP && (PrintSource || PrintLines)) 1209 SP->printSourceLine(OS, Address, ObjectFilename, LVP, ""); 1210 printLead(Bytes, Address.Address, OS); 1211 OS << Preamble; 1212 Preamble = " "; 1213 StringRef Inst; 1214 auto Duplex = HeadTail.first.split('\v'); 1215 if (!Duplex.second.empty()) { 1216 OS << Duplex.first; 1217 OS << "; "; 1218 Inst = Duplex.second; 1219 } 1220 else 1221 Inst = HeadTail.first; 1222 OS << Inst; 1223 HeadTail = HeadTail.second.split('\n'); 1224 if (HeadTail.first.empty()) 1225 OS << " } " << PacketBundle.second; 1226 PrintReloc(); 1227 Bytes = Bytes.slice(4); 1228 Address.Address += 4; 1229 } 1230 } 1231 }; 1232 HexagonPrettyPrinter HexagonPrettyPrinterInst; 1233 1234 class AMDGCNPrettyPrinter : public PrettyPrinter { 1235 public: 1236 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 1237 object::SectionedAddress Address, formatted_raw_ostream &OS, 1238 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 1239 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 1240 LiveVariablePrinter &LVP) override { 1241 if (SP && (PrintSource || PrintLines)) 1242 SP->printSourceLine(OS, Address, ObjectFilename, LVP); 1243 1244 if (MI) { 1245 SmallString<40> InstStr; 1246 raw_svector_ostream IS(InstStr); 1247 1248 IP.printInst(MI, Address.Address, "", STI, IS); 1249 1250 OS << left_justify(IS.str(), 60); 1251 } else { 1252 // an unrecognized encoding - this is probably data so represent it 1253 // using the .long directive, or .byte directive if fewer than 4 bytes 1254 // remaining 1255 if (Bytes.size() >= 4) { 1256 OS << format("\t.long 0x%08" PRIx32 " ", 1257 support::endian::read32<support::little>(Bytes.data())); 1258 OS.indent(42); 1259 } else { 1260 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]); 1261 for (unsigned int i = 1; i < Bytes.size(); i++) 1262 OS << format(", 0x%02" PRIx8, Bytes[i]); 1263 OS.indent(55 - (6 * Bytes.size())); 1264 } 1265 } 1266 1267 OS << format("// %012" PRIX64 ":", Address.Address); 1268 if (Bytes.size() >= 4) { 1269 // D should be casted to uint32_t here as it is passed by format to 1270 // snprintf as vararg. 1271 for (uint32_t D : makeArrayRef( 1272 reinterpret_cast<const support::little32_t *>(Bytes.data()), 1273 Bytes.size() / 4)) 1274 OS << format(" %08" PRIX32, D); 1275 } else { 1276 for (unsigned char B : Bytes) 1277 OS << format(" %02" PRIX8, B); 1278 } 1279 1280 if (!Annot.empty()) 1281 OS << " // " << Annot; 1282 } 1283 }; 1284 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst; 1285 1286 class BPFPrettyPrinter : public PrettyPrinter { 1287 public: 1288 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 1289 object::SectionedAddress Address, formatted_raw_ostream &OS, 1290 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 1291 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 1292 LiveVariablePrinter &LVP) override { 1293 if (SP && (PrintSource || PrintLines)) 1294 SP->printSourceLine(OS, Address, ObjectFilename, LVP); 1295 if (!NoLeadingAddr) 1296 OS << format("%8" PRId64 ":", Address.Address / 8); 1297 if (!NoShowRawInsn) { 1298 OS << "\t"; 1299 dumpBytes(Bytes, OS); 1300 } 1301 if (MI) 1302 IP.printInst(MI, Address.Address, "", STI, OS); 1303 else 1304 OS << "\t<unknown>"; 1305 } 1306 }; 1307 BPFPrettyPrinter BPFPrettyPrinterInst; 1308 1309 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { 1310 switch(Triple.getArch()) { 1311 default: 1312 return PrettyPrinterInst; 1313 case Triple::hexagon: 1314 return HexagonPrettyPrinterInst; 1315 case Triple::amdgcn: 1316 return AMDGCNPrettyPrinterInst; 1317 case Triple::bpfel: 1318 case Triple::bpfeb: 1319 return BPFPrettyPrinterInst; 1320 } 1321 } 1322 } 1323 1324 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) { 1325 assert(Obj->isELF()); 1326 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 1327 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1328 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 1329 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1330 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 1331 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1332 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 1333 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1334 llvm_unreachable("Unsupported binary format"); 1335 } 1336 1337 template <class ELFT> static void 1338 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj, 1339 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 1340 for (auto Symbol : Obj->getDynamicSymbolIterators()) { 1341 uint8_t SymbolType = Symbol.getELFType(); 1342 if (SymbolType == ELF::STT_SECTION) 1343 continue; 1344 1345 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj->getFileName()); 1346 // ELFSymbolRef::getAddress() returns size instead of value for common 1347 // symbols which is not desirable for disassembly output. Overriding. 1348 if (SymbolType == ELF::STT_COMMON) 1349 Address = Obj->getSymbol(Symbol.getRawDataRefImpl())->st_value; 1350 1351 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName()); 1352 if (Name.empty()) 1353 continue; 1354 1355 section_iterator SecI = 1356 unwrapOrError(Symbol.getSection(), Obj->getFileName()); 1357 if (SecI == Obj->section_end()) 1358 continue; 1359 1360 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType); 1361 } 1362 } 1363 1364 static void 1365 addDynamicElfSymbols(const ObjectFile *Obj, 1366 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 1367 assert(Obj->isELF()); 1368 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 1369 addDynamicElfSymbols(Elf32LEObj, AllSymbols); 1370 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 1371 addDynamicElfSymbols(Elf64LEObj, AllSymbols); 1372 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 1373 addDynamicElfSymbols(Elf32BEObj, AllSymbols); 1374 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 1375 addDynamicElfSymbols(Elf64BEObj, AllSymbols); 1376 else 1377 llvm_unreachable("Unsupported binary format"); 1378 } 1379 1380 static void addPltEntries(const ObjectFile *Obj, 1381 std::map<SectionRef, SectionSymbolsTy> &AllSymbols, 1382 StringSaver &Saver) { 1383 Optional<SectionRef> Plt = None; 1384 for (const SectionRef &Section : Obj->sections()) { 1385 Expected<StringRef> SecNameOrErr = Section.getName(); 1386 if (!SecNameOrErr) { 1387 consumeError(SecNameOrErr.takeError()); 1388 continue; 1389 } 1390 if (*SecNameOrErr == ".plt") 1391 Plt = Section; 1392 } 1393 if (!Plt) 1394 return; 1395 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) { 1396 for (auto PltEntry : ElfObj->getPltAddresses()) { 1397 if (PltEntry.first) { 1398 SymbolRef Symbol(*PltEntry.first, ElfObj); 1399 uint8_t SymbolType = getElfSymbolType(Obj, Symbol); 1400 if (Expected<StringRef> NameOrErr = Symbol.getName()) { 1401 if (!NameOrErr->empty()) 1402 AllSymbols[*Plt].emplace_back( 1403 PltEntry.second, Saver.save((*NameOrErr + "@plt").str()), 1404 SymbolType); 1405 continue; 1406 } else { 1407 // The warning has been reported in disassembleObject(). 1408 consumeError(NameOrErr.takeError()); 1409 } 1410 } 1411 reportWarning("PLT entry at 0x" + Twine::utohexstr(PltEntry.second) + 1412 " references an invalid symbol", 1413 Obj->getFileName()); 1414 } 1415 } 1416 } 1417 1418 // Normally the disassembly output will skip blocks of zeroes. This function 1419 // returns the number of zero bytes that can be skipped when dumping the 1420 // disassembly of the instructions in Buf. 1421 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) { 1422 // Find the number of leading zeroes. 1423 size_t N = 0; 1424 while (N < Buf.size() && !Buf[N]) 1425 ++N; 1426 1427 // We may want to skip blocks of zero bytes, but unless we see 1428 // at least 8 of them in a row. 1429 if (N < 8) 1430 return 0; 1431 1432 // We skip zeroes in multiples of 4 because do not want to truncate an 1433 // instruction if it starts with a zero byte. 1434 return N & ~0x3; 1435 } 1436 1437 // Returns a map from sections to their relocations. 1438 static std::map<SectionRef, std::vector<RelocationRef>> 1439 getRelocsMap(object::ObjectFile const &Obj) { 1440 std::map<SectionRef, std::vector<RelocationRef>> Ret; 1441 uint64_t I = (uint64_t)-1; 1442 for (SectionRef Sec : Obj.sections()) { 1443 ++I; 1444 Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection(); 1445 if (!RelocatedOrErr) 1446 reportError(Obj.getFileName(), 1447 "section (" + Twine(I) + 1448 "): failed to get a relocated section: " + 1449 toString(RelocatedOrErr.takeError())); 1450 1451 section_iterator Relocated = *RelocatedOrErr; 1452 if (Relocated == Obj.section_end() || !checkSectionFilter(*Relocated).Keep) 1453 continue; 1454 std::vector<RelocationRef> &V = Ret[*Relocated]; 1455 for (const RelocationRef &R : Sec.relocations()) 1456 V.push_back(R); 1457 // Sort relocations by address. 1458 llvm::stable_sort(V, isRelocAddressLess); 1459 } 1460 return Ret; 1461 } 1462 1463 // Used for --adjust-vma to check if address should be adjusted by the 1464 // specified value for a given section. 1465 // For ELF we do not adjust non-allocatable sections like debug ones, 1466 // because they are not loadable. 1467 // TODO: implement for other file formats. 1468 static bool shouldAdjustVA(const SectionRef &Section) { 1469 const ObjectFile *Obj = Section.getObject(); 1470 if (Obj->isELF()) 1471 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC; 1472 return false; 1473 } 1474 1475 1476 typedef std::pair<uint64_t, char> MappingSymbolPair; 1477 static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols, 1478 uint64_t Address) { 1479 auto It = 1480 partition_point(MappingSymbols, [Address](const MappingSymbolPair &Val) { 1481 return Val.first <= Address; 1482 }); 1483 // Return zero for any address before the first mapping symbol; this means 1484 // we should use the default disassembly mode, depending on the target. 1485 if (It == MappingSymbols.begin()) 1486 return '\x00'; 1487 return (It - 1)->second; 1488 } 1489 1490 static uint64_t dumpARMELFData(uint64_t SectionAddr, uint64_t Index, 1491 uint64_t End, const ObjectFile *Obj, 1492 ArrayRef<uint8_t> Bytes, 1493 ArrayRef<MappingSymbolPair> MappingSymbols, 1494 raw_ostream &OS) { 1495 support::endianness Endian = 1496 Obj->isLittleEndian() ? support::little : support::big; 1497 OS << format("%8" PRIx64 ":\t", SectionAddr + Index); 1498 if (Index + 4 <= End) { 1499 dumpBytes(Bytes.slice(Index, 4), OS); 1500 OS << "\t.word\t" 1501 << format_hex(support::endian::read32(Bytes.data() + Index, Endian), 1502 10); 1503 return 4; 1504 } 1505 if (Index + 2 <= End) { 1506 dumpBytes(Bytes.slice(Index, 2), OS); 1507 OS << "\t\t.short\t" 1508 << format_hex(support::endian::read16(Bytes.data() + Index, Endian), 1509 6); 1510 return 2; 1511 } 1512 dumpBytes(Bytes.slice(Index, 1), OS); 1513 OS << "\t\t.byte\t" << format_hex(Bytes[0], 4); 1514 return 1; 1515 } 1516 1517 static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End, 1518 ArrayRef<uint8_t> Bytes) { 1519 // print out data up to 8 bytes at a time in hex and ascii 1520 uint8_t AsciiData[9] = {'\0'}; 1521 uint8_t Byte; 1522 int NumBytes = 0; 1523 1524 for (; Index < End; ++Index) { 1525 if (NumBytes == 0) 1526 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1527 Byte = Bytes.slice(Index)[0]; 1528 outs() << format(" %02x", Byte); 1529 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.'; 1530 1531 uint8_t IndentOffset = 0; 1532 NumBytes++; 1533 if (Index == End - 1 || NumBytes > 8) { 1534 // Indent the space for less than 8 bytes data. 1535 // 2 spaces for byte and one for space between bytes 1536 IndentOffset = 3 * (8 - NumBytes); 1537 for (int Excess = NumBytes; Excess < 8; Excess++) 1538 AsciiData[Excess] = '\0'; 1539 NumBytes = 8; 1540 } 1541 if (NumBytes == 8) { 1542 AsciiData[8] = '\0'; 1543 outs() << std::string(IndentOffset, ' ') << " "; 1544 outs() << reinterpret_cast<char *>(AsciiData); 1545 outs() << '\n'; 1546 NumBytes = 0; 1547 } 1548 } 1549 } 1550 1551 SymbolInfoTy objdump::createSymbolInfo(const ObjectFile *Obj, 1552 const SymbolRef &Symbol) { 1553 const StringRef FileName = Obj->getFileName(); 1554 const uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName); 1555 const StringRef Name = unwrapOrError(Symbol.getName(), FileName); 1556 1557 if (Obj->isXCOFF() && SymbolDescription) { 1558 const auto *XCOFFObj = cast<XCOFFObjectFile>(Obj); 1559 DataRefImpl SymbolDRI = Symbol.getRawDataRefImpl(); 1560 1561 const uint32_t SymbolIndex = XCOFFObj->getSymbolIndex(SymbolDRI.p); 1562 Optional<XCOFF::StorageMappingClass> Smc = 1563 getXCOFFSymbolCsectSMC(XCOFFObj, Symbol); 1564 return SymbolInfoTy(Addr, Name, Smc, SymbolIndex, 1565 isLabel(XCOFFObj, Symbol)); 1566 } else 1567 return SymbolInfoTy(Addr, Name, 1568 Obj->isELF() ? getElfSymbolType(Obj, Symbol) 1569 : (uint8_t)ELF::STT_NOTYPE); 1570 } 1571 1572 static SymbolInfoTy createDummySymbolInfo(const ObjectFile *Obj, 1573 const uint64_t Addr, StringRef &Name, 1574 uint8_t Type) { 1575 if (Obj->isXCOFF() && SymbolDescription) 1576 return SymbolInfoTy(Addr, Name, None, None, false); 1577 else 1578 return SymbolInfoTy(Addr, Name, Type); 1579 } 1580 1581 static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj, 1582 MCContext &Ctx, MCDisassembler *PrimaryDisAsm, 1583 MCDisassembler *SecondaryDisAsm, 1584 const MCInstrAnalysis *MIA, MCInstPrinter *IP, 1585 const MCSubtargetInfo *PrimarySTI, 1586 const MCSubtargetInfo *SecondarySTI, 1587 PrettyPrinter &PIP, 1588 SourcePrinter &SP, bool InlineRelocs) { 1589 const MCSubtargetInfo *STI = PrimarySTI; 1590 MCDisassembler *DisAsm = PrimaryDisAsm; 1591 bool PrimaryIsThumb = false; 1592 if (isArmElf(Obj)) 1593 PrimaryIsThumb = STI->checkFeatures("+thumb-mode"); 1594 1595 std::map<SectionRef, std::vector<RelocationRef>> RelocMap; 1596 if (InlineRelocs) 1597 RelocMap = getRelocsMap(*Obj); 1598 bool Is64Bits = Obj->getBytesInAddress() > 4; 1599 1600 // Create a mapping from virtual address to symbol name. This is used to 1601 // pretty print the symbols while disassembling. 1602 std::map<SectionRef, SectionSymbolsTy> AllSymbols; 1603 SectionSymbolsTy AbsoluteSymbols; 1604 const StringRef FileName = Obj->getFileName(); 1605 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj); 1606 for (const SymbolRef &Symbol : Obj->symbols()) { 1607 Expected<StringRef> NameOrErr = Symbol.getName(); 1608 if (!NameOrErr) { 1609 reportWarning(toString(NameOrErr.takeError()), FileName); 1610 continue; 1611 } 1612 if (NameOrErr->empty() && !(Obj->isXCOFF() && SymbolDescription)) 1613 continue; 1614 1615 if (Obj->isELF() && getElfSymbolType(Obj, Symbol) == ELF::STT_SECTION) 1616 continue; 1617 1618 // Don't ask a Mach-O STAB symbol for its section unless you know that 1619 // STAB symbol's section field refers to a valid section index. Otherwise 1620 // the symbol may error trying to load a section that does not exist. 1621 if (MachO) { 1622 DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); 1623 uint8_t NType = (MachO->is64Bit() ? 1624 MachO->getSymbol64TableEntry(SymDRI).n_type: 1625 MachO->getSymbolTableEntry(SymDRI).n_type); 1626 if (NType & MachO::N_STAB) 1627 continue; 1628 } 1629 1630 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName); 1631 if (SecI != Obj->section_end()) 1632 AllSymbols[*SecI].push_back(createSymbolInfo(Obj, Symbol)); 1633 else 1634 AbsoluteSymbols.push_back(createSymbolInfo(Obj, Symbol)); 1635 } 1636 1637 if (AllSymbols.empty() && Obj->isELF()) 1638 addDynamicElfSymbols(Obj, AllSymbols); 1639 1640 BumpPtrAllocator A; 1641 StringSaver Saver(A); 1642 addPltEntries(Obj, AllSymbols, Saver); 1643 1644 // Create a mapping from virtual address to section. An empty section can 1645 // cause more than one section at the same address. Sort such sections to be 1646 // before same-addressed non-empty sections so that symbol lookups prefer the 1647 // non-empty section. 1648 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 1649 for (SectionRef Sec : Obj->sections()) 1650 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 1651 llvm::stable_sort(SectionAddresses, [](const auto &LHS, const auto &RHS) { 1652 if (LHS.first != RHS.first) 1653 return LHS.first < RHS.first; 1654 return LHS.second.getSize() < RHS.second.getSize(); 1655 }); 1656 1657 // Linked executables (.exe and .dll files) typically don't include a real 1658 // symbol table but they might contain an export table. 1659 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 1660 for (const auto &ExportEntry : COFFObj->export_directories()) { 1661 StringRef Name; 1662 if (Error E = ExportEntry.getSymbolName(Name)) 1663 reportError(std::move(E), Obj->getFileName()); 1664 if (Name.empty()) 1665 continue; 1666 1667 uint32_t RVA; 1668 if (Error E = ExportEntry.getExportRVA(RVA)) 1669 reportError(std::move(E), Obj->getFileName()); 1670 1671 uint64_t VA = COFFObj->getImageBase() + RVA; 1672 auto Sec = partition_point( 1673 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) { 1674 return O.first <= VA; 1675 }); 1676 if (Sec != SectionAddresses.begin()) { 1677 --Sec; 1678 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 1679 } else 1680 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE); 1681 } 1682 } 1683 1684 // Sort all the symbols, this allows us to use a simple binary search to find 1685 // Multiple symbols can have the same address. Use a stable sort to stabilize 1686 // the output. 1687 StringSet<> FoundDisasmSymbolSet; 1688 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1689 stable_sort(SecSyms.second); 1690 stable_sort(AbsoluteSymbols); 1691 1692 std::unique_ptr<DWARFContext> DICtx; 1693 LiveVariablePrinter LVP(*Ctx.getRegisterInfo(), *STI); 1694 1695 if (DbgVariables != DVDisabled) { 1696 DICtx = DWARFContext::create(*Obj); 1697 for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units()) 1698 LVP.addCompileUnit(CU->getUnitDIE(false)); 1699 } 1700 1701 LLVM_DEBUG(LVP.dump()); 1702 1703 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1704 if (FilterSections.empty() && !DisassembleAll && 1705 (!Section.isText() || Section.isVirtual())) 1706 continue; 1707 1708 uint64_t SectionAddr = Section.getAddress(); 1709 uint64_t SectSize = Section.getSize(); 1710 if (!SectSize) 1711 continue; 1712 1713 // Get the list of all the symbols in this section. 1714 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1715 std::vector<MappingSymbolPair> MappingSymbols; 1716 if (hasMappingSymbols(Obj)) { 1717 for (const auto &Symb : Symbols) { 1718 uint64_t Address = Symb.Addr; 1719 StringRef Name = Symb.Name; 1720 if (Name.startswith("$d")) 1721 MappingSymbols.emplace_back(Address - SectionAddr, 'd'); 1722 if (Name.startswith("$x")) 1723 MappingSymbols.emplace_back(Address - SectionAddr, 'x'); 1724 if (Name.startswith("$a")) 1725 MappingSymbols.emplace_back(Address - SectionAddr, 'a'); 1726 if (Name.startswith("$t")) 1727 MappingSymbols.emplace_back(Address - SectionAddr, 't'); 1728 } 1729 } 1730 1731 llvm::sort(MappingSymbols); 1732 1733 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1734 // AMDGPU disassembler uses symbolizer for printing labels 1735 std::unique_ptr<MCRelocationInfo> RelInfo( 1736 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 1737 if (RelInfo) { 1738 std::unique_ptr<MCSymbolizer> Symbolizer( 1739 TheTarget->createMCSymbolizer( 1740 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1741 DisAsm->setSymbolizer(std::move(Symbolizer)); 1742 } 1743 } 1744 1745 StringRef SegmentName = ""; 1746 if (MachO) { 1747 DataRefImpl DR = Section.getRawDataRefImpl(); 1748 SegmentName = MachO->getSectionFinalSegmentName(DR); 1749 } 1750 1751 StringRef SectionName = unwrapOrError(Section.getName(), Obj->getFileName()); 1752 // If the section has no symbol at the start, just insert a dummy one. 1753 if (Symbols.empty() || Symbols[0].Addr != 0) { 1754 Symbols.insert(Symbols.begin(), 1755 createDummySymbolInfo(Obj, SectionAddr, SectionName, 1756 Section.isText() ? ELF::STT_FUNC 1757 : ELF::STT_OBJECT)); 1758 } 1759 1760 SmallString<40> Comments; 1761 raw_svector_ostream CommentStream(Comments); 1762 1763 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef( 1764 unwrapOrError(Section.getContents(), Obj->getFileName())); 1765 1766 uint64_t VMAAdjustment = 0; 1767 if (shouldAdjustVA(Section)) 1768 VMAAdjustment = AdjustVMA; 1769 1770 uint64_t Size; 1771 uint64_t Index; 1772 bool PrintedSection = false; 1773 std::vector<RelocationRef> Rels = RelocMap[Section]; 1774 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); 1775 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end(); 1776 // Disassemble symbol by symbol. 1777 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) { 1778 std::string SymbolName = Symbols[SI].Name.str(); 1779 if (Demangle) 1780 SymbolName = demangle(SymbolName); 1781 1782 // Skip if --disassemble-symbols is not empty and the symbol is not in 1783 // the list. 1784 if (!DisasmSymbolSet.empty() && !DisasmSymbolSet.count(SymbolName)) 1785 continue; 1786 1787 uint64_t Start = Symbols[SI].Addr; 1788 if (Start < SectionAddr || StopAddress <= Start) 1789 continue; 1790 else 1791 FoundDisasmSymbolSet.insert(SymbolName); 1792 1793 // The end is the section end, the beginning of the next symbol, or 1794 // --stop-address. 1795 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress); 1796 if (SI + 1 < SE) 1797 End = std::min(End, Symbols[SI + 1].Addr); 1798 if (Start >= End || End <= StartAddress) 1799 continue; 1800 Start -= SectionAddr; 1801 End -= SectionAddr; 1802 1803 if (!PrintedSection) { 1804 PrintedSection = true; 1805 outs() << "\nDisassembly of section "; 1806 if (!SegmentName.empty()) 1807 outs() << SegmentName << ","; 1808 outs() << SectionName << ":\n"; 1809 } 1810 1811 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1812 if (Symbols[SI].Type == ELF::STT_AMDGPU_HSA_KERNEL) { 1813 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes) 1814 Start += 256; 1815 } 1816 if (SI == SE - 1 || 1817 Symbols[SI + 1].Type == ELF::STT_AMDGPU_HSA_KERNEL) { 1818 // cut trailing zeroes at the end of kernel 1819 // cut up to 256 bytes 1820 const uint64_t EndAlign = 256; 1821 const auto Limit = End - (std::min)(EndAlign, End - Start); 1822 while (End > Limit && 1823 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0) 1824 End -= 4; 1825 } 1826 } 1827 1828 outs() << '\n'; 1829 if (!NoLeadingAddr) 1830 outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ", 1831 SectionAddr + Start + VMAAdjustment); 1832 if (Obj->isXCOFF() && SymbolDescription) { 1833 outs() << getXCOFFSymbolDescription(Symbols[SI], SymbolName) << ":\n"; 1834 } else 1835 outs() << '<' << SymbolName << ">:\n"; 1836 1837 // Don't print raw contents of a virtual section. A virtual section 1838 // doesn't have any contents in the file. 1839 if (Section.isVirtual()) { 1840 outs() << "...\n"; 1841 continue; 1842 } 1843 1844 auto Status = DisAsm->onSymbolStart(Symbols[SI], Size, 1845 Bytes.slice(Start, End - Start), 1846 SectionAddr + Start, CommentStream); 1847 // To have round trippable disassembly, we fall back to decoding the 1848 // remaining bytes as instructions. 1849 // 1850 // If there is a failure, we disassemble the failed region as bytes before 1851 // falling back. The target is expected to print nothing in this case. 1852 // 1853 // If there is Success or SoftFail i.e no 'real' failure, we go ahead by 1854 // Size bytes before falling back. 1855 // So if the entire symbol is 'eaten' by the target: 1856 // Start += Size // Now Start = End and we will never decode as 1857 // // instructions 1858 // 1859 // Right now, most targets return None i.e ignore to treat a symbol 1860 // separately. But WebAssembly decodes preludes for some symbols. 1861 // 1862 if (Status.hasValue()) { 1863 if (Status.getValue() == MCDisassembler::Fail) { 1864 outs() << "// Error in decoding " << SymbolName 1865 << " : Decoding failed region as bytes.\n"; 1866 for (uint64_t I = 0; I < Size; ++I) { 1867 outs() << "\t.byte\t " << format_hex(Bytes[I], 1, /*Upper=*/true) 1868 << "\n"; 1869 } 1870 } 1871 } else { 1872 Size = 0; 1873 } 1874 1875 Start += Size; 1876 1877 Index = Start; 1878 if (SectionAddr < StartAddress) 1879 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr); 1880 1881 // If there is a data/common symbol inside an ELF text section and we are 1882 // only disassembling text (applicable all architectures), we are in a 1883 // situation where we must print the data and not disassemble it. 1884 if (Obj->isELF() && !DisassembleAll && Section.isText()) { 1885 uint8_t SymTy = Symbols[SI].Type; 1886 if (SymTy == ELF::STT_OBJECT || SymTy == ELF::STT_COMMON) { 1887 dumpELFData(SectionAddr, Index, End, Bytes); 1888 Index = End; 1889 } 1890 } 1891 1892 bool CheckARMELFData = hasMappingSymbols(Obj) && 1893 Symbols[SI].Type != ELF::STT_OBJECT && 1894 !DisassembleAll; 1895 bool DumpARMELFData = false; 1896 formatted_raw_ostream FOS(outs()); 1897 while (Index < End) { 1898 // ARM and AArch64 ELF binaries can interleave data and text in the 1899 // same section. We rely on the markers introduced to understand what 1900 // we need to dump. If the data marker is within a function, it is 1901 // denoted as a word/short etc. 1902 if (CheckARMELFData) { 1903 char Kind = getMappingSymbolKind(MappingSymbols, Index); 1904 DumpARMELFData = Kind == 'd'; 1905 if (SecondarySTI) { 1906 if (Kind == 'a') { 1907 STI = PrimaryIsThumb ? SecondarySTI : PrimarySTI; 1908 DisAsm = PrimaryIsThumb ? SecondaryDisAsm : PrimaryDisAsm; 1909 } else if (Kind == 't') { 1910 STI = PrimaryIsThumb ? PrimarySTI : SecondarySTI; 1911 DisAsm = PrimaryIsThumb ? PrimaryDisAsm : SecondaryDisAsm; 1912 } 1913 } 1914 } 1915 1916 if (DumpARMELFData) { 1917 Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes, 1918 MappingSymbols, FOS); 1919 } else { 1920 // When -z or --disassemble-zeroes are given we always dissasemble 1921 // them. Otherwise we might want to skip zero bytes we see. 1922 if (!DisassembleZeroes) { 1923 uint64_t MaxOffset = End - Index; 1924 // For --reloc: print zero blocks patched by relocations, so that 1925 // relocations can be shown in the dump. 1926 if (RelCur != RelEnd) 1927 MaxOffset = RelCur->getOffset() - Index; 1928 1929 if (size_t N = 1930 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) { 1931 FOS << "\t\t..." << '\n'; 1932 Index += N; 1933 continue; 1934 } 1935 } 1936 1937 // Disassemble a real instruction or a data when disassemble all is 1938 // provided 1939 MCInst Inst; 1940 bool Disassembled = 1941 DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 1942 SectionAddr + Index, CommentStream); 1943 if (Size == 0) 1944 Size = 1; 1945 1946 LVP.update({Index, Section.getIndex()}, 1947 {Index + Size, Section.getIndex()}, Index + Size != End); 1948 1949 PIP.printInst( 1950 *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size), 1951 {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, FOS, 1952 "", *STI, &SP, Obj->getFileName(), &Rels, LVP); 1953 FOS << CommentStream.str(); 1954 Comments.clear(); 1955 1956 // If disassembly has failed, avoid analysing invalid/incomplete 1957 // instruction information. Otherwise, try to resolve the target 1958 // address (jump target or memory operand address) and print it on the 1959 // right of the instruction. 1960 if (Disassembled && MIA) { 1961 uint64_t Target; 1962 bool PrintTarget = 1963 MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target); 1964 if (!PrintTarget) 1965 if (Optional<uint64_t> MaybeTarget = 1966 MIA->evaluateMemoryOperandAddress( 1967 Inst, SectionAddr + Index, Size)) { 1968 Target = *MaybeTarget; 1969 PrintTarget = true; 1970 FOS << " # " << Twine::utohexstr(Target); 1971 } 1972 if (PrintTarget) { 1973 // In a relocatable object, the target's section must reside in 1974 // the same section as the call instruction or it is accessed 1975 // through a relocation. 1976 // 1977 // In a non-relocatable object, the target may be in any section. 1978 // In that case, locate the section(s) containing the target 1979 // address and find the symbol in one of those, if possible. 1980 // 1981 // N.B. We don't walk the relocations in the relocatable case yet. 1982 std::vector<const SectionSymbolsTy *> TargetSectionSymbols; 1983 if (!Obj->isRelocatableObject()) { 1984 auto It = llvm::partition_point( 1985 SectionAddresses, 1986 [=](const std::pair<uint64_t, SectionRef> &O) { 1987 return O.first <= Target; 1988 }); 1989 uint64_t TargetSecAddr = 0; 1990 while (It != SectionAddresses.begin()) { 1991 --It; 1992 if (TargetSecAddr == 0) 1993 TargetSecAddr = It->first; 1994 if (It->first != TargetSecAddr) 1995 break; 1996 TargetSectionSymbols.push_back(&AllSymbols[It->second]); 1997 } 1998 } else { 1999 TargetSectionSymbols.push_back(&Symbols); 2000 } 2001 TargetSectionSymbols.push_back(&AbsoluteSymbols); 2002 2003 // Find the last symbol in the first candidate section whose 2004 // offset is less than or equal to the target. If there are no 2005 // such symbols, try in the next section and so on, before finally 2006 // using the nearest preceding absolute symbol (if any), if there 2007 // are no other valid symbols. 2008 const SymbolInfoTy *TargetSym = nullptr; 2009 for (const SectionSymbolsTy *TargetSymbols : 2010 TargetSectionSymbols) { 2011 auto It = llvm::partition_point( 2012 *TargetSymbols, 2013 [=](const SymbolInfoTy &O) { return O.Addr <= Target; }); 2014 if (It != TargetSymbols->begin()) { 2015 TargetSym = &*(It - 1); 2016 break; 2017 } 2018 } 2019 2020 if (TargetSym != nullptr) { 2021 uint64_t TargetAddress = TargetSym->Addr; 2022 std::string TargetName = TargetSym->Name.str(); 2023 if (Demangle) 2024 TargetName = demangle(TargetName); 2025 2026 FOS << " <" << TargetName; 2027 uint64_t Disp = Target - TargetAddress; 2028 if (Disp) 2029 FOS << "+0x" << Twine::utohexstr(Disp); 2030 FOS << '>'; 2031 } 2032 } 2033 } 2034 } 2035 2036 LVP.printAfterInst(FOS); 2037 FOS << "\n"; 2038 2039 // Hexagon does this in pretty printer 2040 if (Obj->getArch() != Triple::hexagon) { 2041 // Print relocation for instruction and data. 2042 while (RelCur != RelEnd) { 2043 uint64_t Offset = RelCur->getOffset(); 2044 // If this relocation is hidden, skip it. 2045 if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) { 2046 ++RelCur; 2047 continue; 2048 } 2049 2050 // Stop when RelCur's offset is past the disassembled 2051 // instruction/data. Note that it's possible the disassembled data 2052 // is not the complete data: we might see the relocation printed in 2053 // the middle of the data, but this matches the binutils objdump 2054 // output. 2055 if (Offset >= Index + Size) 2056 break; 2057 2058 // When --adjust-vma is used, update the address printed. 2059 if (RelCur->getSymbol() != Obj->symbol_end()) { 2060 Expected<section_iterator> SymSI = 2061 RelCur->getSymbol()->getSection(); 2062 if (SymSI && *SymSI != Obj->section_end() && 2063 shouldAdjustVA(**SymSI)) 2064 Offset += AdjustVMA; 2065 } 2066 2067 printRelocation(FOS, Obj->getFileName(), *RelCur, 2068 SectionAddr + Offset, Is64Bits); 2069 LVP.printAfterOtherLine(FOS, true); 2070 ++RelCur; 2071 } 2072 } 2073 2074 Index += Size; 2075 } 2076 } 2077 } 2078 StringSet<> MissingDisasmSymbolSet = 2079 set_difference(DisasmSymbolSet, FoundDisasmSymbolSet); 2080 for (StringRef Sym : MissingDisasmSymbolSet.keys()) 2081 reportWarning("failed to disassemble missing symbol " + Sym, FileName); 2082 } 2083 2084 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 2085 const Target *TheTarget = getTarget(Obj); 2086 2087 // Package up features to be passed to target/subtarget 2088 SubtargetFeatures Features = Obj->getFeatures(); 2089 if (!MAttrs.empty()) 2090 for (unsigned I = 0; I != MAttrs.size(); ++I) 2091 Features.AddFeature(MAttrs[I]); 2092 2093 std::unique_ptr<const MCRegisterInfo> MRI( 2094 TheTarget->createMCRegInfo(TripleName)); 2095 if (!MRI) 2096 reportError(Obj->getFileName(), 2097 "no register info for target " + TripleName); 2098 2099 // Set up disassembler. 2100 MCTargetOptions MCOptions; 2101 std::unique_ptr<const MCAsmInfo> AsmInfo( 2102 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 2103 if (!AsmInfo) 2104 reportError(Obj->getFileName(), 2105 "no assembly info for target " + TripleName); 2106 std::unique_ptr<const MCSubtargetInfo> STI( 2107 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 2108 if (!STI) 2109 reportError(Obj->getFileName(), 2110 "no subtarget info for target " + TripleName); 2111 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 2112 if (!MII) 2113 reportError(Obj->getFileName(), 2114 "no instruction info for target " + TripleName); 2115 MCObjectFileInfo MOFI; 2116 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI); 2117 // FIXME: for now initialize MCObjectFileInfo with default values 2118 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx); 2119 2120 std::unique_ptr<MCDisassembler> DisAsm( 2121 TheTarget->createMCDisassembler(*STI, Ctx)); 2122 if (!DisAsm) 2123 reportError(Obj->getFileName(), "no disassembler for target " + TripleName); 2124 2125 // If we have an ARM object file, we need a second disassembler, because 2126 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode. 2127 // We use mapping symbols to switch between the two assemblers, where 2128 // appropriate. 2129 std::unique_ptr<MCDisassembler> SecondaryDisAsm; 2130 std::unique_ptr<const MCSubtargetInfo> SecondarySTI; 2131 if (isArmElf(Obj) && !STI->checkFeatures("+mclass")) { 2132 if (STI->checkFeatures("+thumb-mode")) 2133 Features.AddFeature("-thumb-mode"); 2134 else 2135 Features.AddFeature("+thumb-mode"); 2136 SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU, 2137 Features.getString())); 2138 SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx)); 2139 } 2140 2141 std::unique_ptr<const MCInstrAnalysis> MIA( 2142 TheTarget->createMCInstrAnalysis(MII.get())); 2143 2144 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 2145 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 2146 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 2147 if (!IP) 2148 reportError(Obj->getFileName(), 2149 "no instruction printer for target " + TripleName); 2150 IP->setPrintImmHex(PrintImmHex); 2151 IP->setPrintBranchImmAsAddress(true); 2152 2153 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 2154 SourcePrinter SP(Obj, TheTarget->getName()); 2155 2156 for (StringRef Opt : DisassemblerOptions) 2157 if (!IP->applyTargetSpecificCLOption(Opt)) 2158 reportError(Obj->getFileName(), 2159 "Unrecognized disassembler option: " + Opt); 2160 2161 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(), 2162 MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP, 2163 SP, InlineRelocs); 2164 } 2165 2166 void objdump::printRelocations(const ObjectFile *Obj) { 2167 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 2168 "%08" PRIx64; 2169 // Regular objdump doesn't print relocations in non-relocatable object 2170 // files. 2171 if (!Obj->isRelocatableObject()) 2172 return; 2173 2174 // Build a mapping from relocation target to a vector of relocation 2175 // sections. Usually, there is an only one relocation section for 2176 // each relocated section. 2177 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec; 2178 uint64_t Ndx; 2179 for (const SectionRef &Section : ToolSectionFilter(*Obj, &Ndx)) { 2180 if (Section.relocation_begin() == Section.relocation_end()) 2181 continue; 2182 Expected<section_iterator> SecOrErr = Section.getRelocatedSection(); 2183 if (!SecOrErr) 2184 reportError(Obj->getFileName(), 2185 "section (" + Twine(Ndx) + 2186 "): unable to get a relocation target: " + 2187 toString(SecOrErr.takeError())); 2188 SecToRelSec[**SecOrErr].push_back(Section); 2189 } 2190 2191 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) { 2192 StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName()); 2193 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n"; 2194 uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8); 2195 uint32_t TypePadding = 24; 2196 outs() << left_justify("OFFSET", OffsetPadding) << " " 2197 << left_justify("TYPE", TypePadding) << " " 2198 << "VALUE\n"; 2199 2200 for (SectionRef Section : P.second) { 2201 for (const RelocationRef &Reloc : Section.relocations()) { 2202 uint64_t Address = Reloc.getOffset(); 2203 SmallString<32> RelocName; 2204 SmallString<32> ValueStr; 2205 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc)) 2206 continue; 2207 Reloc.getTypeName(RelocName); 2208 if (Error E = getRelocationValueString(Reloc, ValueStr)) 2209 reportError(std::move(E), Obj->getFileName()); 2210 2211 outs() << format(Fmt.data(), Address) << " " 2212 << left_justify(RelocName, TypePadding) << " " << ValueStr 2213 << "\n"; 2214 } 2215 } 2216 outs() << "\n"; 2217 } 2218 } 2219 2220 void objdump::printDynamicRelocations(const ObjectFile *Obj) { 2221 // For the moment, this option is for ELF only 2222 if (!Obj->isELF()) 2223 return; 2224 2225 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); 2226 if (!Elf || Elf->getEType() != ELF::ET_DYN) { 2227 reportError(Obj->getFileName(), "not a dynamic object"); 2228 return; 2229 } 2230 2231 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections(); 2232 if (DynRelSec.empty()) 2233 return; 2234 2235 outs() << "DYNAMIC RELOCATION RECORDS\n"; 2236 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2237 for (const SectionRef &Section : DynRelSec) 2238 for (const RelocationRef &Reloc : Section.relocations()) { 2239 uint64_t Address = Reloc.getOffset(); 2240 SmallString<32> RelocName; 2241 SmallString<32> ValueStr; 2242 Reloc.getTypeName(RelocName); 2243 if (Error E = getRelocationValueString(Reloc, ValueStr)) 2244 reportError(std::move(E), Obj->getFileName()); 2245 outs() << format(Fmt.data(), Address) << " " << RelocName << " " 2246 << ValueStr << "\n"; 2247 } 2248 } 2249 2250 // Returns true if we need to show LMA column when dumping section headers. We 2251 // show it only when the platform is ELF and either we have at least one section 2252 // whose VMA and LMA are different and/or when --show-lma flag is used. 2253 static bool shouldDisplayLMA(const ObjectFile *Obj) { 2254 if (!Obj->isELF()) 2255 return false; 2256 for (const SectionRef &S : ToolSectionFilter(*Obj)) 2257 if (S.getAddress() != getELFSectionLMA(S)) 2258 return true; 2259 return ShowLMA; 2260 } 2261 2262 static size_t getMaxSectionNameWidth(const ObjectFile *Obj) { 2263 // Default column width for names is 13 even if no names are that long. 2264 size_t MaxWidth = 13; 2265 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 2266 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 2267 MaxWidth = std::max(MaxWidth, Name.size()); 2268 } 2269 return MaxWidth; 2270 } 2271 2272 void objdump::printSectionHeaders(const ObjectFile *Obj) { 2273 size_t NameWidth = getMaxSectionNameWidth(Obj); 2274 size_t AddressWidth = 2 * Obj->getBytesInAddress(); 2275 bool HasLMAColumn = shouldDisplayLMA(Obj); 2276 if (HasLMAColumn) 2277 outs() << "Sections:\n" 2278 "Idx " 2279 << left_justify("Name", NameWidth) << " Size " 2280 << left_justify("VMA", AddressWidth) << " " 2281 << left_justify("LMA", AddressWidth) << " Type\n"; 2282 else 2283 outs() << "Sections:\n" 2284 "Idx " 2285 << left_justify("Name", NameWidth) << " Size " 2286 << left_justify("VMA", AddressWidth) << " Type\n"; 2287 2288 uint64_t Idx; 2289 for (const SectionRef &Section : ToolSectionFilter(*Obj, &Idx)) { 2290 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 2291 uint64_t VMA = Section.getAddress(); 2292 if (shouldAdjustVA(Section)) 2293 VMA += AdjustVMA; 2294 2295 uint64_t Size = Section.getSize(); 2296 2297 std::string Type = Section.isText() ? "TEXT" : ""; 2298 if (Section.isData()) 2299 Type += Type.empty() ? "DATA" : " DATA"; 2300 if (Section.isBSS()) 2301 Type += Type.empty() ? "BSS" : " BSS"; 2302 2303 if (HasLMAColumn) 2304 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 2305 Name.str().c_str(), Size) 2306 << format_hex_no_prefix(VMA, AddressWidth) << " " 2307 << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth) 2308 << " " << Type << "\n"; 2309 else 2310 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 2311 Name.str().c_str(), Size) 2312 << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n"; 2313 } 2314 outs() << "\n"; 2315 } 2316 2317 void objdump::printSectionContents(const ObjectFile *Obj) { 2318 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 2319 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 2320 uint64_t BaseAddr = Section.getAddress(); 2321 uint64_t Size = Section.getSize(); 2322 if (!Size) 2323 continue; 2324 2325 outs() << "Contents of section " << Name << ":\n"; 2326 if (Section.isBSS()) { 2327 outs() << format("<skipping contents of bss section at [%04" PRIx64 2328 ", %04" PRIx64 ")>\n", 2329 BaseAddr, BaseAddr + Size); 2330 continue; 2331 } 2332 2333 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName()); 2334 2335 // Dump out the content as hex and printable ascii characters. 2336 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { 2337 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr); 2338 // Dump line of hex. 2339 for (std::size_t I = 0; I < 16; ++I) { 2340 if (I != 0 && I % 4 == 0) 2341 outs() << ' '; 2342 if (Addr + I < End) 2343 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true) 2344 << hexdigit(Contents[Addr + I] & 0xF, true); 2345 else 2346 outs() << " "; 2347 } 2348 // Print ascii. 2349 outs() << " "; 2350 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { 2351 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) 2352 outs() << Contents[Addr + I]; 2353 else 2354 outs() << "."; 2355 } 2356 outs() << "\n"; 2357 } 2358 } 2359 } 2360 2361 void objdump::printSymbolTable(const ObjectFile *O, StringRef ArchiveName, 2362 StringRef ArchitectureName, bool DumpDynamic) { 2363 if (O->isCOFF() && !DumpDynamic) { 2364 outs() << "SYMBOL TABLE:\n"; 2365 printCOFFSymbolTable(cast<const COFFObjectFile>(O)); 2366 return; 2367 } 2368 2369 const StringRef FileName = O->getFileName(); 2370 2371 if (!DumpDynamic) { 2372 outs() << "SYMBOL TABLE:\n"; 2373 for (auto I = O->symbol_begin(); I != O->symbol_end(); ++I) 2374 printSymbol(O, *I, FileName, ArchiveName, ArchitectureName, DumpDynamic); 2375 return; 2376 } 2377 2378 outs() << "DYNAMIC SYMBOL TABLE:\n"; 2379 if (!O->isELF()) { 2380 reportWarning( 2381 "this operation is not currently supported for this file format", 2382 FileName); 2383 return; 2384 } 2385 2386 const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(O); 2387 for (auto I = ELF->getDynamicSymbolIterators().begin(); 2388 I != ELF->getDynamicSymbolIterators().end(); ++I) 2389 printSymbol(O, *I, FileName, ArchiveName, ArchitectureName, DumpDynamic); 2390 } 2391 2392 void objdump::printSymbol(const ObjectFile *O, const SymbolRef &Symbol, 2393 StringRef FileName, StringRef ArchiveName, 2394 StringRef ArchitectureName, bool DumpDynamic) { 2395 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(O); 2396 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName, 2397 ArchitectureName); 2398 if ((Address < StartAddress) || (Address > StopAddress)) 2399 return; 2400 SymbolRef::Type Type = 2401 unwrapOrError(Symbol.getType(), FileName, ArchiveName, ArchitectureName); 2402 uint32_t Flags = 2403 unwrapOrError(Symbol.getFlags(), FileName, ArchiveName, ArchitectureName); 2404 2405 // Don't ask a Mach-O STAB symbol for its section unless you know that 2406 // STAB symbol's section field refers to a valid section index. Otherwise 2407 // the symbol may error trying to load a section that does not exist. 2408 bool IsSTAB = false; 2409 if (MachO) { 2410 DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); 2411 uint8_t NType = 2412 (MachO->is64Bit() ? MachO->getSymbol64TableEntry(SymDRI).n_type 2413 : MachO->getSymbolTableEntry(SymDRI).n_type); 2414 if (NType & MachO::N_STAB) 2415 IsSTAB = true; 2416 } 2417 section_iterator Section = IsSTAB 2418 ? O->section_end() 2419 : unwrapOrError(Symbol.getSection(), FileName, 2420 ArchiveName, ArchitectureName); 2421 2422 StringRef Name; 2423 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) { 2424 if (Expected<StringRef> NameOrErr = Section->getName()) 2425 Name = *NameOrErr; 2426 else 2427 consumeError(NameOrErr.takeError()); 2428 2429 } else { 2430 Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName, 2431 ArchitectureName); 2432 } 2433 2434 bool Global = Flags & SymbolRef::SF_Global; 2435 bool Weak = Flags & SymbolRef::SF_Weak; 2436 bool Absolute = Flags & SymbolRef::SF_Absolute; 2437 bool Common = Flags & SymbolRef::SF_Common; 2438 bool Hidden = Flags & SymbolRef::SF_Hidden; 2439 2440 char GlobLoc = ' '; 2441 if ((Section != O->section_end() || Absolute) && !Weak) 2442 GlobLoc = Global ? 'g' : 'l'; 2443 char IFunc = ' '; 2444 if (O->isELF()) { 2445 if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC) 2446 IFunc = 'i'; 2447 if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE) 2448 GlobLoc = 'u'; 2449 } 2450 2451 char Debug = ' '; 2452 if (DumpDynamic) 2453 Debug = 'D'; 2454 else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 2455 Debug = 'd'; 2456 2457 char FileFunc = ' '; 2458 if (Type == SymbolRef::ST_File) 2459 FileFunc = 'f'; 2460 else if (Type == SymbolRef::ST_Function) 2461 FileFunc = 'F'; 2462 else if (Type == SymbolRef::ST_Data) 2463 FileFunc = 'O'; 2464 2465 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2466 2467 outs() << format(Fmt, Address) << " " 2468 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 2469 << (Weak ? 'w' : ' ') // Weak? 2470 << ' ' // Constructor. Not supported yet. 2471 << ' ' // Warning. Not supported yet. 2472 << IFunc // Indirect reference to another symbol. 2473 << Debug // Debugging (d) or dynamic (D) symbol. 2474 << FileFunc // Name of function (F), file (f) or object (O). 2475 << ' '; 2476 if (Absolute) { 2477 outs() << "*ABS*"; 2478 } else if (Common) { 2479 outs() << "*COM*"; 2480 } else if (Section == O->section_end()) { 2481 outs() << "*UND*"; 2482 } else { 2483 if (MachO) { 2484 DataRefImpl DR = Section->getRawDataRefImpl(); 2485 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 2486 outs() << SegmentName << ","; 2487 } 2488 StringRef SectionName = unwrapOrError(Section->getName(), FileName); 2489 outs() << SectionName; 2490 } 2491 2492 if (Common || O->isELF()) { 2493 uint64_t Val = 2494 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 2495 outs() << '\t' << format(Fmt, Val); 2496 } 2497 2498 if (O->isELF()) { 2499 uint8_t Other = ELFSymbolRef(Symbol).getOther(); 2500 switch (Other) { 2501 case ELF::STV_DEFAULT: 2502 break; 2503 case ELF::STV_INTERNAL: 2504 outs() << " .internal"; 2505 break; 2506 case ELF::STV_HIDDEN: 2507 outs() << " .hidden"; 2508 break; 2509 case ELF::STV_PROTECTED: 2510 outs() << " .protected"; 2511 break; 2512 default: 2513 outs() << format(" 0x%02x", Other); 2514 break; 2515 } 2516 } else if (Hidden) { 2517 outs() << " .hidden"; 2518 } 2519 2520 if (Demangle) 2521 outs() << ' ' << demangle(std::string(Name)) << '\n'; 2522 else 2523 outs() << ' ' << Name << '\n'; 2524 } 2525 2526 static void printUnwindInfo(const ObjectFile *O) { 2527 outs() << "Unwind info:\n\n"; 2528 2529 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O)) 2530 printCOFFUnwindInfo(Coff); 2531 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O)) 2532 printMachOUnwindInfo(MachO); 2533 else 2534 // TODO: Extract DWARF dump tool to objdump. 2535 WithColor::error(errs(), ToolName) 2536 << "This operation is only currently supported " 2537 "for COFF and MachO object files.\n"; 2538 } 2539 2540 /// Dump the raw contents of the __clangast section so the output can be piped 2541 /// into llvm-bcanalyzer. 2542 static void printRawClangAST(const ObjectFile *Obj) { 2543 if (outs().is_displayed()) { 2544 WithColor::error(errs(), ToolName) 2545 << "The -raw-clang-ast option will dump the raw binary contents of " 2546 "the clang ast section.\n" 2547 "Please redirect the output to a file or another program such as " 2548 "llvm-bcanalyzer.\n"; 2549 return; 2550 } 2551 2552 StringRef ClangASTSectionName("__clangast"); 2553 if (Obj->isCOFF()) { 2554 ClangASTSectionName = "clangast"; 2555 } 2556 2557 Optional<object::SectionRef> ClangASTSection; 2558 for (auto Sec : ToolSectionFilter(*Obj)) { 2559 StringRef Name; 2560 if (Expected<StringRef> NameOrErr = Sec.getName()) 2561 Name = *NameOrErr; 2562 else 2563 consumeError(NameOrErr.takeError()); 2564 2565 if (Name == ClangASTSectionName) { 2566 ClangASTSection = Sec; 2567 break; 2568 } 2569 } 2570 if (!ClangASTSection) 2571 return; 2572 2573 StringRef ClangASTContents = unwrapOrError( 2574 ClangASTSection.getValue().getContents(), Obj->getFileName()); 2575 outs().write(ClangASTContents.data(), ClangASTContents.size()); 2576 } 2577 2578 static void printFaultMaps(const ObjectFile *Obj) { 2579 StringRef FaultMapSectionName; 2580 2581 if (Obj->isELF()) { 2582 FaultMapSectionName = ".llvm_faultmaps"; 2583 } else if (Obj->isMachO()) { 2584 FaultMapSectionName = "__llvm_faultmaps"; 2585 } else { 2586 WithColor::error(errs(), ToolName) 2587 << "This operation is only currently supported " 2588 "for ELF and Mach-O executable files.\n"; 2589 return; 2590 } 2591 2592 Optional<object::SectionRef> FaultMapSection; 2593 2594 for (auto Sec : ToolSectionFilter(*Obj)) { 2595 StringRef Name; 2596 if (Expected<StringRef> NameOrErr = Sec.getName()) 2597 Name = *NameOrErr; 2598 else 2599 consumeError(NameOrErr.takeError()); 2600 2601 if (Name == FaultMapSectionName) { 2602 FaultMapSection = Sec; 2603 break; 2604 } 2605 } 2606 2607 outs() << "FaultMap table:\n"; 2608 2609 if (!FaultMapSection.hasValue()) { 2610 outs() << "<not found>\n"; 2611 return; 2612 } 2613 2614 StringRef FaultMapContents = 2615 unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName()); 2616 FaultMapParser FMP(FaultMapContents.bytes_begin(), 2617 FaultMapContents.bytes_end()); 2618 2619 outs() << FMP; 2620 } 2621 2622 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) { 2623 if (O->isELF()) { 2624 printELFFileHeader(O); 2625 printELFDynamicSection(O); 2626 printELFSymbolVersionInfo(O); 2627 return; 2628 } 2629 if (O->isCOFF()) 2630 return printCOFFFileHeader(O); 2631 if (O->isWasm()) 2632 return printWasmFileHeader(O); 2633 if (O->isMachO()) { 2634 printMachOFileHeader(O); 2635 if (!OnlyFirst) 2636 printMachOLoadCommands(O); 2637 return; 2638 } 2639 reportError(O->getFileName(), "Invalid/Unsupported object file format"); 2640 } 2641 2642 static void printFileHeaders(const ObjectFile *O) { 2643 if (!O->isELF() && !O->isCOFF()) 2644 reportError(O->getFileName(), "Invalid/Unsupported object file format"); 2645 2646 Triple::ArchType AT = O->getArch(); 2647 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; 2648 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName()); 2649 2650 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2651 outs() << "start address: " 2652 << "0x" << format(Fmt.data(), Address) << "\n\n"; 2653 } 2654 2655 static void printArchiveChild(StringRef Filename, const Archive::Child &C) { 2656 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 2657 if (!ModeOrErr) { 2658 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n"; 2659 consumeError(ModeOrErr.takeError()); 2660 return; 2661 } 2662 sys::fs::perms Mode = ModeOrErr.get(); 2663 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 2664 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 2665 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 2666 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 2667 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 2668 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 2669 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 2670 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 2671 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 2672 2673 outs() << " "; 2674 2675 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename), 2676 unwrapOrError(C.getGID(), Filename), 2677 unwrapOrError(C.getRawSize(), Filename)); 2678 2679 StringRef RawLastModified = C.getRawLastModified(); 2680 unsigned Seconds; 2681 if (RawLastModified.getAsInteger(10, Seconds)) 2682 outs() << "(date: \"" << RawLastModified 2683 << "\" contains non-decimal chars) "; 2684 else { 2685 // Since ctime(3) returns a 26 character string of the form: 2686 // "Sun Sep 16 01:03:52 1973\n\0" 2687 // just print 24 characters. 2688 time_t t = Seconds; 2689 outs() << format("%.24s ", ctime(&t)); 2690 } 2691 2692 StringRef Name = ""; 2693 Expected<StringRef> NameOrErr = C.getName(); 2694 if (!NameOrErr) { 2695 consumeError(NameOrErr.takeError()); 2696 Name = unwrapOrError(C.getRawName(), Filename); 2697 } else { 2698 Name = NameOrErr.get(); 2699 } 2700 outs() << Name << "\n"; 2701 } 2702 2703 // For ELF only now. 2704 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) { 2705 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) { 2706 if (Elf->getEType() != ELF::ET_REL) 2707 return true; 2708 } 2709 return false; 2710 } 2711 2712 static void checkForInvalidStartStopAddress(ObjectFile *Obj, 2713 uint64_t Start, uint64_t Stop) { 2714 if (!shouldWarnForInvalidStartStopAddress(Obj)) 2715 return; 2716 2717 for (const SectionRef &Section : Obj->sections()) 2718 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) { 2719 uint64_t BaseAddr = Section.getAddress(); 2720 uint64_t Size = Section.getSize(); 2721 if ((Start < BaseAddr + Size) && Stop > BaseAddr) 2722 return; 2723 } 2724 2725 if (StartAddress.getNumOccurrences() == 0) 2726 reportWarning("no section has address less than 0x" + 2727 Twine::utohexstr(Stop) + " specified by --stop-address", 2728 Obj->getFileName()); 2729 else if (StopAddress.getNumOccurrences() == 0) 2730 reportWarning("no section has address greater than or equal to 0x" + 2731 Twine::utohexstr(Start) + " specified by --start-address", 2732 Obj->getFileName()); 2733 else 2734 reportWarning("no section overlaps the range [0x" + 2735 Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) + 2736 ") specified by --start-address/--stop-address", 2737 Obj->getFileName()); 2738 } 2739 2740 static void dumpObject(ObjectFile *O, const Archive *A = nullptr, 2741 const Archive::Child *C = nullptr) { 2742 // Avoid other output when using a raw option. 2743 if (!RawClangAST) { 2744 outs() << '\n'; 2745 if (A) 2746 outs() << A->getFileName() << "(" << O->getFileName() << ")"; 2747 else 2748 outs() << O->getFileName(); 2749 outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n\n"; 2750 } 2751 2752 if (StartAddress.getNumOccurrences() || StopAddress.getNumOccurrences()) 2753 checkForInvalidStartStopAddress(O, StartAddress, StopAddress); 2754 2755 // Note: the order here matches GNU objdump for compatability. 2756 StringRef ArchiveName = A ? A->getFileName() : ""; 2757 if (ArchiveHeaders && !MachOOpt && C) 2758 printArchiveChild(ArchiveName, *C); 2759 if (FileHeaders) 2760 printFileHeaders(O); 2761 if (PrivateHeaders || FirstPrivateHeader) 2762 printPrivateFileHeaders(O, FirstPrivateHeader); 2763 if (SectionHeaders) 2764 printSectionHeaders(O); 2765 if (SymbolTable) 2766 printSymbolTable(O, ArchiveName); 2767 if (DynamicSymbolTable) 2768 printSymbolTable(O, ArchiveName, /*ArchitectureName=*/"", 2769 /*DumpDynamic=*/true); 2770 if (DwarfDumpType != DIDT_Null) { 2771 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); 2772 // Dump the complete DWARF structure. 2773 DIDumpOptions DumpOpts; 2774 DumpOpts.DumpType = DwarfDumpType; 2775 DICtx->dump(outs(), DumpOpts); 2776 } 2777 if (Relocations && !Disassemble) 2778 printRelocations(O); 2779 if (DynamicRelocations) 2780 printDynamicRelocations(O); 2781 if (SectionContents) 2782 printSectionContents(O); 2783 if (Disassemble) 2784 disassembleObject(O, Relocations); 2785 if (UnwindInfo) 2786 printUnwindInfo(O); 2787 2788 // Mach-O specific options: 2789 if (ExportsTrie) 2790 printExportsTrie(O); 2791 if (Rebase) 2792 printRebaseTable(O); 2793 if (Bind) 2794 printBindTable(O); 2795 if (LazyBind) 2796 printLazyBindTable(O); 2797 if (WeakBind) 2798 printWeakBindTable(O); 2799 2800 // Other special sections: 2801 if (RawClangAST) 2802 printRawClangAST(O); 2803 if (FaultMapSection) 2804 printFaultMaps(O); 2805 } 2806 2807 static void dumpObject(const COFFImportFile *I, const Archive *A, 2808 const Archive::Child *C = nullptr) { 2809 StringRef ArchiveName = A ? A->getFileName() : ""; 2810 2811 // Avoid other output when using a raw option. 2812 if (!RawClangAST) 2813 outs() << '\n' 2814 << ArchiveName << "(" << I->getFileName() << ")" 2815 << ":\tfile format COFF-import-file" 2816 << "\n\n"; 2817 2818 if (ArchiveHeaders && !MachOOpt && C) 2819 printArchiveChild(ArchiveName, *C); 2820 if (SymbolTable) 2821 printCOFFSymbolTable(I); 2822 } 2823 2824 /// Dump each object file in \a a; 2825 static void dumpArchive(const Archive *A) { 2826 Error Err = Error::success(); 2827 unsigned I = -1; 2828 for (auto &C : A->children(Err)) { 2829 ++I; 2830 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2831 if (!ChildOrErr) { 2832 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2833 reportError(std::move(E), getFileNameForError(C, I), A->getFileName()); 2834 continue; 2835 } 2836 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 2837 dumpObject(O, A, &C); 2838 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 2839 dumpObject(I, A, &C); 2840 else 2841 reportError(errorCodeToError(object_error::invalid_file_type), 2842 A->getFileName()); 2843 } 2844 if (Err) 2845 reportError(std::move(Err), A->getFileName()); 2846 } 2847 2848 /// Open file and figure out how to dump it. 2849 static void dumpInput(StringRef file) { 2850 // If we are using the Mach-O specific object file parser, then let it parse 2851 // the file and process the command line options. So the -arch flags can 2852 // be used to select specific slices, etc. 2853 if (MachOOpt) { 2854 parseInputMachO(file); 2855 return; 2856 } 2857 2858 // Attempt to open the binary. 2859 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file); 2860 Binary &Binary = *OBinary.getBinary(); 2861 2862 if (Archive *A = dyn_cast<Archive>(&Binary)) 2863 dumpArchive(A); 2864 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary)) 2865 dumpObject(O); 2866 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) 2867 parseInputMachO(UB); 2868 else 2869 reportError(errorCodeToError(object_error::invalid_file_type), file); 2870 } 2871 2872 int main(int argc, char **argv) { 2873 using namespace llvm; 2874 InitLLVM X(argc, argv); 2875 const cl::OptionCategory *OptionFilters[] = {&ObjdumpCat, &MachOCat}; 2876 cl::HideUnrelatedOptions(OptionFilters); 2877 2878 // Initialize targets and assembly printers/parsers. 2879 InitializeAllTargetInfos(); 2880 InitializeAllTargetMCs(); 2881 InitializeAllDisassemblers(); 2882 2883 // Register the target printer for --version. 2884 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 2885 2886 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n", nullptr, 2887 /*EnvVar=*/nullptr, 2888 /*LongOptionsUseDoubleDash=*/true); 2889 2890 if (StartAddress >= StopAddress) 2891 reportCmdLineError("start address should be less than stop address"); 2892 2893 ToolName = argv[0]; 2894 2895 // Defaults to a.out if no filenames specified. 2896 if (InputFilenames.empty()) 2897 InputFilenames.push_back("a.out"); 2898 2899 if (AllHeaders) 2900 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = 2901 SectionHeaders = SymbolTable = true; 2902 2903 if (DisassembleAll || PrintSource || PrintLines || 2904 !DisassembleSymbols.empty()) 2905 Disassemble = true; 2906 2907 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null && 2908 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST && 2909 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable && 2910 !DynamicSymbolTable && !UnwindInfo && !FaultMapSection && 2911 !(MachOOpt && 2912 (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie || 2913 FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind || 2914 LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders || 2915 WeakBind || !FilterSections.empty()))) { 2916 cl::PrintHelpMessage(); 2917 return 2; 2918 } 2919 2920 DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end()); 2921 2922 llvm::for_each(InputFilenames, dumpInput); 2923 2924 warnOnNoMatchForSections(); 2925 2926 return EXIT_SUCCESS; 2927 } 2928