xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision 81e8b7d9496688476c6bb601cce2575c3f2811ed)
1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
12 // flags.
13 //
14 // The flags and output of this program should be near identical to those of
15 // binutils objdump.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm-objdump.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/FaultMaps.h"
25 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
29 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCInstPrinter.h"
32 #include "llvm/MC/MCInstrAnalysis.h"
33 #include "llvm/MC/MCInstrInfo.h"
34 #include "llvm/MC/MCObjectFileInfo.h"
35 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/Object/Archive.h"
38 #include "llvm/Object/COFF.h"
39 #include "llvm/Object/ELFObjectFile.h"
40 #include "llvm/Object/MachO.h"
41 #include "llvm/Object/ObjectFile.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/Errc.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/Format.h"
48 #include "llvm/Support/GraphWriter.h"
49 #include "llvm/Support/Host.h"
50 #include "llvm/Support/ManagedStatic.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/PrettyStackTrace.h"
53 #include "llvm/Support/Signals.h"
54 #include "llvm/Support/SourceMgr.h"
55 #include "llvm/Support/TargetRegistry.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <algorithm>
59 #include <cctype>
60 #include <cstring>
61 #include <system_error>
62 
63 using namespace llvm;
64 using namespace object;
65 
66 static cl::list<std::string>
67 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
68 
69 cl::opt<bool>
70 llvm::Disassemble("disassemble",
71   cl::desc("Display assembler mnemonics for the machine instructions"));
72 static cl::alias
73 Disassembled("d", cl::desc("Alias for --disassemble"),
74              cl::aliasopt(Disassemble));
75 
76 cl::opt<bool>
77 llvm::DisassembleAll("disassemble-all",
78   cl::desc("Display assembler mnemonics for the machine instructions"));
79 static cl::alias
80 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
81              cl::aliasopt(DisassembleAll));
82 
83 cl::opt<bool>
84 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
85 
86 cl::opt<bool>
87 llvm::SectionContents("s", cl::desc("Display the content of each section"));
88 
89 cl::opt<bool>
90 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
91 
92 cl::opt<bool>
93 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
94 
95 cl::opt<bool>
96 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
97 
98 cl::opt<bool>
99 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
100 
101 cl::opt<bool>
102 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
103 
104 cl::opt<bool>
105 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
106 
107 cl::opt<bool>
108 llvm::RawClangAST("raw-clang-ast",
109     cl::desc("Dump the raw binary contents of the clang AST section"));
110 
111 static cl::opt<bool>
112 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
113 static cl::alias
114 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
115 
116 cl::opt<std::string>
117 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
118                                     "see -version for available targets"));
119 
120 cl::opt<std::string>
121 llvm::MCPU("mcpu",
122      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
123      cl::value_desc("cpu-name"),
124      cl::init(""));
125 
126 cl::opt<std::string>
127 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
128                                 "see -version for available targets"));
129 
130 cl::opt<bool>
131 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
132                                                  "headers for each section."));
133 static cl::alias
134 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
135                     cl::aliasopt(SectionHeaders));
136 static cl::alias
137 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
138                       cl::aliasopt(SectionHeaders));
139 
140 cl::list<std::string>
141 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
142                                          "With -macho dump segment,section"));
143 cl::alias
144 static FilterSectionsj("j", cl::desc("Alias for --section"),
145                  cl::aliasopt(llvm::FilterSections));
146 
147 cl::list<std::string>
148 llvm::MAttrs("mattr",
149   cl::CommaSeparated,
150   cl::desc("Target specific attributes"),
151   cl::value_desc("a1,+a2,-a3,..."));
152 
153 cl::opt<bool>
154 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
155                                                  "instructions, do not print "
156                                                  "the instruction bytes."));
157 
158 cl::opt<bool>
159 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
160 
161 static cl::alias
162 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
163                 cl::aliasopt(UnwindInfo));
164 
165 cl::opt<bool>
166 llvm::PrivateHeaders("private-headers",
167                      cl::desc("Display format specific file headers"));
168 
169 cl::opt<bool>
170 llvm::FirstPrivateHeader("private-header",
171                          cl::desc("Display only the first format specific file "
172                                   "header"));
173 
174 static cl::alias
175 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
176                     cl::aliasopt(PrivateHeaders));
177 
178 cl::opt<bool>
179     llvm::PrintImmHex("print-imm-hex",
180                       cl::desc("Use hex format for immediate values"));
181 
182 cl::opt<bool> PrintFaultMaps("fault-map-section",
183                              cl::desc("Display contents of faultmap section"));
184 
185 cl::opt<DIDumpType> llvm::DwarfDumpType(
186     "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
187     cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
188                clEnumValEnd));
189 
190 static StringRef ToolName;
191 
192 namespace {
193 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
194 
195 class SectionFilterIterator {
196 public:
197   SectionFilterIterator(FilterPredicate P,
198                         llvm::object::section_iterator const &I,
199                         llvm::object::section_iterator const &E)
200       : Predicate(P), Iterator(I), End(E) {
201     ScanPredicate();
202   }
203   const llvm::object::SectionRef &operator*() const { return *Iterator; }
204   SectionFilterIterator &operator++() {
205     ++Iterator;
206     ScanPredicate();
207     return *this;
208   }
209   bool operator!=(SectionFilterIterator const &Other) const {
210     return Iterator != Other.Iterator;
211   }
212 
213 private:
214   void ScanPredicate() {
215     while (Iterator != End && !Predicate(*Iterator)) {
216       ++Iterator;
217     }
218   }
219   FilterPredicate Predicate;
220   llvm::object::section_iterator Iterator;
221   llvm::object::section_iterator End;
222 };
223 
224 class SectionFilter {
225 public:
226   SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
227       : Predicate(P), Object(O) {}
228   SectionFilterIterator begin() {
229     return SectionFilterIterator(Predicate, Object.section_begin(),
230                                  Object.section_end());
231   }
232   SectionFilterIterator end() {
233     return SectionFilterIterator(Predicate, Object.section_end(),
234                                  Object.section_end());
235   }
236 
237 private:
238   FilterPredicate Predicate;
239   llvm::object::ObjectFile const &Object;
240 };
241 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
242   return SectionFilter([](llvm::object::SectionRef const &S) {
243                          if(FilterSections.empty())
244                            return true;
245                          llvm::StringRef String;
246                          std::error_code error = S.getName(String);
247                          if (error)
248                            return false;
249                          return std::find(FilterSections.begin(),
250                                           FilterSections.end(),
251                                           String) != FilterSections.end();
252                        },
253                        O);
254 }
255 }
256 
257 void llvm::error(std::error_code EC) {
258   if (!EC)
259     return;
260 
261   errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
262   errs().flush();
263   exit(1);
264 }
265 
266 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
267                                                 std::error_code EC) {
268   assert(EC);
269   errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
270   exit(1);
271 }
272 
273 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
274                                                 llvm::Error E) {
275   assert(E);
276   std::string Buf;
277   raw_string_ostream OS(Buf);
278   logAllUnhandledErrors(std::move(E), OS, "");
279   OS.flush();
280   errs() << ToolName << ": " << Buf;
281   exit(1);
282 }
283 
284 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
285   // Figure out the target triple.
286   llvm::Triple TheTriple("unknown-unknown-unknown");
287   if (TripleName.empty()) {
288     if (Obj) {
289       TheTriple.setArch(Triple::ArchType(Obj->getArch()));
290       // TheTriple defaults to ELF, and COFF doesn't have an environment:
291       // the best we can do here is indicate that it is mach-o.
292       if (Obj->isMachO())
293         TheTriple.setObjectFormat(Triple::MachO);
294 
295       if (Obj->isCOFF()) {
296         const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
297         if (COFFObj->getArch() == Triple::thumb)
298           TheTriple.setTriple("thumbv7-windows");
299       }
300     }
301   } else
302     TheTriple.setTriple(Triple::normalize(TripleName));
303 
304   // Get the target specific parser.
305   std::string Error;
306   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
307                                                          Error);
308   if (!TheTarget)
309     report_fatal_error("can't find target: " + Error);
310 
311   // Update the triple name and return the found target.
312   TripleName = TheTriple.getTriple();
313   return TheTarget;
314 }
315 
316 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
317   return a.getOffset() < b.getOffset();
318 }
319 
320 namespace {
321 class PrettyPrinter {
322 public:
323   virtual ~PrettyPrinter(){}
324   virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
325                          ArrayRef<uint8_t> Bytes, uint64_t Address,
326                          raw_ostream &OS, StringRef Annot,
327                          MCSubtargetInfo const &STI) {
328     OS << format("%8" PRIx64 ":", Address);
329     if (!NoShowRawInsn) {
330       OS << "\t";
331       dumpBytes(Bytes, OS);
332     }
333     if (MI)
334       IP.printInst(MI, OS, "", STI);
335     else
336       OS << " <unknown>";
337   }
338 };
339 PrettyPrinter PrettyPrinterInst;
340 class HexagonPrettyPrinter : public PrettyPrinter {
341 public:
342   void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
343                  raw_ostream &OS) {
344     uint32_t opcode =
345       (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
346     OS << format("%8" PRIx64 ":", Address);
347     if (!NoShowRawInsn) {
348       OS << "\t";
349       dumpBytes(Bytes.slice(0, 4), OS);
350       OS << format("%08" PRIx32, opcode);
351     }
352   }
353   void printInst(MCInstPrinter &IP, const MCInst *MI,
354                  ArrayRef<uint8_t> Bytes, uint64_t Address,
355                  raw_ostream &OS, StringRef Annot,
356                  MCSubtargetInfo const &STI) override {
357     if (!MI) {
358       printLead(Bytes, Address, OS);
359       OS << " <unknown>";
360       return;
361     }
362     std::string Buffer;
363     {
364       raw_string_ostream TempStream(Buffer);
365       IP.printInst(MI, TempStream, "", STI);
366     }
367     StringRef Contents(Buffer);
368     // Split off bundle attributes
369     auto PacketBundle = Contents.rsplit('\n');
370     // Split off first instruction from the rest
371     auto HeadTail = PacketBundle.first.split('\n');
372     auto Preamble = " { ";
373     auto Separator = "";
374     while(!HeadTail.first.empty()) {
375       OS << Separator;
376       Separator = "\n";
377       printLead(Bytes, Address, OS);
378       OS << Preamble;
379       Preamble = "   ";
380       StringRef Inst;
381       auto Duplex = HeadTail.first.split('\v');
382       if(!Duplex.second.empty()){
383         OS << Duplex.first;
384         OS << "; ";
385         Inst = Duplex.second;
386       }
387       else
388         Inst = HeadTail.first;
389       OS << Inst;
390       Bytes = Bytes.slice(4);
391       Address += 4;
392       HeadTail = HeadTail.second.split('\n');
393     }
394     OS << " } " << PacketBundle.second;
395   }
396 };
397 HexagonPrettyPrinter HexagonPrettyPrinterInst;
398 
399 class AMDGCNPrettyPrinter : public PrettyPrinter {
400 public:
401   void printInst(MCInstPrinter &IP,
402                  const MCInst *MI,
403                  ArrayRef<uint8_t> Bytes,
404                  uint64_t Address,
405                  raw_ostream &OS,
406                  StringRef Annot,
407                  MCSubtargetInfo const &STI) override {
408     SmallString<40> InstStr;
409     raw_svector_ostream IS(InstStr);
410 
411     IP.printInst(MI, IS, "", STI);
412 
413     OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
414     typedef support::ulittle32_t U32;
415     for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
416                                Bytes.size() / sizeof(U32)))
417       // D should be explicitly casted to uint32_t here as it is passed
418       // by format to snprintf as vararg.
419       OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
420 
421     if (!Annot.empty())
422       OS << "// " << Annot;
423   }
424 };
425 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
426 
427 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
428   switch(Triple.getArch()) {
429   default:
430     return PrettyPrinterInst;
431   case Triple::hexagon:
432     return HexagonPrettyPrinterInst;
433   case Triple::amdgcn:
434     return AMDGCNPrettyPrinterInst;
435   }
436 }
437 }
438 
439 template <class ELFT>
440 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
441                                                 const RelocationRef &RelRef,
442                                                 SmallVectorImpl<char> &Result) {
443   DataRefImpl Rel = RelRef.getRawDataRefImpl();
444 
445   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
446   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
447   typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
448 
449   const ELFFile<ELFT> &EF = *Obj->getELFFile();
450 
451   ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
452   if (std::error_code EC = SecOrErr.getError())
453     return EC;
454   const Elf_Shdr *Sec = *SecOrErr;
455   ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
456   if (std::error_code EC = SymTabOrErr.getError())
457     return EC;
458   const Elf_Shdr *SymTab = *SymTabOrErr;
459   assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
460          SymTab->sh_type == ELF::SHT_DYNSYM);
461   ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
462   if (std::error_code EC = StrTabSec.getError())
463     return EC;
464   ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
465   if (std::error_code EC = StrTabOrErr.getError())
466     return EC;
467   StringRef StrTab = *StrTabOrErr;
468   uint8_t type = RelRef.getType();
469   StringRef res;
470   int64_t addend = 0;
471   switch (Sec->sh_type) {
472   default:
473     return object_error::parse_failed;
474   case ELF::SHT_REL: {
475     // TODO: Read implicit addend from section data.
476     break;
477   }
478   case ELF::SHT_RELA: {
479     const Elf_Rela *ERela = Obj->getRela(Rel);
480     addend = ERela->r_addend;
481     break;
482   }
483   }
484   symbol_iterator SI = RelRef.getSymbol();
485   const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
486   StringRef Target;
487   if (symb->getType() == ELF::STT_SECTION) {
488     ErrorOr<section_iterator> SymSI = SI->getSection();
489     if (std::error_code EC = SymSI.getError())
490       return EC;
491     const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
492     ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
493     if (std::error_code EC = SecName.getError())
494       return EC;
495     Target = *SecName;
496   } else {
497     Expected<StringRef> SymName = symb->getName(StrTab);
498     if (!SymName)
499       return errorToErrorCode(SymName.takeError());
500     Target = *SymName;
501   }
502   switch (EF.getHeader()->e_machine) {
503   case ELF::EM_X86_64:
504     switch (type) {
505     case ELF::R_X86_64_PC8:
506     case ELF::R_X86_64_PC16:
507     case ELF::R_X86_64_PC32: {
508       std::string fmtbuf;
509       raw_string_ostream fmt(fmtbuf);
510       fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
511       fmt.flush();
512       Result.append(fmtbuf.begin(), fmtbuf.end());
513     } break;
514     case ELF::R_X86_64_8:
515     case ELF::R_X86_64_16:
516     case ELF::R_X86_64_32:
517     case ELF::R_X86_64_32S:
518     case ELF::R_X86_64_64: {
519       std::string fmtbuf;
520       raw_string_ostream fmt(fmtbuf);
521       fmt << Target << (addend < 0 ? "" : "+") << addend;
522       fmt.flush();
523       Result.append(fmtbuf.begin(), fmtbuf.end());
524     } break;
525     default:
526       res = "Unknown";
527     }
528     break;
529   case ELF::EM_LANAI:
530   case ELF::EM_AARCH64: {
531     std::string fmtbuf;
532     raw_string_ostream fmt(fmtbuf);
533     fmt << Target;
534     if (addend != 0)
535       fmt << (addend < 0 ? "" : "+") << addend;
536     fmt.flush();
537     Result.append(fmtbuf.begin(), fmtbuf.end());
538     break;
539   }
540   case ELF::EM_386:
541   case ELF::EM_IAMCU:
542   case ELF::EM_ARM:
543   case ELF::EM_HEXAGON:
544   case ELF::EM_MIPS:
545     res = Target;
546     break;
547   case ELF::EM_WEBASSEMBLY:
548     switch (type) {
549     case ELF::R_WEBASSEMBLY_DATA: {
550       std::string fmtbuf;
551       raw_string_ostream fmt(fmtbuf);
552       fmt << Target << (addend < 0 ? "" : "+") << addend;
553       fmt.flush();
554       Result.append(fmtbuf.begin(), fmtbuf.end());
555       break;
556     }
557     case ELF::R_WEBASSEMBLY_FUNCTION:
558       res = Target;
559       break;
560     default:
561       res = "Unknown";
562     }
563     break;
564   default:
565     res = "Unknown";
566   }
567   if (Result.empty())
568     Result.append(res.begin(), res.end());
569   return std::error_code();
570 }
571 
572 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
573                                                 const RelocationRef &Rel,
574                                                 SmallVectorImpl<char> &Result) {
575   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
576     return getRelocationValueString(ELF32LE, Rel, Result);
577   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
578     return getRelocationValueString(ELF64LE, Rel, Result);
579   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
580     return getRelocationValueString(ELF32BE, Rel, Result);
581   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
582   return getRelocationValueString(ELF64BE, Rel, Result);
583 }
584 
585 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
586                                                 const RelocationRef &Rel,
587                                                 SmallVectorImpl<char> &Result) {
588   symbol_iterator SymI = Rel.getSymbol();
589   Expected<StringRef> SymNameOrErr = SymI->getName();
590   if (!SymNameOrErr)
591     return errorToErrorCode(SymNameOrErr.takeError());
592   StringRef SymName = *SymNameOrErr;
593   Result.append(SymName.begin(), SymName.end());
594   return std::error_code();
595 }
596 
597 static void printRelocationTargetName(const MachOObjectFile *O,
598                                       const MachO::any_relocation_info &RE,
599                                       raw_string_ostream &fmt) {
600   bool IsScattered = O->isRelocationScattered(RE);
601 
602   // Target of a scattered relocation is an address.  In the interest of
603   // generating pretty output, scan through the symbol table looking for a
604   // symbol that aligns with that address.  If we find one, print it.
605   // Otherwise, we just print the hex address of the target.
606   if (IsScattered) {
607     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
608 
609     for (const SymbolRef &Symbol : O->symbols()) {
610       std::error_code ec;
611       ErrorOr<uint64_t> Addr = Symbol.getAddress();
612       if ((ec = Addr.getError()))
613         report_fatal_error(ec.message());
614       if (*Addr != Val)
615         continue;
616       Expected<StringRef> Name = Symbol.getName();
617       if (!Name) {
618         std::string Buf;
619         raw_string_ostream OS(Buf);
620         logAllUnhandledErrors(Name.takeError(), OS, "");
621         OS.flush();
622         report_fatal_error(Buf);
623       }
624       fmt << *Name;
625       return;
626     }
627 
628     // If we couldn't find a symbol that this relocation refers to, try
629     // to find a section beginning instead.
630     for (const SectionRef &Section : ToolSectionFilter(*O)) {
631       std::error_code ec;
632 
633       StringRef Name;
634       uint64_t Addr = Section.getAddress();
635       if (Addr != Val)
636         continue;
637       if ((ec = Section.getName(Name)))
638         report_fatal_error(ec.message());
639       fmt << Name;
640       return;
641     }
642 
643     fmt << format("0x%x", Val);
644     return;
645   }
646 
647   StringRef S;
648   bool isExtern = O->getPlainRelocationExternal(RE);
649   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
650 
651   if (isExtern) {
652     symbol_iterator SI = O->symbol_begin();
653     advance(SI, Val);
654     Expected<StringRef> SOrErr = SI->getName();
655     error(errorToErrorCode(SOrErr.takeError()));
656     S = *SOrErr;
657   } else {
658     section_iterator SI = O->section_begin();
659     // Adjust for the fact that sections are 1-indexed.
660     advance(SI, Val - 1);
661     SI->getName(S);
662   }
663 
664   fmt << S;
665 }
666 
667 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
668                                                 const RelocationRef &RelRef,
669                                                 SmallVectorImpl<char> &Result) {
670   DataRefImpl Rel = RelRef.getRawDataRefImpl();
671   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
672 
673   unsigned Arch = Obj->getArch();
674 
675   std::string fmtbuf;
676   raw_string_ostream fmt(fmtbuf);
677   unsigned Type = Obj->getAnyRelocationType(RE);
678   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
679 
680   // Determine any addends that should be displayed with the relocation.
681   // These require decoding the relocation type, which is triple-specific.
682 
683   // X86_64 has entirely custom relocation types.
684   if (Arch == Triple::x86_64) {
685     bool isPCRel = Obj->getAnyRelocationPCRel(RE);
686 
687     switch (Type) {
688     case MachO::X86_64_RELOC_GOT_LOAD:
689     case MachO::X86_64_RELOC_GOT: {
690       printRelocationTargetName(Obj, RE, fmt);
691       fmt << "@GOT";
692       if (isPCRel)
693         fmt << "PCREL";
694       break;
695     }
696     case MachO::X86_64_RELOC_SUBTRACTOR: {
697       DataRefImpl RelNext = Rel;
698       Obj->moveRelocationNext(RelNext);
699       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
700 
701       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
702       // X86_64_RELOC_UNSIGNED.
703       // NOTE: Scattered relocations don't exist on x86_64.
704       unsigned RType = Obj->getAnyRelocationType(RENext);
705       if (RType != MachO::X86_64_RELOC_UNSIGNED)
706         report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
707                            "X86_64_RELOC_SUBTRACTOR.");
708 
709       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
710       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
711       printRelocationTargetName(Obj, RENext, fmt);
712       fmt << "-";
713       printRelocationTargetName(Obj, RE, fmt);
714       break;
715     }
716     case MachO::X86_64_RELOC_TLV:
717       printRelocationTargetName(Obj, RE, fmt);
718       fmt << "@TLV";
719       if (isPCRel)
720         fmt << "P";
721       break;
722     case MachO::X86_64_RELOC_SIGNED_1:
723       printRelocationTargetName(Obj, RE, fmt);
724       fmt << "-1";
725       break;
726     case MachO::X86_64_RELOC_SIGNED_2:
727       printRelocationTargetName(Obj, RE, fmt);
728       fmt << "-2";
729       break;
730     case MachO::X86_64_RELOC_SIGNED_4:
731       printRelocationTargetName(Obj, RE, fmt);
732       fmt << "-4";
733       break;
734     default:
735       printRelocationTargetName(Obj, RE, fmt);
736       break;
737     }
738     // X86 and ARM share some relocation types in common.
739   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
740              Arch == Triple::ppc) {
741     // Generic relocation types...
742     switch (Type) {
743     case MachO::GENERIC_RELOC_PAIR: // prints no info
744       return std::error_code();
745     case MachO::GENERIC_RELOC_SECTDIFF: {
746       DataRefImpl RelNext = Rel;
747       Obj->moveRelocationNext(RelNext);
748       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
749 
750       // X86 sect diff's must be followed by a relocation of type
751       // GENERIC_RELOC_PAIR.
752       unsigned RType = Obj->getAnyRelocationType(RENext);
753 
754       if (RType != MachO::GENERIC_RELOC_PAIR)
755         report_fatal_error("Expected GENERIC_RELOC_PAIR after "
756                            "GENERIC_RELOC_SECTDIFF.");
757 
758       printRelocationTargetName(Obj, RE, fmt);
759       fmt << "-";
760       printRelocationTargetName(Obj, RENext, fmt);
761       break;
762     }
763     }
764 
765     if (Arch == Triple::x86 || Arch == Triple::ppc) {
766       switch (Type) {
767       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
768         DataRefImpl RelNext = Rel;
769         Obj->moveRelocationNext(RelNext);
770         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
771 
772         // X86 sect diff's must be followed by a relocation of type
773         // GENERIC_RELOC_PAIR.
774         unsigned RType = Obj->getAnyRelocationType(RENext);
775         if (RType != MachO::GENERIC_RELOC_PAIR)
776           report_fatal_error("Expected GENERIC_RELOC_PAIR after "
777                              "GENERIC_RELOC_LOCAL_SECTDIFF.");
778 
779         printRelocationTargetName(Obj, RE, fmt);
780         fmt << "-";
781         printRelocationTargetName(Obj, RENext, fmt);
782         break;
783       }
784       case MachO::GENERIC_RELOC_TLV: {
785         printRelocationTargetName(Obj, RE, fmt);
786         fmt << "@TLV";
787         if (IsPCRel)
788           fmt << "P";
789         break;
790       }
791       default:
792         printRelocationTargetName(Obj, RE, fmt);
793       }
794     } else { // ARM-specific relocations
795       switch (Type) {
796       case MachO::ARM_RELOC_HALF:
797       case MachO::ARM_RELOC_HALF_SECTDIFF: {
798         // Half relocations steal a bit from the length field to encode
799         // whether this is an upper16 or a lower16 relocation.
800         bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
801 
802         if (isUpper)
803           fmt << ":upper16:(";
804         else
805           fmt << ":lower16:(";
806         printRelocationTargetName(Obj, RE, fmt);
807 
808         DataRefImpl RelNext = Rel;
809         Obj->moveRelocationNext(RelNext);
810         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
811 
812         // ARM half relocs must be followed by a relocation of type
813         // ARM_RELOC_PAIR.
814         unsigned RType = Obj->getAnyRelocationType(RENext);
815         if (RType != MachO::ARM_RELOC_PAIR)
816           report_fatal_error("Expected ARM_RELOC_PAIR after "
817                              "ARM_RELOC_HALF");
818 
819         // NOTE: The half of the target virtual address is stashed in the
820         // address field of the secondary relocation, but we can't reverse
821         // engineer the constant offset from it without decoding the movw/movt
822         // instruction to find the other half in its immediate field.
823 
824         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
825         // symbol/section pointer of the follow-on relocation.
826         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
827           fmt << "-";
828           printRelocationTargetName(Obj, RENext, fmt);
829         }
830 
831         fmt << ")";
832         break;
833       }
834       default: { printRelocationTargetName(Obj, RE, fmt); }
835       }
836     }
837   } else
838     printRelocationTargetName(Obj, RE, fmt);
839 
840   fmt.flush();
841   Result.append(fmtbuf.begin(), fmtbuf.end());
842   return std::error_code();
843 }
844 
845 static std::error_code getRelocationValueString(const RelocationRef &Rel,
846                                                 SmallVectorImpl<char> &Result) {
847   const ObjectFile *Obj = Rel.getObject();
848   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
849     return getRelocationValueString(ELF, Rel, Result);
850   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
851     return getRelocationValueString(COFF, Rel, Result);
852   auto *MachO = cast<MachOObjectFile>(Obj);
853   return getRelocationValueString(MachO, Rel, Result);
854 }
855 
856 /// @brief Indicates whether this relocation should hidden when listing
857 /// relocations, usually because it is the trailing part of a multipart
858 /// relocation that will be printed as part of the leading relocation.
859 static bool getHidden(RelocationRef RelRef) {
860   const ObjectFile *Obj = RelRef.getObject();
861   auto *MachO = dyn_cast<MachOObjectFile>(Obj);
862   if (!MachO)
863     return false;
864 
865   unsigned Arch = MachO->getArch();
866   DataRefImpl Rel = RelRef.getRawDataRefImpl();
867   uint64_t Type = MachO->getRelocationType(Rel);
868 
869   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
870   // is always hidden.
871   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
872     if (Type == MachO::GENERIC_RELOC_PAIR)
873       return true;
874   } else if (Arch == Triple::x86_64) {
875     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
876     // an X86_64_RELOC_SUBTRACTOR.
877     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
878       DataRefImpl RelPrev = Rel;
879       RelPrev.d.a--;
880       uint64_t PrevType = MachO->getRelocationType(RelPrev);
881       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
882         return true;
883     }
884   }
885 
886   return false;
887 }
888 
889 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
890   const Target *TheTarget = getTarget(Obj);
891 
892   // Package up features to be passed to target/subtarget
893   std::string FeaturesStr;
894   if (MAttrs.size()) {
895     SubtargetFeatures Features;
896     for (unsigned i = 0; i != MAttrs.size(); ++i)
897       Features.AddFeature(MAttrs[i]);
898     FeaturesStr = Features.getString();
899   }
900 
901   std::unique_ptr<const MCRegisterInfo> MRI(
902       TheTarget->createMCRegInfo(TripleName));
903   if (!MRI)
904     report_fatal_error("error: no register info for target " + TripleName);
905 
906   // Set up disassembler.
907   std::unique_ptr<const MCAsmInfo> AsmInfo(
908       TheTarget->createMCAsmInfo(*MRI, TripleName));
909   if (!AsmInfo)
910     report_fatal_error("error: no assembly info for target " + TripleName);
911   std::unique_ptr<const MCSubtargetInfo> STI(
912       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
913   if (!STI)
914     report_fatal_error("error: no subtarget info for target " + TripleName);
915   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
916   if (!MII)
917     report_fatal_error("error: no instruction info for target " + TripleName);
918   std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
919   MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
920 
921   std::unique_ptr<MCDisassembler> DisAsm(
922     TheTarget->createMCDisassembler(*STI, Ctx));
923   if (!DisAsm)
924     report_fatal_error("error: no disassembler for target " + TripleName);
925 
926   std::unique_ptr<const MCInstrAnalysis> MIA(
927       TheTarget->createMCInstrAnalysis(MII.get()));
928 
929   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
930   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
931       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
932   if (!IP)
933     report_fatal_error("error: no instruction printer for target " +
934                        TripleName);
935   IP->setPrintImmHex(PrintImmHex);
936   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
937 
938   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
939                                                  "\t\t\t%08" PRIx64 ":  ";
940 
941   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
942   // in RelocSecs contain the relocations for section S.
943   std::error_code EC;
944   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
945   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
946     section_iterator Sec2 = Section.getRelocatedSection();
947     if (Sec2 != Obj->section_end())
948       SectionRelocMap[*Sec2].push_back(Section);
949   }
950 
951   // Create a mapping from virtual address to symbol name.  This is used to
952   // pretty print the symbols while disassembling.
953   typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
954   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
955   for (const SymbolRef &Symbol : Obj->symbols()) {
956     ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
957     error(AddressOrErr.getError());
958     uint64_t Address = *AddressOrErr;
959 
960     Expected<StringRef> Name = Symbol.getName();
961     error(errorToErrorCode(Name.takeError()));
962     if (Name->empty())
963       continue;
964 
965     ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
966     error(SectionOrErr.getError());
967     section_iterator SecI = *SectionOrErr;
968     if (SecI == Obj->section_end())
969       continue;
970 
971     AllSymbols[*SecI].emplace_back(Address, *Name);
972   }
973 
974   // Create a mapping from virtual address to section.
975   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
976   for (SectionRef Sec : Obj->sections())
977     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
978   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
979 
980   // Linked executables (.exe and .dll files) typically don't include a real
981   // symbol table but they might contain an export table.
982   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
983     for (const auto &ExportEntry : COFFObj->export_directories()) {
984       StringRef Name;
985       error(ExportEntry.getSymbolName(Name));
986       if (Name.empty())
987         continue;
988       uint32_t RVA;
989       error(ExportEntry.getExportRVA(RVA));
990 
991       uint64_t VA = COFFObj->getImageBase() + RVA;
992       auto Sec = std::upper_bound(
993           SectionAddresses.begin(), SectionAddresses.end(), VA,
994           [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
995             return LHS < RHS.first;
996           });
997       if (Sec != SectionAddresses.begin())
998         --Sec;
999       else
1000         Sec = SectionAddresses.end();
1001 
1002       if (Sec != SectionAddresses.end())
1003         AllSymbols[Sec->second].emplace_back(VA, Name);
1004     }
1005   }
1006 
1007   // Sort all the symbols, this allows us to use a simple binary search to find
1008   // a symbol near an address.
1009   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1010     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1011 
1012   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1013     if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1014       continue;
1015 
1016     uint64_t SectionAddr = Section.getAddress();
1017     uint64_t SectSize = Section.getSize();
1018     if (!SectSize)
1019       continue;
1020 
1021     // Get the list of all the symbols in this section.
1022     SectionSymbolsTy &Symbols = AllSymbols[Section];
1023     std::vector<uint64_t> DataMappingSymsAddr;
1024     std::vector<uint64_t> TextMappingSymsAddr;
1025     if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1026       for (const auto &Symb : Symbols) {
1027         uint64_t Address = Symb.first;
1028         StringRef Name = Symb.second;
1029         if (Name.startswith("$d"))
1030           DataMappingSymsAddr.push_back(Address - SectionAddr);
1031         if (Name.startswith("$x"))
1032           TextMappingSymsAddr.push_back(Address - SectionAddr);
1033       }
1034     }
1035 
1036     std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1037     std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
1038 
1039     // Make a list of all the relocations for this section.
1040     std::vector<RelocationRef> Rels;
1041     if (InlineRelocs) {
1042       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1043         for (const RelocationRef &Reloc : RelocSec.relocations()) {
1044           Rels.push_back(Reloc);
1045         }
1046       }
1047     }
1048 
1049     // Sort relocations by address.
1050     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1051 
1052     StringRef SegmentName = "";
1053     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1054       DataRefImpl DR = Section.getRawDataRefImpl();
1055       SegmentName = MachO->getSectionFinalSegmentName(DR);
1056     }
1057     StringRef name;
1058     error(Section.getName(name));
1059     outs() << "Disassembly of section ";
1060     if (!SegmentName.empty())
1061       outs() << SegmentName << ",";
1062     outs() << name << ':';
1063 
1064     // If the section has no symbol at the start, just insert a dummy one.
1065     if (Symbols.empty() || Symbols[0].first != 0)
1066       Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
1067 
1068     SmallString<40> Comments;
1069     raw_svector_ostream CommentStream(Comments);
1070 
1071     StringRef BytesStr;
1072     error(Section.getContents(BytesStr));
1073     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1074                             BytesStr.size());
1075 
1076     uint64_t Size;
1077     uint64_t Index;
1078 
1079     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1080     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1081     // Disassemble symbol by symbol.
1082     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1083 
1084       uint64_t Start = Symbols[si].first - SectionAddr;
1085       // The end is either the section end or the beginning of the next
1086       // symbol.
1087       uint64_t End =
1088           (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1089       // Don't try to disassemble beyond the end of section contents.
1090       if (End > SectSize)
1091         End = SectSize;
1092       // If this symbol has the same address as the next symbol, then skip it.
1093       if (Start >= End)
1094         continue;
1095 
1096       if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1097         // make size 4 bytes folded
1098         End = Start + ((End - Start) & ~0x3ull);
1099         Start += 256; // add sizeof(amd_kernel_code_t)
1100         // cut trailing zeroes - up to 256 bytes (align)
1101         const uint64_t EndAlign = 256;
1102         const auto Limit = End - (std::min)(EndAlign, End - Start);
1103         while (End > Limit &&
1104           *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1105           End -= 4;
1106       }
1107 
1108       outs() << '\n' << Symbols[si].second << ":\n";
1109 
1110 #ifndef NDEBUG
1111       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1112 #else
1113       raw_ostream &DebugOut = nulls();
1114 #endif
1115 
1116       for (Index = Start; Index < End; Index += Size) {
1117         MCInst Inst;
1118 
1119         // AArch64 ELF binaries can interleave data and text in the
1120         // same section. We rely on the markers introduced to
1121         // understand what we need to dump.
1122         if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1123           uint64_t Stride = 0;
1124 
1125           auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1126                                       DataMappingSymsAddr.end(), Index);
1127           if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1128             // Switch to data.
1129             while (Index < End) {
1130               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1131               outs() << "\t";
1132               if (Index + 4 <= End) {
1133                 Stride = 4;
1134                 dumpBytes(Bytes.slice(Index, 4), outs());
1135                 outs() << "\t.word";
1136               } else if (Index + 2 <= End) {
1137                 Stride = 2;
1138                 dumpBytes(Bytes.slice(Index, 2), outs());
1139                 outs() << "\t.short";
1140               } else {
1141                 Stride = 1;
1142                 dumpBytes(Bytes.slice(Index, 1), outs());
1143                 outs() << "\t.byte";
1144               }
1145               Index += Stride;
1146               outs() << "\n";
1147               auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1148                                           TextMappingSymsAddr.end(), Index);
1149               if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1150                 break;
1151             }
1152           }
1153         }
1154 
1155         if (Index >= End)
1156           break;
1157 
1158         bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1159                                                    SectionAddr + Index, DebugOut,
1160                                                    CommentStream);
1161         if (Size == 0)
1162           Size = 1;
1163         PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1164                       Bytes.slice(Index, Size),
1165                       SectionAddr + Index, outs(), "", *STI);
1166         outs() << CommentStream.str();
1167         Comments.clear();
1168 
1169         // Try to resolve the target of a call, tail call, etc. to a specific
1170         // symbol.
1171         if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1172                     MIA->isConditionalBranch(Inst))) {
1173           uint64_t Target;
1174           if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1175             // In a relocatable object, the target's section must reside in
1176             // the same section as the call instruction or it is accessed
1177             // through a relocation.
1178             //
1179             // In a non-relocatable object, the target may be in any section.
1180             //
1181             // N.B. We don't walk the relocations in the relocatable case yet.
1182             auto *TargetSectionSymbols = &Symbols;
1183             if (!Obj->isRelocatableObject()) {
1184               auto SectionAddress = std::upper_bound(
1185                   SectionAddresses.begin(), SectionAddresses.end(), Target,
1186                   [](uint64_t LHS,
1187                       const std::pair<uint64_t, SectionRef> &RHS) {
1188                     return LHS < RHS.first;
1189                   });
1190               if (SectionAddress != SectionAddresses.begin()) {
1191                 --SectionAddress;
1192                 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1193               } else {
1194                 TargetSectionSymbols = nullptr;
1195               }
1196             }
1197 
1198             // Find the first symbol in the section whose offset is less than
1199             // or equal to the target.
1200             if (TargetSectionSymbols) {
1201               auto TargetSym = std::upper_bound(
1202                   TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1203                   Target, [](uint64_t LHS,
1204                               const std::pair<uint64_t, StringRef> &RHS) {
1205                     return LHS < RHS.first;
1206                   });
1207               if (TargetSym != TargetSectionSymbols->begin()) {
1208                 --TargetSym;
1209                 uint64_t TargetAddress = std::get<0>(*TargetSym);
1210                 StringRef TargetName = std::get<1>(*TargetSym);
1211                 outs() << " <" << TargetName;
1212                 uint64_t Disp = Target - TargetAddress;
1213                 if (Disp)
1214                   outs() << "+0x" << utohexstr(Disp);
1215                 outs() << '>';
1216               }
1217             }
1218           }
1219         }
1220         outs() << "\n";
1221 
1222         // Print relocation for instruction.
1223         while (rel_cur != rel_end) {
1224           bool hidden = getHidden(*rel_cur);
1225           uint64_t addr = rel_cur->getOffset();
1226           SmallString<16> name;
1227           SmallString<32> val;
1228 
1229           // If this relocation is hidden, skip it.
1230           if (hidden) goto skip_print_rel;
1231 
1232           // Stop when rel_cur's address is past the current instruction.
1233           if (addr >= Index + Size) break;
1234           rel_cur->getTypeName(name);
1235           error(getRelocationValueString(*rel_cur, val));
1236           outs() << format(Fmt.data(), SectionAddr + addr) << name
1237                  << "\t" << val << "\n";
1238 
1239         skip_print_rel:
1240           ++rel_cur;
1241         }
1242       }
1243     }
1244   }
1245 }
1246 
1247 void llvm::PrintRelocations(const ObjectFile *Obj) {
1248   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1249                                                  "%08" PRIx64;
1250   // Regular objdump doesn't print relocations in non-relocatable object
1251   // files.
1252   if (!Obj->isRelocatableObject())
1253     return;
1254 
1255   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1256     if (Section.relocation_begin() == Section.relocation_end())
1257       continue;
1258     StringRef secname;
1259     error(Section.getName(secname));
1260     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1261     for (const RelocationRef &Reloc : Section.relocations()) {
1262       bool hidden = getHidden(Reloc);
1263       uint64_t address = Reloc.getOffset();
1264       SmallString<32> relocname;
1265       SmallString<32> valuestr;
1266       if (hidden)
1267         continue;
1268       Reloc.getTypeName(relocname);
1269       error(getRelocationValueString(Reloc, valuestr));
1270       outs() << format(Fmt.data(), address) << " " << relocname << " "
1271              << valuestr << "\n";
1272     }
1273     outs() << "\n";
1274   }
1275 }
1276 
1277 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1278   outs() << "Sections:\n"
1279             "Idx Name          Size      Address          Type\n";
1280   unsigned i = 0;
1281   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1282     StringRef Name;
1283     error(Section.getName(Name));
1284     uint64_t Address = Section.getAddress();
1285     uint64_t Size = Section.getSize();
1286     bool Text = Section.isText();
1287     bool Data = Section.isData();
1288     bool BSS = Section.isBSS();
1289     std::string Type = (std::string(Text ? "TEXT " : "") +
1290                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1291     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1292                      Name.str().c_str(), Size, Address, Type.c_str());
1293     ++i;
1294   }
1295 }
1296 
1297 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1298   std::error_code EC;
1299   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1300     StringRef Name;
1301     StringRef Contents;
1302     error(Section.getName(Name));
1303     uint64_t BaseAddr = Section.getAddress();
1304     uint64_t Size = Section.getSize();
1305     if (!Size)
1306       continue;
1307 
1308     outs() << "Contents of section " << Name << ":\n";
1309     if (Section.isBSS()) {
1310       outs() << format("<skipping contents of bss section at [%04" PRIx64
1311                        ", %04" PRIx64 ")>\n",
1312                        BaseAddr, BaseAddr + Size);
1313       continue;
1314     }
1315 
1316     error(Section.getContents(Contents));
1317 
1318     // Dump out the content as hex and printable ascii characters.
1319     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1320       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1321       // Dump line of hex.
1322       for (std::size_t i = 0; i < 16; ++i) {
1323         if (i != 0 && i % 4 == 0)
1324           outs() << ' ';
1325         if (addr + i < end)
1326           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1327                  << hexdigit(Contents[addr + i] & 0xF, true);
1328         else
1329           outs() << "  ";
1330       }
1331       // Print ascii.
1332       outs() << "  ";
1333       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1334         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1335           outs() << Contents[addr + i];
1336         else
1337           outs() << ".";
1338       }
1339       outs() << "\n";
1340     }
1341   }
1342 }
1343 
1344 void llvm::PrintSymbolTable(const ObjectFile *o) {
1345   outs() << "SYMBOL TABLE:\n";
1346 
1347   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1348     printCOFFSymbolTable(coff);
1349     return;
1350   }
1351   for (const SymbolRef &Symbol : o->symbols()) {
1352     ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1353     error(AddressOrError.getError());
1354     uint64_t Address = *AddressOrError;
1355     ErrorOr<SymbolRef::Type> TypeOrError = Symbol.getType();
1356     error(TypeOrError.getError());
1357     SymbolRef::Type Type = *TypeOrError;
1358     uint32_t Flags = Symbol.getFlags();
1359     ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1360     error(SectionOrErr.getError());
1361     section_iterator Section = *SectionOrErr;
1362     StringRef Name;
1363     if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1364       Section->getName(Name);
1365     } else {
1366       Expected<StringRef> NameOrErr = Symbol.getName();
1367       if (!NameOrErr)
1368         report_error(o->getFileName(), NameOrErr.takeError());
1369       Name = *NameOrErr;
1370     }
1371 
1372     bool Global = Flags & SymbolRef::SF_Global;
1373     bool Weak = Flags & SymbolRef::SF_Weak;
1374     bool Absolute = Flags & SymbolRef::SF_Absolute;
1375     bool Common = Flags & SymbolRef::SF_Common;
1376     bool Hidden = Flags & SymbolRef::SF_Hidden;
1377 
1378     char GlobLoc = ' ';
1379     if (Type != SymbolRef::ST_Unknown)
1380       GlobLoc = Global ? 'g' : 'l';
1381     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1382                  ? 'd' : ' ';
1383     char FileFunc = ' ';
1384     if (Type == SymbolRef::ST_File)
1385       FileFunc = 'f';
1386     else if (Type == SymbolRef::ST_Function)
1387       FileFunc = 'F';
1388 
1389     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1390                                                    "%08" PRIx64;
1391 
1392     outs() << format(Fmt, Address) << " "
1393            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1394            << (Weak ? 'w' : ' ') // Weak?
1395            << ' ' // Constructor. Not supported yet.
1396            << ' ' // Warning. Not supported yet.
1397            << ' ' // Indirect reference to another symbol.
1398            << Debug // Debugging (d) or dynamic (D) symbol.
1399            << FileFunc // Name of function (F), file (f) or object (O).
1400            << ' ';
1401     if (Absolute) {
1402       outs() << "*ABS*";
1403     } else if (Common) {
1404       outs() << "*COM*";
1405     } else if (Section == o->section_end()) {
1406       outs() << "*UND*";
1407     } else {
1408       if (const MachOObjectFile *MachO =
1409           dyn_cast<const MachOObjectFile>(o)) {
1410         DataRefImpl DR = Section->getRawDataRefImpl();
1411         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1412         outs() << SegmentName << ",";
1413       }
1414       StringRef SectionName;
1415       error(Section->getName(SectionName));
1416       outs() << SectionName;
1417     }
1418 
1419     outs() << '\t';
1420     if (Common || isa<ELFObjectFileBase>(o)) {
1421       uint64_t Val =
1422           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1423       outs() << format("\t %08" PRIx64 " ", Val);
1424     }
1425 
1426     if (Hidden) {
1427       outs() << ".hidden ";
1428     }
1429     outs() << Name
1430            << '\n';
1431   }
1432 }
1433 
1434 static void PrintUnwindInfo(const ObjectFile *o) {
1435   outs() << "Unwind info:\n\n";
1436 
1437   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1438     printCOFFUnwindInfo(coff);
1439   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1440     printMachOUnwindInfo(MachO);
1441   else {
1442     // TODO: Extract DWARF dump tool to objdump.
1443     errs() << "This operation is only currently supported "
1444               "for COFF and MachO object files.\n";
1445     return;
1446   }
1447 }
1448 
1449 void llvm::printExportsTrie(const ObjectFile *o) {
1450   outs() << "Exports trie:\n";
1451   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1452     printMachOExportsTrie(MachO);
1453   else {
1454     errs() << "This operation is only currently supported "
1455               "for Mach-O executable files.\n";
1456     return;
1457   }
1458 }
1459 
1460 void llvm::printRebaseTable(const ObjectFile *o) {
1461   outs() << "Rebase table:\n";
1462   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1463     printMachORebaseTable(MachO);
1464   else {
1465     errs() << "This operation is only currently supported "
1466               "for Mach-O executable files.\n";
1467     return;
1468   }
1469 }
1470 
1471 void llvm::printBindTable(const ObjectFile *o) {
1472   outs() << "Bind table:\n";
1473   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1474     printMachOBindTable(MachO);
1475   else {
1476     errs() << "This operation is only currently supported "
1477               "for Mach-O executable files.\n";
1478     return;
1479   }
1480 }
1481 
1482 void llvm::printLazyBindTable(const ObjectFile *o) {
1483   outs() << "Lazy bind table:\n";
1484   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1485     printMachOLazyBindTable(MachO);
1486   else {
1487     errs() << "This operation is only currently supported "
1488               "for Mach-O executable files.\n";
1489     return;
1490   }
1491 }
1492 
1493 void llvm::printWeakBindTable(const ObjectFile *o) {
1494   outs() << "Weak bind table:\n";
1495   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1496     printMachOWeakBindTable(MachO);
1497   else {
1498     errs() << "This operation is only currently supported "
1499               "for Mach-O executable files.\n";
1500     return;
1501   }
1502 }
1503 
1504 /// Dump the raw contents of the __clangast section so the output can be piped
1505 /// into llvm-bcanalyzer.
1506 void llvm::printRawClangAST(const ObjectFile *Obj) {
1507   if (outs().is_displayed()) {
1508     errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1509               "the clang ast section.\n"
1510               "Please redirect the output to a file or another program such as "
1511               "llvm-bcanalyzer.\n";
1512     return;
1513   }
1514 
1515   StringRef ClangASTSectionName("__clangast");
1516   if (isa<COFFObjectFile>(Obj)) {
1517     ClangASTSectionName = "clangast";
1518   }
1519 
1520   Optional<object::SectionRef> ClangASTSection;
1521   for (auto Sec : ToolSectionFilter(*Obj)) {
1522     StringRef Name;
1523     Sec.getName(Name);
1524     if (Name == ClangASTSectionName) {
1525       ClangASTSection = Sec;
1526       break;
1527     }
1528   }
1529   if (!ClangASTSection)
1530     return;
1531 
1532   StringRef ClangASTContents;
1533   error(ClangASTSection.getValue().getContents(ClangASTContents));
1534   outs().write(ClangASTContents.data(), ClangASTContents.size());
1535 }
1536 
1537 static void printFaultMaps(const ObjectFile *Obj) {
1538   const char *FaultMapSectionName = nullptr;
1539 
1540   if (isa<ELFObjectFileBase>(Obj)) {
1541     FaultMapSectionName = ".llvm_faultmaps";
1542   } else if (isa<MachOObjectFile>(Obj)) {
1543     FaultMapSectionName = "__llvm_faultmaps";
1544   } else {
1545     errs() << "This operation is only currently supported "
1546               "for ELF and Mach-O executable files.\n";
1547     return;
1548   }
1549 
1550   Optional<object::SectionRef> FaultMapSection;
1551 
1552   for (auto Sec : ToolSectionFilter(*Obj)) {
1553     StringRef Name;
1554     Sec.getName(Name);
1555     if (Name == FaultMapSectionName) {
1556       FaultMapSection = Sec;
1557       break;
1558     }
1559   }
1560 
1561   outs() << "FaultMap table:\n";
1562 
1563   if (!FaultMapSection.hasValue()) {
1564     outs() << "<not found>\n";
1565     return;
1566   }
1567 
1568   StringRef FaultMapContents;
1569   error(FaultMapSection.getValue().getContents(FaultMapContents));
1570 
1571   FaultMapParser FMP(FaultMapContents.bytes_begin(),
1572                      FaultMapContents.bytes_end());
1573 
1574   outs() << FMP;
1575 }
1576 
1577 static void printPrivateFileHeaders(const ObjectFile *o) {
1578   if (o->isELF())
1579     printELFFileHeader(o);
1580   else if (o->isCOFF())
1581     printCOFFFileHeader(o);
1582   else if (o->isMachO()) {
1583     printMachOFileHeader(o);
1584     printMachOLoadCommands(o);
1585   } else
1586     report_fatal_error("Invalid/Unsupported object file format");
1587 }
1588 
1589 static void printFirstPrivateFileHeader(const ObjectFile *o) {
1590   if (o->isELF())
1591     printELFFileHeader(o);
1592   else if (o->isCOFF())
1593     printCOFFFileHeader(o);
1594   else if (o->isMachO())
1595     printMachOFileHeader(o);
1596   else
1597     report_fatal_error("Invalid/Unsupported object file format");
1598 }
1599 
1600 static void DumpObject(const ObjectFile *o) {
1601   // Avoid other output when using a raw option.
1602   if (!RawClangAST) {
1603     outs() << '\n';
1604     outs() << o->getFileName()
1605            << ":\tfile format " << o->getFileFormatName() << "\n\n";
1606   }
1607 
1608   if (Disassemble)
1609     DisassembleObject(o, Relocations);
1610   if (Relocations && !Disassemble)
1611     PrintRelocations(o);
1612   if (SectionHeaders)
1613     PrintSectionHeaders(o);
1614   if (SectionContents)
1615     PrintSectionContents(o);
1616   if (SymbolTable)
1617     PrintSymbolTable(o);
1618   if (UnwindInfo)
1619     PrintUnwindInfo(o);
1620   if (PrivateHeaders)
1621     printPrivateFileHeaders(o);
1622   if (FirstPrivateHeader)
1623     printFirstPrivateFileHeader(o);
1624   if (ExportsTrie)
1625     printExportsTrie(o);
1626   if (Rebase)
1627     printRebaseTable(o);
1628   if (Bind)
1629     printBindTable(o);
1630   if (LazyBind)
1631     printLazyBindTable(o);
1632   if (WeakBind)
1633     printWeakBindTable(o);
1634   if (RawClangAST)
1635     printRawClangAST(o);
1636   if (PrintFaultMaps)
1637     printFaultMaps(o);
1638   if (DwarfDumpType != DIDT_Null) {
1639     std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1640     // Dump the complete DWARF structure.
1641     DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1642   }
1643 }
1644 
1645 /// @brief Dump each object file in \a a;
1646 static void DumpArchive(const Archive *a) {
1647   for (auto &ErrorOrChild : a->children()) {
1648     if (std::error_code EC = ErrorOrChild.getError())
1649       report_error(a->getFileName(), EC);
1650     const Archive::Child &C = *ErrorOrChild;
1651     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1652     if (std::error_code EC = ChildOrErr.getError())
1653       if (EC != object_error::invalid_file_type)
1654         report_error(a->getFileName(), EC);
1655     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1656       DumpObject(o);
1657     else
1658       report_error(a->getFileName(), object_error::invalid_file_type);
1659   }
1660 }
1661 
1662 /// @brief Open file and figure out how to dump it.
1663 static void DumpInput(StringRef file) {
1664 
1665   // If we are using the Mach-O specific object file parser, then let it parse
1666   // the file and process the command line options.  So the -arch flags can
1667   // be used to select specific slices, etc.
1668   if (MachOOpt) {
1669     ParseInputMachO(file);
1670     return;
1671   }
1672 
1673   // Attempt to open the binary.
1674   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1675   if (!BinaryOrErr)
1676     report_error(file, errorToErrorCode(BinaryOrErr.takeError()));
1677   Binary &Binary = *BinaryOrErr.get().getBinary();
1678 
1679   if (Archive *a = dyn_cast<Archive>(&Binary))
1680     DumpArchive(a);
1681   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1682     DumpObject(o);
1683   else
1684     report_error(file, object_error::invalid_file_type);
1685 }
1686 
1687 int main(int argc, char **argv) {
1688   // Print a stack trace if we signal out.
1689   sys::PrintStackTraceOnErrorSignal();
1690   PrettyStackTraceProgram X(argc, argv);
1691   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
1692 
1693   // Initialize targets and assembly printers/parsers.
1694   llvm::InitializeAllTargetInfos();
1695   llvm::InitializeAllTargetMCs();
1696   llvm::InitializeAllDisassemblers();
1697 
1698   // Register the target printer for --version.
1699   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1700 
1701   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1702   TripleName = Triple::normalize(TripleName);
1703 
1704   ToolName = argv[0];
1705 
1706   // Defaults to a.out if no filenames specified.
1707   if (InputFilenames.size() == 0)
1708     InputFilenames.push_back("a.out");
1709 
1710   if (DisassembleAll)
1711     Disassemble = true;
1712   if (!Disassemble
1713       && !Relocations
1714       && !SectionHeaders
1715       && !SectionContents
1716       && !SymbolTable
1717       && !UnwindInfo
1718       && !PrivateHeaders
1719       && !FirstPrivateHeader
1720       && !ExportsTrie
1721       && !Rebase
1722       && !Bind
1723       && !LazyBind
1724       && !WeakBind
1725       && !RawClangAST
1726       && !(UniversalHeaders && MachOOpt)
1727       && !(ArchiveHeaders && MachOOpt)
1728       && !(IndirectSymbols && MachOOpt)
1729       && !(DataInCode && MachOOpt)
1730       && !(LinkOptHints && MachOOpt)
1731       && !(InfoPlist && MachOOpt)
1732       && !(DylibsUsed && MachOOpt)
1733       && !(DylibId && MachOOpt)
1734       && !(ObjcMetaData && MachOOpt)
1735       && !(FilterSections.size() != 0 && MachOOpt)
1736       && !PrintFaultMaps
1737       && DwarfDumpType == DIDT_Null) {
1738     cl::PrintHelpMessage();
1739     return 2;
1740   }
1741 
1742   std::for_each(InputFilenames.begin(), InputFilenames.end(),
1743                 DumpInput);
1744 
1745   return EXIT_SUCCESS;
1746 }
1747