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