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