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