xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision 6ce6bfa4357ec172b5bf90959bead55a9a8c825c)
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/StringSet.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/FaultMaps.h"
26 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
27 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
28 #include "llvm/Demangle/Demangle.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
32 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCInstPrinter.h"
35 #include "llvm/MC/MCInstrAnalysis.h"
36 #include "llvm/MC/MCInstrInfo.h"
37 #include "llvm/MC/MCObjectFileInfo.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MC/MCSubtargetInfo.h"
40 #include "llvm/Object/Archive.h"
41 #include "llvm/Object/COFF.h"
42 #include "llvm/Object/COFFImportFile.h"
43 #include "llvm/Object/ELFObjectFile.h"
44 #include "llvm/Object/MachO.h"
45 #include "llvm/Object/MachOUniversal.h"
46 #include "llvm/Object/ObjectFile.h"
47 #include "llvm/Object/Wasm.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/Errc.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/Format.h"
54 #include "llvm/Support/GraphWriter.h"
55 #include "llvm/Support/Host.h"
56 #include "llvm/Support/InitLLVM.h"
57 #include "llvm/Support/MemoryBuffer.h"
58 #include "llvm/Support/SourceMgr.h"
59 #include "llvm/Support/StringSaver.h"
60 #include "llvm/Support/TargetRegistry.h"
61 #include "llvm/Support/TargetSelect.h"
62 #include "llvm/Support/WithColor.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include <algorithm>
65 #include <cctype>
66 #include <cstring>
67 #include <system_error>
68 #include <unordered_map>
69 #include <utility>
70 
71 using namespace llvm;
72 using namespace object;
73 
74 cl::opt<bool>
75     llvm::AllHeaders("all-headers",
76                      cl::desc("Display all available header information"));
77 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
78                                  cl::aliasopt(AllHeaders));
79 
80 static cl::list<std::string>
81 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
82 
83 cl::opt<bool>
84 llvm::Disassemble("disassemble",
85   cl::desc("Display assembler mnemonics for the machine instructions"));
86 static cl::alias
87 Disassembled("d", cl::desc("Alias for --disassemble"),
88              cl::aliasopt(Disassemble));
89 
90 cl::opt<bool>
91 llvm::DisassembleAll("disassemble-all",
92   cl::desc("Display assembler mnemonics for the machine instructions"));
93 static cl::alias
94 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
95              cl::aliasopt(DisassembleAll));
96 
97 cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
98                              cl::init(false));
99 
100 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
101                                cl::aliasopt(llvm::Demangle));
102 
103 static cl::list<std::string>
104 DisassembleFunctions("df",
105                      cl::CommaSeparated,
106                      cl::desc("List of functions to disassemble"));
107 static StringSet<> DisasmFuncsSet;
108 
109 cl::opt<bool>
110 llvm::Relocations("reloc",
111                   cl::desc("Display the relocation entries in the file"));
112 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
113                                   cl::NotHidden,
114                                   cl::aliasopt(llvm::Relocations));
115 
116 cl::opt<bool>
117 llvm::DynamicRelocations("dynamic-reloc",
118   cl::desc("Display the dynamic relocation entries in the file"));
119 static cl::alias
120 DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
121              cl::aliasopt(DynamicRelocations));
122 
123 cl::opt<bool>
124     llvm::SectionContents("full-contents",
125                           cl::desc("Display the content of each section"));
126 static cl::alias SectionContentsShort("s",
127                                       cl::desc("Alias for --full-contents"),
128                                       cl::aliasopt(SectionContents));
129 
130 cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table"));
131 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
132                                   cl::NotHidden,
133                                   cl::aliasopt(llvm::SymbolTable));
134 
135 cl::opt<bool>
136 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
137 
138 cl::opt<bool>
139 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
140 
141 cl::opt<bool>
142 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
143 
144 cl::opt<bool>
145 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
146 
147 cl::opt<bool>
148 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
149 
150 cl::opt<bool>
151 llvm::RawClangAST("raw-clang-ast",
152     cl::desc("Dump the raw binary contents of the clang AST section"));
153 
154 static cl::opt<bool>
155 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
156 static cl::alias
157 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
158 
159 cl::opt<std::string>
160 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
161                                     "see -version for available targets"));
162 
163 cl::opt<std::string>
164 llvm::MCPU("mcpu",
165      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
166      cl::value_desc("cpu-name"),
167      cl::init(""));
168 
169 cl::opt<std::string>
170 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
171                                 "see -version for available targets"));
172 
173 cl::opt<bool>
174 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
175                                                  "headers for each section."));
176 static cl::alias
177 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
178                     cl::aliasopt(SectionHeaders));
179 static cl::alias
180 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
181                       cl::aliasopt(SectionHeaders));
182 
183 cl::list<std::string>
184 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
185                                          "With -macho dump segment,section"));
186 cl::alias
187 static FilterSectionsj("j", cl::desc("Alias for --section"),
188                  cl::aliasopt(llvm::FilterSections));
189 
190 cl::list<std::string>
191 llvm::MAttrs("mattr",
192   cl::CommaSeparated,
193   cl::desc("Target specific attributes"),
194   cl::value_desc("a1,+a2,-a3,..."));
195 
196 cl::opt<bool>
197 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
198                                                  "instructions, do not print "
199                                                  "the instruction bytes."));
200 cl::opt<bool>
201 llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
202 
203 cl::opt<bool>
204 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
205 
206 static cl::alias
207 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
208                 cl::aliasopt(UnwindInfo));
209 
210 cl::opt<bool>
211 llvm::PrivateHeaders("private-headers",
212                      cl::desc("Display format specific file headers"));
213 
214 cl::opt<bool>
215 llvm::FirstPrivateHeader("private-header",
216                          cl::desc("Display only the first format specific file "
217                                   "header"));
218 
219 static cl::alias
220 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
221                     cl::aliasopt(PrivateHeaders));
222 
223 cl::opt<bool> llvm::FileHeaders(
224     "file-headers",
225     cl::desc("Display the contents of the overall file header"));
226 
227 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
228                                   cl::aliasopt(FileHeaders));
229 
230 cl::opt<bool>
231     llvm::ArchiveHeaders("archive-headers",
232                          cl::desc("Display archive header information"));
233 
234 cl::alias
235 ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
236                     cl::aliasopt(ArchiveHeaders));
237 
238 cl::opt<bool>
239     llvm::PrintImmHex("print-imm-hex",
240                       cl::desc("Use hex format for immediate values"));
241 
242 cl::opt<bool> PrintFaultMaps("fault-map-section",
243                              cl::desc("Display contents of faultmap section"));
244 
245 cl::opt<DIDumpType> llvm::DwarfDumpType(
246     "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
247     cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
248 
249 cl::opt<bool> PrintSource(
250     "source",
251     cl::desc(
252         "Display source inlined with disassembly. Implies disassemble object"));
253 
254 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
255                            cl::aliasopt(PrintSource));
256 
257 cl::opt<bool> PrintLines("line-numbers",
258                          cl::desc("Display source line numbers with "
259                                   "disassembly. Implies disassemble object"));
260 
261 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
262                           cl::aliasopt(PrintLines));
263 
264 cl::opt<unsigned long long>
265     StartAddress("start-address", cl::desc("Disassemble beginning at address"),
266                  cl::value_desc("address"), cl::init(0));
267 cl::opt<unsigned long long>
268     StopAddress("stop-address",
269                 cl::desc("Stop disassembly at address"),
270                 cl::value_desc("address"), cl::init(UINT64_MAX));
271 
272 cl::opt<bool> DisassembleZeroes(
273                 "disassemble-zeroes",
274                 cl::desc("Do not skip blocks of zeroes when disassembling"));
275 cl::alias DisassembleZeroesShort("z",
276                                  cl::desc("Alias for --disassemble-zeroes"),
277                                  cl::aliasopt(DisassembleZeroes));
278 
279 static StringRef ToolName;
280 
281 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
282 
283 namespace {
284 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
285 
286 class SectionFilterIterator {
287 public:
288   SectionFilterIterator(FilterPredicate P,
289                         llvm::object::section_iterator const &I,
290                         llvm::object::section_iterator const &E)
291       : Predicate(std::move(P)), Iterator(I), End(E) {
292     ScanPredicate();
293   }
294   const llvm::object::SectionRef &operator*() const { return *Iterator; }
295   SectionFilterIterator &operator++() {
296     ++Iterator;
297     ScanPredicate();
298     return *this;
299   }
300   bool operator!=(SectionFilterIterator const &Other) const {
301     return Iterator != Other.Iterator;
302   }
303 
304 private:
305   void ScanPredicate() {
306     while (Iterator != End && !Predicate(*Iterator)) {
307       ++Iterator;
308     }
309   }
310   FilterPredicate Predicate;
311   llvm::object::section_iterator Iterator;
312   llvm::object::section_iterator End;
313 };
314 
315 class SectionFilter {
316 public:
317   SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
318       : Predicate(std::move(P)), Object(O) {}
319   SectionFilterIterator begin() {
320     return SectionFilterIterator(Predicate, Object.section_begin(),
321                                  Object.section_end());
322   }
323   SectionFilterIterator end() {
324     return SectionFilterIterator(Predicate, Object.section_end(),
325                                  Object.section_end());
326   }
327 
328 private:
329   FilterPredicate Predicate;
330   llvm::object::ObjectFile const &Object;
331 };
332 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
333   return SectionFilter(
334       [](llvm::object::SectionRef const &S) {
335         if (FilterSections.empty())
336           return true;
337         llvm::StringRef String;
338         std::error_code error = S.getName(String);
339         if (error)
340           return false;
341         return is_contained(FilterSections, String);
342       },
343       O);
344 }
345 }
346 
347 void llvm::error(std::error_code EC) {
348   if (!EC)
349     return;
350   WithColor::error(errs(), ToolName)
351       << "reading file: " << EC.message() << ".\n";
352   errs().flush();
353   exit(1);
354 }
355 
356 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
357   WithColor::error(errs(), ToolName) << Message << ".\n";
358   errs().flush();
359   exit(1);
360 }
361 
362 void llvm::warn(StringRef Message) {
363   WithColor::warning(errs(), ToolName) << Message << ".\n";
364   errs().flush();
365 }
366 
367 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
368                                                 Twine Message) {
369   WithColor::error(errs(), ToolName)
370       << "'" << File << "': " << Message << ".\n";
371   exit(1);
372 }
373 
374 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
375                                                 std::error_code EC) {
376   assert(EC);
377   WithColor::error(errs(), ToolName)
378       << "'" << File << "': " << EC.message() << ".\n";
379   exit(1);
380 }
381 
382 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
383                                                 llvm::Error E) {
384   assert(E);
385   std::string Buf;
386   raw_string_ostream OS(Buf);
387   logAllUnhandledErrors(std::move(E), OS);
388   OS.flush();
389   WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
390   exit(1);
391 }
392 
393 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
394                                                 StringRef FileName,
395                                                 llvm::Error E,
396                                                 StringRef ArchitectureName) {
397   assert(E);
398   WithColor::error(errs(), ToolName);
399   if (ArchiveName != "")
400     errs() << ArchiveName << "(" << FileName << ")";
401   else
402     errs() << "'" << FileName << "'";
403   if (!ArchitectureName.empty())
404     errs() << " (for architecture " << ArchitectureName << ")";
405   std::string Buf;
406   raw_string_ostream OS(Buf);
407   logAllUnhandledErrors(std::move(E), OS);
408   OS.flush();
409   errs() << ": " << Buf;
410   exit(1);
411 }
412 
413 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
414                                                 const object::Archive::Child &C,
415                                                 llvm::Error E,
416                                                 StringRef ArchitectureName) {
417   Expected<StringRef> NameOrErr = C.getName();
418   // TODO: if we have a error getting the name then it would be nice to print
419   // the index of which archive member this is and or its offset in the
420   // archive instead of "???" as the name.
421   if (!NameOrErr) {
422     consumeError(NameOrErr.takeError());
423     llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
424   } else
425     llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
426                        ArchitectureName);
427 }
428 
429 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
430   // Figure out the target triple.
431   llvm::Triple TheTriple("unknown-unknown-unknown");
432   if (TripleName.empty()) {
433     if (Obj)
434       TheTriple = Obj->makeTriple();
435   } else {
436     TheTriple.setTriple(Triple::normalize(TripleName));
437 
438     // Use the triple, but also try to combine with ARM build attributes.
439     if (Obj) {
440       auto Arch = Obj->getArch();
441       if (Arch == Triple::arm || Arch == Triple::armeb)
442         Obj->setARMSubArch(TheTriple);
443     }
444   }
445 
446   // Get the target specific parser.
447   std::string Error;
448   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
449                                                          Error);
450   if (!TheTarget) {
451     if (Obj)
452       report_error(Obj->getFileName(), "can't find target: " + Error);
453     else
454       error("can't find target: " + Error);
455   }
456 
457   // Update the triple name and return the found target.
458   TripleName = TheTriple.getTriple();
459   return TheTarget;
460 }
461 
462 bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) {
463   return A.getOffset() < B.getOffset();
464 }
465 
466 static std::string demangle(StringRef Name) {
467   char *Demangled = nullptr;
468   if (Name.startswith("_Z"))
469     Demangled = itaniumDemangle(Name.data(), Demangled, nullptr, nullptr);
470   else if (Name.startswith("?"))
471     Demangled = microsoftDemangle(Name.data(), Demangled, nullptr, nullptr);
472 
473   if (!Demangled)
474     return Name;
475 
476   std::string Ret = Demangled;
477   free(Demangled);
478   return Ret;
479 }
480 
481 template <class ELFT>
482 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
483                                                 const RelocationRef &RelRef,
484                                                 SmallVectorImpl<char> &Result) {
485   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
486   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
487   typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
488 
489   const ELFFile<ELFT> &EF = *Obj->getELFFile();
490   DataRefImpl Rel = RelRef.getRawDataRefImpl();
491   auto SecOrErr = EF.getSection(Rel.d.a);
492   if (!SecOrErr)
493     return errorToErrorCode(SecOrErr.takeError());
494 
495   int64_t Addend = 0;
496   // If there is no Symbol associated with the relocation, we set the undef
497   // boolean value to 'true'. This will prevent us from calling functions that
498   // requires the relocation to be associated with a symbol.
499   //
500   // In SHT_REL case we would need to read the addend from section data.
501   // GNU objdump does not do that and we just follow for simplicity atm.
502   bool Undef = false;
503   if ((*SecOrErr)->sh_type == ELF::SHT_RELA) {
504     const Elf_Rela *ERela = Obj->getRela(Rel);
505     Addend = ERela->r_addend;
506     Undef = ERela->getSymbol(false) == 0;
507   } else if ((*SecOrErr)->sh_type != ELF::SHT_REL) {
508     return object_error::parse_failed;
509   }
510 
511   // Default scheme is to print Target, as well as "+ <addend>" for nonzero
512   // addend. Should be acceptable for all normal purposes.
513   std::string FmtBuf;
514   raw_string_ostream Fmt(FmtBuf);
515 
516   if (!Undef) {
517     symbol_iterator SI = RelRef.getSymbol();
518     const Elf_Sym *Sym = Obj->getSymbol(SI->getRawDataRefImpl());
519     if (Sym->getType() == ELF::STT_SECTION) {
520       Expected<section_iterator> SymSI = SI->getSection();
521       if (!SymSI)
522         return errorToErrorCode(SymSI.takeError());
523       const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
524       auto SecName = EF.getSectionName(SymSec);
525       if (!SecName)
526         return errorToErrorCode(SecName.takeError());
527       Fmt << *SecName;
528     } else {
529       Expected<StringRef> SymName = SI->getName();
530       if (!SymName)
531         return errorToErrorCode(SymName.takeError());
532       if (Demangle)
533         Fmt << demangle(*SymName);
534       else
535         Fmt << *SymName;
536     }
537   } else {
538     Fmt << "*ABS*";
539   }
540 
541   if (Addend != 0)
542     Fmt << (Addend < 0 ? "" : "+") << Addend;
543   Fmt.flush();
544   Result.append(FmtBuf.begin(), FmtBuf.end());
545   return std::error_code();
546 }
547 
548 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
549                                                 const RelocationRef &Rel,
550                                                 SmallVectorImpl<char> &Result) {
551   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
552     return getRelocationValueString(ELF32LE, Rel, Result);
553   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
554     return getRelocationValueString(ELF64LE, Rel, Result);
555   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
556     return getRelocationValueString(ELF32BE, Rel, Result);
557   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
558   return getRelocationValueString(ELF64BE, Rel, Result);
559 }
560 
561 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
562                                                 const RelocationRef &Rel,
563                                                 SmallVectorImpl<char> &Result) {
564   symbol_iterator SymI = Rel.getSymbol();
565   Expected<StringRef> SymNameOrErr = SymI->getName();
566   if (!SymNameOrErr)
567     return errorToErrorCode(SymNameOrErr.takeError());
568   StringRef SymName = *SymNameOrErr;
569   Result.append(SymName.begin(), SymName.end());
570   return std::error_code();
571 }
572 
573 static void printRelocationTargetName(const MachOObjectFile *O,
574                                       const MachO::any_relocation_info &RE,
575                                       raw_string_ostream &Fmt) {
576   // Target of a scattered relocation is an address.  In the interest of
577   // generating pretty output, scan through the symbol table looking for a
578   // symbol that aligns with that address.  If we find one, print it.
579   // Otherwise, we just print the hex address of the target.
580   if (O->isRelocationScattered(RE)) {
581     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
582 
583     for (const SymbolRef &Symbol : O->symbols()) {
584       Expected<uint64_t> Addr = Symbol.getAddress();
585       if (!Addr)
586         report_error(O->getFileName(), Addr.takeError());
587       if (*Addr != Val)
588         continue;
589       Expected<StringRef> Name = Symbol.getName();
590       if (!Name)
591         report_error(O->getFileName(), Name.takeError());
592       Fmt << *Name;
593       return;
594     }
595 
596     // If we couldn't find a symbol that this relocation refers to, try
597     // to find a section beginning instead.
598     for (const SectionRef &Section : ToolSectionFilter(*O)) {
599       std::error_code ec;
600 
601       StringRef Name;
602       uint64_t Addr = Section.getAddress();
603       if (Addr != Val)
604         continue;
605       if ((ec = Section.getName(Name)))
606         report_error(O->getFileName(), ec);
607       Fmt << Name;
608       return;
609     }
610 
611     Fmt << format("0x%x", Val);
612     return;
613   }
614 
615   StringRef S;
616   bool isExtern = O->getPlainRelocationExternal(RE);
617   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
618 
619   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
620     Fmt << format("0x%0" PRIx64, Val);
621     return;
622   }
623 
624   if (isExtern) {
625     symbol_iterator SI = O->symbol_begin();
626     advance(SI, Val);
627     Expected<StringRef> SOrErr = SI->getName();
628     if (!SOrErr)
629       report_error(O->getFileName(), SOrErr.takeError());
630     S = *SOrErr;
631   } else {
632     section_iterator SI = O->section_begin();
633     // Adjust for the fact that sections are 1-indexed.
634     if (Val == 0) {
635       Fmt << "0 (?,?)";
636       return;
637     }
638     uint32_t I = Val - 1;
639     while (I != 0 && SI != O->section_end()) {
640       --I;
641       advance(SI, 1);
642     }
643     if (SI == O->section_end())
644       Fmt << Val << " (?,?)";
645     else
646       SI->getName(S);
647   }
648 
649   Fmt << S;
650 }
651 
652 static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
653                                                 const RelocationRef &RelRef,
654                                                 SmallVectorImpl<char> &Result) {
655   const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
656   symbol_iterator SI = RelRef.getSymbol();
657   std::string FmtBuf;
658   raw_string_ostream Fmt(FmtBuf);
659   if (SI == Obj->symbol_end()) {
660     // Not all wasm relocations have symbols associated with them.
661     // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
662     Fmt << Rel.Index;
663   } else {
664     Expected<StringRef> SymNameOrErr = SI->getName();
665     if (!SymNameOrErr)
666       return errorToErrorCode(SymNameOrErr.takeError());
667     StringRef SymName = *SymNameOrErr;
668     Result.append(SymName.begin(), SymName.end());
669   }
670   Fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
671   Fmt.flush();
672   Result.append(FmtBuf.begin(), FmtBuf.end());
673   return std::error_code();
674 }
675 
676 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
677                                                 const RelocationRef &RelRef,
678                                                 SmallVectorImpl<char> &Result) {
679   DataRefImpl Rel = RelRef.getRawDataRefImpl();
680   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
681 
682   unsigned Arch = Obj->getArch();
683 
684   std::string FmtBuf;
685   raw_string_ostream Fmt(FmtBuf);
686   unsigned Type = Obj->getAnyRelocationType(RE);
687   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
688 
689   // Determine any addends that should be displayed with the relocation.
690   // These require decoding the relocation type, which is triple-specific.
691 
692   // X86_64 has entirely custom relocation types.
693   if (Arch == Triple::x86_64) {
694     switch (Type) {
695     case MachO::X86_64_RELOC_GOT_LOAD:
696     case MachO::X86_64_RELOC_GOT: {
697       printRelocationTargetName(Obj, RE, Fmt);
698       Fmt << "@GOT";
699       if (IsPCRel)
700         Fmt << "PCREL";
701       break;
702     }
703     case MachO::X86_64_RELOC_SUBTRACTOR: {
704       DataRefImpl RelNext = Rel;
705       Obj->moveRelocationNext(RelNext);
706       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
707 
708       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
709       // X86_64_RELOC_UNSIGNED.
710       // NOTE: Scattered relocations don't exist on x86_64.
711       unsigned RType = Obj->getAnyRelocationType(RENext);
712       if (RType != MachO::X86_64_RELOC_UNSIGNED)
713         report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
714                      "X86_64_RELOC_SUBTRACTOR.");
715 
716       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
717       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
718       printRelocationTargetName(Obj, RENext, Fmt);
719       Fmt << "-";
720       printRelocationTargetName(Obj, RE, Fmt);
721       break;
722     }
723     case MachO::X86_64_RELOC_TLV:
724       printRelocationTargetName(Obj, RE, Fmt);
725       Fmt << "@TLV";
726       if (IsPCRel)
727         Fmt << "P";
728       break;
729     case MachO::X86_64_RELOC_SIGNED_1:
730       printRelocationTargetName(Obj, RE, Fmt);
731       Fmt << "-1";
732       break;
733     case MachO::X86_64_RELOC_SIGNED_2:
734       printRelocationTargetName(Obj, RE, Fmt);
735       Fmt << "-2";
736       break;
737     case MachO::X86_64_RELOC_SIGNED_4:
738       printRelocationTargetName(Obj, RE, Fmt);
739       Fmt << "-4";
740       break;
741     default:
742       printRelocationTargetName(Obj, RE, Fmt);
743       break;
744     }
745     // X86 and ARM share some relocation types in common.
746   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
747              Arch == Triple::ppc) {
748     // Generic relocation types...
749     switch (Type) {
750     case MachO::GENERIC_RELOC_PAIR: // prints no info
751       return std::error_code();
752     case MachO::GENERIC_RELOC_SECTDIFF: {
753       DataRefImpl RelNext = Rel;
754       Obj->moveRelocationNext(RelNext);
755       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
756 
757       // X86 sect diff's must be followed by a relocation of type
758       // GENERIC_RELOC_PAIR.
759       unsigned RType = Obj->getAnyRelocationType(RENext);
760 
761       if (RType != MachO::GENERIC_RELOC_PAIR)
762         report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
763                      "GENERIC_RELOC_SECTDIFF.");
764 
765       printRelocationTargetName(Obj, RE, Fmt);
766       Fmt << "-";
767       printRelocationTargetName(Obj, RENext, Fmt);
768       break;
769     }
770     }
771 
772     if (Arch == Triple::x86 || Arch == Triple::ppc) {
773       switch (Type) {
774       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
775         DataRefImpl RelNext = Rel;
776         Obj->moveRelocationNext(RelNext);
777         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
778 
779         // X86 sect diff's must be followed by a relocation of type
780         // GENERIC_RELOC_PAIR.
781         unsigned RType = Obj->getAnyRelocationType(RENext);
782         if (RType != MachO::GENERIC_RELOC_PAIR)
783           report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
784                        "GENERIC_RELOC_LOCAL_SECTDIFF.");
785 
786         printRelocationTargetName(Obj, RE, Fmt);
787         Fmt << "-";
788         printRelocationTargetName(Obj, RENext, Fmt);
789         break;
790       }
791       case MachO::GENERIC_RELOC_TLV: {
792         printRelocationTargetName(Obj, RE, Fmt);
793         Fmt << "@TLV";
794         if (IsPCRel)
795           Fmt << "P";
796         break;
797       }
798       default:
799         printRelocationTargetName(Obj, RE, Fmt);
800       }
801     } else { // ARM-specific relocations
802       switch (Type) {
803       case MachO::ARM_RELOC_HALF:
804       case MachO::ARM_RELOC_HALF_SECTDIFF: {
805         // Half relocations steal a bit from the length field to encode
806         // whether this is an upper16 or a lower16 relocation.
807         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
808 
809         if (isUpper)
810           Fmt << ":upper16:(";
811         else
812           Fmt << ":lower16:(";
813         printRelocationTargetName(Obj, RE, Fmt);
814 
815         DataRefImpl RelNext = Rel;
816         Obj->moveRelocationNext(RelNext);
817         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
818 
819         // ARM half relocs must be followed by a relocation of type
820         // ARM_RELOC_PAIR.
821         unsigned RType = Obj->getAnyRelocationType(RENext);
822         if (RType != MachO::ARM_RELOC_PAIR)
823           report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
824                        "ARM_RELOC_HALF");
825 
826         // NOTE: The half of the target virtual address is stashed in the
827         // address field of the secondary relocation, but we can't reverse
828         // engineer the constant offset from it without decoding the movw/movt
829         // instruction to find the other half in its immediate field.
830 
831         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
832         // symbol/section pointer of the follow-on relocation.
833         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
834           Fmt << "-";
835           printRelocationTargetName(Obj, RENext, Fmt);
836         }
837 
838         Fmt << ")";
839         break;
840       }
841       default: { printRelocationTargetName(Obj, RE, Fmt); }
842       }
843     }
844   } else
845     printRelocationTargetName(Obj, RE, Fmt);
846 
847   Fmt.flush();
848   Result.append(FmtBuf.begin(), FmtBuf.end());
849   return std::error_code();
850 }
851 
852 static std::error_code getRelocationValueString(const RelocationRef &Rel,
853                                                 SmallVectorImpl<char> &Result) {
854   const ObjectFile *Obj = Rel.getObject();
855   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
856     return getRelocationValueString(ELF, Rel, Result);
857   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
858     return getRelocationValueString(COFF, Rel, Result);
859   if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
860     return getRelocationValueString(Wasm, Rel, Result);
861   if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
862     return getRelocationValueString(MachO, Rel, Result);
863   llvm_unreachable("unknown object file format");
864 }
865 
866 /// Indicates whether this relocation should hidden when listing
867 /// relocations, usually because it is the trailing part of a multipart
868 /// relocation that will be printed as part of the leading relocation.
869 static bool getHidden(RelocationRef RelRef) {
870   auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
871   if (!MachO)
872     return false;
873 
874   unsigned Arch = MachO->getArch();
875   DataRefImpl Rel = RelRef.getRawDataRefImpl();
876   uint64_t Type = MachO->getRelocationType(Rel);
877 
878   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
879   // is always hidden.
880   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
881     return Type == MachO::GENERIC_RELOC_PAIR;
882 
883   if (Arch == Triple::x86_64) {
884     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
885     // an X86_64_RELOC_SUBTRACTOR.
886     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
887       DataRefImpl RelPrev = Rel;
888       RelPrev.d.a--;
889       uint64_t PrevType = MachO->getRelocationType(RelPrev);
890       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
891         return true;
892     }
893   }
894 
895   return false;
896 }
897 
898 namespace {
899 class SourcePrinter {
900 protected:
901   DILineInfo OldLineInfo;
902   const ObjectFile *Obj = nullptr;
903   std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
904   // File name to file contents of source
905   std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
906   // Mark the line endings of the cached source
907   std::unordered_map<std::string, std::vector<StringRef>> LineCache;
908 
909 private:
910   bool cacheSource(const DILineInfo& LineInfoFile);
911 
912 public:
913   SourcePrinter() = default;
914   SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
915     symbolize::LLVMSymbolizer::Options SymbolizerOpts(
916         DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
917         DefaultArch);
918     Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
919   }
920   virtual ~SourcePrinter() = default;
921   virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
922                                StringRef Delimiter = "; ");
923 };
924 
925 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
926   std::unique_ptr<MemoryBuffer> Buffer;
927   if (LineInfo.Source) {
928     Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
929   } else {
930     auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
931     if (!BufferOrError)
932       return false;
933     Buffer = std::move(*BufferOrError);
934   }
935   // Chomp the file to get lines
936   size_t BufferSize = Buffer->getBufferSize();
937   const char *BufferStart = Buffer->getBufferStart();
938   for (const char *Start = BufferStart, *End = BufferStart;
939        End < BufferStart + BufferSize; End++)
940     if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
941         (*End == '\r' && *(End + 1) == '\n')) {
942       LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
943       if (*End == '\r')
944         End++;
945       Start = End + 1;
946     }
947   SourceCache[LineInfo.FileName] = std::move(Buffer);
948   return true;
949 }
950 
951 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
952                                     StringRef Delimiter) {
953   if (!Symbolizer)
954     return;
955   DILineInfo LineInfo = DILineInfo();
956   auto ExpectecLineInfo =
957       Symbolizer->symbolizeCode(Obj->getFileName(), Address);
958   if (!ExpectecLineInfo)
959     consumeError(ExpectecLineInfo.takeError());
960   else
961     LineInfo = *ExpectecLineInfo;
962 
963   if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
964       LineInfo.Line == 0)
965     return;
966 
967   if (PrintLines)
968     OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
969   if (PrintSource) {
970     if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
971       if (!cacheSource(LineInfo))
972         return;
973     auto FileBuffer = SourceCache.find(LineInfo.FileName);
974     if (FileBuffer != SourceCache.end()) {
975       auto LineBuffer = LineCache.find(LineInfo.FileName);
976       if (LineBuffer != LineCache.end()) {
977         if (LineInfo.Line > LineBuffer->second.size())
978           return;
979         // Vector begins at 0, line numbers are non-zero
980         OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
981            << "\n";
982       }
983     }
984   }
985   OldLineInfo = LineInfo;
986 }
987 
988 static bool isArmElf(const ObjectFile *Obj) {
989   return (Obj->isELF() &&
990           (Obj->getArch() == Triple::aarch64 ||
991            Obj->getArch() == Triple::aarch64_be ||
992            Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
993            Obj->getArch() == Triple::thumb ||
994            Obj->getArch() == Triple::thumbeb));
995 }
996 
997 class PrettyPrinter {
998 public:
999   virtual ~PrettyPrinter() = default;
1000   virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
1001                          ArrayRef<uint8_t> Bytes, uint64_t Address,
1002                          raw_ostream &OS, StringRef Annot,
1003                          MCSubtargetInfo const &STI, SourcePrinter *SP,
1004                          std::vector<RelocationRef> *Rels = nullptr) {
1005     if (SP && (PrintSource || PrintLines))
1006       SP->printSourceLine(OS, Address);
1007     if (!NoLeadingAddr)
1008       OS << format("%8" PRIx64 ":", Address);
1009     if (!NoShowRawInsn) {
1010       OS << "\t";
1011       dumpBytes(Bytes, OS);
1012     }
1013     if (MI)
1014       IP.printInst(MI, OS, "", STI);
1015     else
1016       OS << " <unknown>";
1017   }
1018 };
1019 PrettyPrinter PrettyPrinterInst;
1020 class HexagonPrettyPrinter : public PrettyPrinter {
1021 public:
1022   void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1023                  raw_ostream &OS) {
1024     uint32_t opcode =
1025       (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1026     if (!NoLeadingAddr)
1027       OS << format("%8" PRIx64 ":", Address);
1028     if (!NoShowRawInsn) {
1029       OS << "\t";
1030       dumpBytes(Bytes.slice(0, 4), OS);
1031       OS << format("%08" PRIx32, opcode);
1032     }
1033   }
1034   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1035                  uint64_t Address, raw_ostream &OS, StringRef Annot,
1036                  MCSubtargetInfo const &STI, SourcePrinter *SP,
1037                  std::vector<RelocationRef> *Rels) override {
1038     if (SP && (PrintSource || PrintLines))
1039       SP->printSourceLine(OS, Address, "");
1040     if (!MI) {
1041       printLead(Bytes, Address, OS);
1042       OS << " <unknown>";
1043       return;
1044     }
1045     std::string Buffer;
1046     {
1047       raw_string_ostream TempStream(Buffer);
1048       IP.printInst(MI, TempStream, "", STI);
1049     }
1050     StringRef Contents(Buffer);
1051     // Split off bundle attributes
1052     auto PacketBundle = Contents.rsplit('\n');
1053     // Split off first instruction from the rest
1054     auto HeadTail = PacketBundle.first.split('\n');
1055     auto Preamble = " { ";
1056     auto Separator = "";
1057     StringRef Fmt = "\t\t\t%08" PRIx64 ":  ";
1058     std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
1059     std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
1060 
1061     // Hexagon's packets require relocations to be inline rather than
1062     // clustered at the end of the packet.
1063     auto PrintReloc = [&]() -> void {
1064       while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) {
1065         if (RelCur->getOffset() == Address) {
1066           SmallString<16> Name;
1067           SmallString<32> Val;
1068           RelCur->getTypeName(Name);
1069           error(getRelocationValueString(*RelCur, Val));
1070           OS << Separator << format(Fmt.data(), Address) << Name << "\t" << Val
1071                 << "\n";
1072           return;
1073         }
1074         ++RelCur;
1075       }
1076     };
1077 
1078     while (!HeadTail.first.empty()) {
1079       OS << Separator;
1080       Separator = "\n";
1081       if (SP && (PrintSource || PrintLines))
1082         SP->printSourceLine(OS, Address, "");
1083       printLead(Bytes, Address, OS);
1084       OS << Preamble;
1085       Preamble = "   ";
1086       StringRef Inst;
1087       auto Duplex = HeadTail.first.split('\v');
1088       if (!Duplex.second.empty()) {
1089         OS << Duplex.first;
1090         OS << "; ";
1091         Inst = Duplex.second;
1092       }
1093       else
1094         Inst = HeadTail.first;
1095       OS << Inst;
1096       HeadTail = HeadTail.second.split('\n');
1097       if (HeadTail.first.empty())
1098         OS << " } " << PacketBundle.second;
1099       PrintReloc();
1100       Bytes = Bytes.slice(4);
1101       Address += 4;
1102     }
1103   }
1104 };
1105 HexagonPrettyPrinter HexagonPrettyPrinterInst;
1106 
1107 class AMDGCNPrettyPrinter : public PrettyPrinter {
1108 public:
1109   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1110                  uint64_t Address, raw_ostream &OS, StringRef Annot,
1111                  MCSubtargetInfo const &STI, SourcePrinter *SP,
1112                  std::vector<RelocationRef> *Rels) override {
1113     if (SP && (PrintSource || PrintLines))
1114       SP->printSourceLine(OS, Address);
1115 
1116     typedef support::ulittle32_t U32;
1117 
1118     if (MI) {
1119       SmallString<40> InstStr;
1120       raw_svector_ostream IS(InstStr);
1121 
1122       IP.printInst(MI, IS, "", STI);
1123 
1124       OS << left_justify(IS.str(), 60);
1125     } else {
1126       // an unrecognized encoding - this is probably data so represent it
1127       // using the .long directive, or .byte directive if fewer than 4 bytes
1128       // remaining
1129       if (Bytes.size() >= 4) {
1130         OS << format("\t.long 0x%08" PRIx32 " ",
1131                      static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1132         OS.indent(42);
1133       } else {
1134           OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1135           for (unsigned int i = 1; i < Bytes.size(); i++)
1136             OS << format(", 0x%02" PRIx8, Bytes[i]);
1137           OS.indent(55 - (6 * Bytes.size()));
1138       }
1139     }
1140 
1141     OS << format("// %012" PRIX64 ": ", Address);
1142     if (Bytes.size() >=4) {
1143       for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1144                                  Bytes.size() / sizeof(U32)))
1145         // D should be explicitly casted to uint32_t here as it is passed
1146         // by format to snprintf as vararg.
1147         OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1148     } else {
1149       for (unsigned int i = 0; i < Bytes.size(); i++)
1150         OS << format("%02" PRIX8 " ", Bytes[i]);
1151     }
1152 
1153     if (!Annot.empty())
1154       OS << "// " << Annot;
1155   }
1156 };
1157 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1158 
1159 class BPFPrettyPrinter : public PrettyPrinter {
1160 public:
1161   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1162                  uint64_t Address, raw_ostream &OS, StringRef Annot,
1163                  MCSubtargetInfo const &STI, SourcePrinter *SP,
1164                  std::vector<RelocationRef> *Rels) override {
1165     if (SP && (PrintSource || PrintLines))
1166       SP->printSourceLine(OS, Address);
1167     if (!NoLeadingAddr)
1168       OS << format("%8" PRId64 ":", Address / 8);
1169     if (!NoShowRawInsn) {
1170       OS << "\t";
1171       dumpBytes(Bytes, OS);
1172     }
1173     if (MI)
1174       IP.printInst(MI, OS, "", STI);
1175     else
1176       OS << " <unknown>";
1177   }
1178 };
1179 BPFPrettyPrinter BPFPrettyPrinterInst;
1180 
1181 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1182   switch(Triple.getArch()) {
1183   default:
1184     return PrettyPrinterInst;
1185   case Triple::hexagon:
1186     return HexagonPrettyPrinterInst;
1187   case Triple::amdgcn:
1188     return AMDGCNPrettyPrinterInst;
1189   case Triple::bpfel:
1190   case Triple::bpfeb:
1191     return BPFPrettyPrinterInst;
1192   }
1193 }
1194 }
1195 
1196 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1197   assert(Obj->isELF());
1198   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1199     return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1200   if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1201     return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1202   if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1203     return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1204   if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1205     return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1206   llvm_unreachable("Unsupported binary format");
1207 }
1208 
1209 template <class ELFT> static void
1210 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1211                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1212   for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1213     uint8_t SymbolType = Symbol.getELFType();
1214     if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1215       continue;
1216 
1217     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1218     if (!AddressOrErr)
1219       report_error(Obj->getFileName(), AddressOrErr.takeError());
1220 
1221     Expected<StringRef> Name = Symbol.getName();
1222     if (!Name)
1223       report_error(Obj->getFileName(), Name.takeError());
1224     if (Name->empty())
1225       continue;
1226 
1227     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1228     if (!SectionOrErr)
1229       report_error(Obj->getFileName(), SectionOrErr.takeError());
1230     section_iterator SecI = *SectionOrErr;
1231     if (SecI == Obj->section_end())
1232       continue;
1233 
1234     AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType);
1235   }
1236 }
1237 
1238 static void
1239 addDynamicElfSymbols(const ObjectFile *Obj,
1240                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1241   assert(Obj->isELF());
1242   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1243     addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1244   else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1245     addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1246   else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1247     addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1248   else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1249     addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1250   else
1251     llvm_unreachable("Unsupported binary format");
1252 }
1253 
1254 static void addPltEntries(const ObjectFile *Obj,
1255                           std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1256                           StringSaver &Saver) {
1257   Optional<SectionRef> Plt = None;
1258   for (const SectionRef &Section : Obj->sections()) {
1259     StringRef Name;
1260     if (Section.getName(Name))
1261       continue;
1262     if (Name == ".plt")
1263       Plt = Section;
1264   }
1265   if (!Plt)
1266     return;
1267   if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1268     for (auto PltEntry : ElfObj->getPltAddresses()) {
1269       SymbolRef Symbol(PltEntry.first, ElfObj);
1270       uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1271 
1272       Expected<StringRef> NameOrErr = Symbol.getName();
1273       if (!NameOrErr)
1274         report_error(Obj->getFileName(), NameOrErr.takeError());
1275       if (NameOrErr->empty())
1276         continue;
1277       StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1278 
1279       AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1280     }
1281   }
1282 }
1283 
1284 // Normally the disassembly output will skip blocks of zeroes. This function
1285 // returns the number of zero bytes that can be skipped when dumping the
1286 // disassembly of the instructions in Buf.
1287 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
1288   // When -z or --disassemble-zeroes are given we always dissasemble them.
1289   if (DisassembleZeroes)
1290     return 0;
1291 
1292   // Find the number of leading zeroes.
1293   size_t N = 0;
1294   while (N < Buf.size() && !Buf[N])
1295     ++N;
1296 
1297   // We may want to skip blocks of zero bytes, but unless we see
1298   // at least 8 of them in a row.
1299   if (N < 8)
1300     return 0;
1301 
1302   // We skip zeroes in multiples of 4 because do not want to truncate an
1303   // instruction if it starts with a zero byte.
1304   return N & ~0x3;
1305 }
1306 
1307 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1308   if (StartAddress > StopAddress)
1309     error("Start address should be less than stop address");
1310 
1311   const Target *TheTarget = getTarget(Obj);
1312 
1313   // Package up features to be passed to target/subtarget
1314   SubtargetFeatures Features = Obj->getFeatures();
1315   if (!MAttrs.empty())
1316     for (unsigned I = 0; I != MAttrs.size(); ++I)
1317       Features.AddFeature(MAttrs[I]);
1318 
1319   std::unique_ptr<const MCRegisterInfo> MRI(
1320       TheTarget->createMCRegInfo(TripleName));
1321   if (!MRI)
1322     report_error(Obj->getFileName(), "no register info for target " +
1323                  TripleName);
1324 
1325   // Set up disassembler.
1326   std::unique_ptr<const MCAsmInfo> AsmInfo(
1327       TheTarget->createMCAsmInfo(*MRI, TripleName));
1328   if (!AsmInfo)
1329     report_error(Obj->getFileName(), "no assembly info for target " +
1330                  TripleName);
1331   std::unique_ptr<const MCSubtargetInfo> STI(
1332       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1333   if (!STI)
1334     report_error(Obj->getFileName(), "no subtarget info for target " +
1335                  TripleName);
1336   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1337   if (!MII)
1338     report_error(Obj->getFileName(), "no instruction info for target " +
1339                  TripleName);
1340   MCObjectFileInfo MOFI;
1341   MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1342   // FIXME: for now initialize MCObjectFileInfo with default values
1343   MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1344 
1345   std::unique_ptr<MCDisassembler> DisAsm(
1346     TheTarget->createMCDisassembler(*STI, Ctx));
1347   if (!DisAsm)
1348     report_error(Obj->getFileName(), "no disassembler for target " +
1349                  TripleName);
1350 
1351   std::unique_ptr<const MCInstrAnalysis> MIA(
1352       TheTarget->createMCInstrAnalysis(MII.get()));
1353 
1354   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1355   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1356       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1357   if (!IP)
1358     report_error(Obj->getFileName(), "no instruction printer for target " +
1359                  TripleName);
1360   IP->setPrintImmHex(PrintImmHex);
1361   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1362 
1363   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
1364                                                  "\t\t\t%08" PRIx64 ":  ";
1365 
1366   SourcePrinter SP(Obj, TheTarget->getName());
1367 
1368   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1369   // in RelocSecs contain the relocations for section S.
1370   std::error_code EC;
1371   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1372   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1373     section_iterator Sec2 = Section.getRelocatedSection();
1374     if (Sec2 != Obj->section_end())
1375       SectionRelocMap[*Sec2].push_back(Section);
1376   }
1377 
1378   // Create a mapping from virtual address to symbol name.  This is used to
1379   // pretty print the symbols while disassembling.
1380   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1381   SectionSymbolsTy AbsoluteSymbols;
1382   for (const SymbolRef &Symbol : Obj->symbols()) {
1383     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1384     if (!AddressOrErr)
1385       report_error(Obj->getFileName(), AddressOrErr.takeError());
1386     uint64_t Address = *AddressOrErr;
1387 
1388     Expected<StringRef> Name = Symbol.getName();
1389     if (!Name)
1390       report_error(Obj->getFileName(), Name.takeError());
1391     if (Name->empty())
1392       continue;
1393 
1394     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1395     if (!SectionOrErr)
1396       report_error(Obj->getFileName(), SectionOrErr.takeError());
1397 
1398     uint8_t SymbolType = ELF::STT_NOTYPE;
1399     if (Obj->isELF())
1400       SymbolType = getElfSymbolType(Obj, Symbol);
1401 
1402     section_iterator SecI = *SectionOrErr;
1403     if (SecI != Obj->section_end())
1404       AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1405     else
1406       AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1407 
1408 
1409   }
1410   if (AllSymbols.empty() && Obj->isELF())
1411     addDynamicElfSymbols(Obj, AllSymbols);
1412 
1413   BumpPtrAllocator A;
1414   StringSaver Saver(A);
1415   addPltEntries(Obj, AllSymbols, Saver);
1416 
1417   // Create a mapping from virtual address to section.
1418   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1419   for (SectionRef Sec : Obj->sections())
1420     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1421   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1422 
1423   // Linked executables (.exe and .dll files) typically don't include a real
1424   // symbol table but they might contain an export table.
1425   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1426     for (const auto &ExportEntry : COFFObj->export_directories()) {
1427       StringRef Name;
1428       error(ExportEntry.getSymbolName(Name));
1429       if (Name.empty())
1430         continue;
1431       uint32_t RVA;
1432       error(ExportEntry.getExportRVA(RVA));
1433 
1434       uint64_t VA = COFFObj->getImageBase() + RVA;
1435       auto Sec = std::upper_bound(
1436           SectionAddresses.begin(), SectionAddresses.end(), VA,
1437           [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1438             return LHS < RHS.first;
1439           });
1440       if (Sec != SectionAddresses.begin())
1441         --Sec;
1442       else
1443         Sec = SectionAddresses.end();
1444 
1445       if (Sec != SectionAddresses.end())
1446         AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1447       else
1448         AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1449     }
1450   }
1451 
1452   // Sort all the symbols, this allows us to use a simple binary search to find
1453   // a symbol near an address.
1454   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1455     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1456   array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1457 
1458   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1459     if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1460       continue;
1461 
1462     uint64_t SectionAddr = Section.getAddress();
1463     uint64_t SectSize = Section.getSize();
1464     if (!SectSize)
1465       continue;
1466 
1467     // Get the list of all the symbols in this section.
1468     SectionSymbolsTy &Symbols = AllSymbols[Section];
1469     std::vector<uint64_t> DataMappingSymsAddr;
1470     std::vector<uint64_t> TextMappingSymsAddr;
1471     if (isArmElf(Obj)) {
1472       for (const auto &Symb : Symbols) {
1473         uint64_t Address = std::get<0>(Symb);
1474         StringRef Name = std::get<1>(Symb);
1475         if (Name.startswith("$d"))
1476           DataMappingSymsAddr.push_back(Address - SectionAddr);
1477         if (Name.startswith("$x"))
1478           TextMappingSymsAddr.push_back(Address - SectionAddr);
1479         if (Name.startswith("$a"))
1480           TextMappingSymsAddr.push_back(Address - SectionAddr);
1481         if (Name.startswith("$t"))
1482           TextMappingSymsAddr.push_back(Address - SectionAddr);
1483       }
1484     }
1485 
1486     llvm::sort(DataMappingSymsAddr);
1487     llvm::sort(TextMappingSymsAddr);
1488 
1489     if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1490       // AMDGPU disassembler uses symbolizer for printing labels
1491       std::unique_ptr<MCRelocationInfo> RelInfo(
1492         TheTarget->createMCRelocationInfo(TripleName, Ctx));
1493       if (RelInfo) {
1494         std::unique_ptr<MCSymbolizer> Symbolizer(
1495           TheTarget->createMCSymbolizer(
1496             TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1497         DisAsm->setSymbolizer(std::move(Symbolizer));
1498       }
1499     }
1500 
1501     // Make a list of all the relocations for this section.
1502     std::vector<RelocationRef> Rels;
1503     if (InlineRelocs) {
1504       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1505         for (const RelocationRef &Reloc : RelocSec.relocations()) {
1506           Rels.push_back(Reloc);
1507         }
1508       }
1509     }
1510 
1511     // Sort relocations by address.
1512     llvm::sort(Rels, isRelocAddressLess);
1513 
1514     StringRef SegmentName = "";
1515     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1516       DataRefImpl DR = Section.getRawDataRefImpl();
1517       SegmentName = MachO->getSectionFinalSegmentName(DR);
1518     }
1519     StringRef SectionName;
1520     error(Section.getName(SectionName));
1521 
1522     // If the section has no symbol at the start, just insert a dummy one.
1523     if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1524       Symbols.insert(
1525           Symbols.begin(),
1526           std::make_tuple(SectionAddr, SectionName,
1527                           Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1528     }
1529 
1530     SmallString<40> Comments;
1531     raw_svector_ostream CommentStream(Comments);
1532 
1533     StringRef BytesStr;
1534     error(Section.getContents(BytesStr));
1535     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1536                             BytesStr.size());
1537 
1538     uint64_t Size;
1539     uint64_t Index;
1540     bool PrintedSection = false;
1541 
1542     std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1543     std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1544     // Disassemble symbol by symbol.
1545     for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1546       uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr;
1547       // The end is either the section end or the beginning of the next
1548       // symbol.
1549       uint64_t End = (SI == SE - 1)
1550                          ? SectSize
1551                          : std::get<0>(Symbols[SI + 1]) - SectionAddr;
1552       // Don't try to disassemble beyond the end of section contents.
1553       if (End > SectSize)
1554         End = SectSize;
1555       // If this symbol has the same address as the next symbol, then skip it.
1556       if (Start >= End)
1557         continue;
1558 
1559       // Check if we need to skip symbol
1560       // Skip if the symbol's data is not between StartAddress and StopAddress
1561       if (End + SectionAddr < StartAddress ||
1562           Start + SectionAddr > StopAddress) {
1563         continue;
1564       }
1565 
1566       /// Skip if user requested specific symbols and this is not in the list
1567       if (!DisasmFuncsSet.empty() &&
1568           !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
1569         continue;
1570 
1571       if (!PrintedSection) {
1572         PrintedSection = true;
1573         outs() << "Disassembly of section ";
1574         if (!SegmentName.empty())
1575           outs() << SegmentName << ",";
1576         outs() << SectionName << ':';
1577       }
1578 
1579       // Stop disassembly at the stop address specified
1580       if (End + SectionAddr > StopAddress)
1581         End = StopAddress - SectionAddr;
1582 
1583       if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1584         if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1585           // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1586           Start += 256;
1587         }
1588         if (SI == SE - 1 ||
1589             std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1590           // cut trailing zeroes at the end of kernel
1591           // cut up to 256 bytes
1592           const uint64_t EndAlign = 256;
1593           const auto Limit = End - (std::min)(EndAlign, End - Start);
1594           while (End > Limit &&
1595             *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1596             End -= 4;
1597         }
1598       }
1599 
1600       outs() << '\n';
1601       if (!NoLeadingAddr)
1602         outs() << format("%016" PRIx64 " ", SectionAddr + Start);
1603 
1604       StringRef SymbolName = std::get<1>(Symbols[SI]);
1605       if (Demangle)
1606         outs() << demangle(SymbolName) << ":\n";
1607       else
1608         outs() << SymbolName << ":\n";
1609 
1610       // Don't print raw contents of a virtual section. A virtual section
1611       // doesn't have any contents in the file.
1612       if (Section.isVirtual()) {
1613         outs() << "...\n";
1614         continue;
1615       }
1616 
1617 #ifndef NDEBUG
1618       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1619 #else
1620       raw_ostream &DebugOut = nulls();
1621 #endif
1622 
1623       for (Index = Start; Index < End; Index += Size) {
1624         MCInst Inst;
1625 
1626         if (Index + SectionAddr < StartAddress ||
1627             Index + SectionAddr > StopAddress) {
1628           // skip byte by byte till StartAddress is reached
1629           Size = 1;
1630           continue;
1631         }
1632         // AArch64 ELF binaries can interleave data and text in the
1633         // same section. We rely on the markers introduced to
1634         // understand what we need to dump. If the data marker is within a
1635         // function, it is denoted as a word/short etc
1636         if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
1637             !DisassembleAll) {
1638           uint64_t Stride = 0;
1639 
1640           auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1641                                       DataMappingSymsAddr.end(), Index);
1642           if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1643             // Switch to data.
1644             while (Index < End) {
1645               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1646               outs() << "\t";
1647               if (Index + 4 <= End) {
1648                 Stride = 4;
1649                 dumpBytes(Bytes.slice(Index, 4), outs());
1650                 outs() << "\t.word\t";
1651                 uint32_t Data = 0;
1652                 if (Obj->isLittleEndian()) {
1653                   const auto Word =
1654                       reinterpret_cast<const support::ulittle32_t *>(
1655                           Bytes.data() + Index);
1656                   Data = *Word;
1657                 } else {
1658                   const auto Word = reinterpret_cast<const support::ubig32_t *>(
1659                       Bytes.data() + Index);
1660                   Data = *Word;
1661                 }
1662                 outs() << "0x" << format("%08" PRIx32, Data);
1663               } else if (Index + 2 <= End) {
1664                 Stride = 2;
1665                 dumpBytes(Bytes.slice(Index, 2), outs());
1666                 outs() << "\t\t.short\t";
1667                 uint16_t Data = 0;
1668                 if (Obj->isLittleEndian()) {
1669                   const auto Short =
1670                       reinterpret_cast<const support::ulittle16_t *>(
1671                           Bytes.data() + Index);
1672                   Data = *Short;
1673                 } else {
1674                   const auto Short =
1675                       reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1676                                                                   Index);
1677                   Data = *Short;
1678                 }
1679                 outs() << "0x" << format("%04" PRIx16, Data);
1680               } else {
1681                 Stride = 1;
1682                 dumpBytes(Bytes.slice(Index, 1), outs());
1683                 outs() << "\t\t.byte\t";
1684                 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1685               }
1686               Index += Stride;
1687               outs() << "\n";
1688               auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1689                                           TextMappingSymsAddr.end(), Index);
1690               if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1691                 break;
1692             }
1693           }
1694         }
1695 
1696         // If there is a data symbol inside an ELF text section and we are only
1697         // disassembling text (applicable all architectures),
1698         // we are in a situation where we must print the data and not
1699         // disassemble it.
1700         if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
1701             !DisassembleAll && Section.isText()) {
1702           // print out data up to 8 bytes at a time in hex and ascii
1703           uint8_t AsciiData[9] = {'\0'};
1704           uint8_t Byte;
1705           int NumBytes = 0;
1706 
1707           for (Index = Start; Index < End; Index += 1) {
1708             if (((SectionAddr + Index) < StartAddress) ||
1709                 ((SectionAddr + Index) > StopAddress))
1710               continue;
1711             if (NumBytes == 0) {
1712               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1713               outs() << "\t";
1714             }
1715             Byte = Bytes.slice(Index)[0];
1716             outs() << format(" %02x", Byte);
1717             AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1718 
1719             uint8_t IndentOffset = 0;
1720             NumBytes++;
1721             if (Index == End - 1 || NumBytes > 8) {
1722               // Indent the space for less than 8 bytes data.
1723               // 2 spaces for byte and one for space between bytes
1724               IndentOffset = 3 * (8 - NumBytes);
1725               for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1726                 AsciiData[Excess] = '\0';
1727               NumBytes = 8;
1728             }
1729             if (NumBytes == 8) {
1730               AsciiData[8] = '\0';
1731               outs() << std::string(IndentOffset, ' ') << "         ";
1732               outs() << reinterpret_cast<char *>(AsciiData);
1733               outs() << '\n';
1734               NumBytes = 0;
1735             }
1736           }
1737         }
1738         if (Index >= End)
1739           break;
1740 
1741         if (size_t N =
1742                 countSkippableZeroBytes(Bytes.slice(Index, End - Index))) {
1743           outs() << "\t\t..." << '\n';
1744           Index += N;
1745           if (Index >= End)
1746             break;
1747         }
1748 
1749         // Disassemble a real instruction or a data when disassemble all is
1750         // provided
1751         bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1752                                                    SectionAddr + Index, DebugOut,
1753                                                    CommentStream);
1754         if (Size == 0)
1755           Size = 1;
1756 
1757         PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1758                       Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1759                       *STI, &SP, &Rels);
1760         outs() << CommentStream.str();
1761         Comments.clear();
1762 
1763         // Try to resolve the target of a call, tail call, etc. to a specific
1764         // symbol.
1765         if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1766                     MIA->isConditionalBranch(Inst))) {
1767           uint64_t Target;
1768           if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1769             // In a relocatable object, the target's section must reside in
1770             // the same section as the call instruction or it is accessed
1771             // through a relocation.
1772             //
1773             // In a non-relocatable object, the target may be in any section.
1774             //
1775             // N.B. We don't walk the relocations in the relocatable case yet.
1776             auto *TargetSectionSymbols = &Symbols;
1777             if (!Obj->isRelocatableObject()) {
1778               auto SectionAddress = std::upper_bound(
1779                   SectionAddresses.begin(), SectionAddresses.end(), Target,
1780                   [](uint64_t LHS,
1781                       const std::pair<uint64_t, SectionRef> &RHS) {
1782                     return LHS < RHS.first;
1783                   });
1784               if (SectionAddress != SectionAddresses.begin()) {
1785                 --SectionAddress;
1786                 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1787               } else {
1788                 TargetSectionSymbols = &AbsoluteSymbols;
1789               }
1790             }
1791 
1792             // Find the first symbol in the section whose offset is less than
1793             // or equal to the target. If there isn't a section that contains
1794             // the target, find the nearest preceding absolute symbol.
1795             auto TargetSym = std::upper_bound(
1796                 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1797                 Target, [](uint64_t LHS,
1798                            const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1799                   return LHS < std::get<0>(RHS);
1800                 });
1801             if (TargetSym == TargetSectionSymbols->begin()) {
1802               TargetSectionSymbols = &AbsoluteSymbols;
1803               TargetSym = std::upper_bound(
1804                   AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1805                   Target, [](uint64_t LHS,
1806                              const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1807                             return LHS < std::get<0>(RHS);
1808                           });
1809             }
1810             if (TargetSym != TargetSectionSymbols->begin()) {
1811               --TargetSym;
1812               uint64_t TargetAddress = std::get<0>(*TargetSym);
1813               StringRef TargetName = std::get<1>(*TargetSym);
1814               outs() << " <" << TargetName;
1815               uint64_t Disp = Target - TargetAddress;
1816               if (Disp)
1817                 outs() << "+0x" << Twine::utohexstr(Disp);
1818               outs() << '>';
1819             }
1820           }
1821         }
1822         outs() << "\n";
1823 
1824         // Hexagon does this in pretty printer
1825         if (Obj->getArch() != Triple::hexagon)
1826           // Print relocation for instruction.
1827           while (RelCur != RelEnd) {
1828             uint64_t Addr = RelCur->getOffset();
1829             SmallString<16> Name;
1830             SmallString<32> Val;
1831 
1832             // If this relocation is hidden, skip it.
1833             if (getHidden(*RelCur) || ((SectionAddr + Addr) < StartAddress)) {
1834               ++RelCur;
1835               continue;
1836             }
1837 
1838             // Stop when rel_cur's address is past the current instruction.
1839             if (Addr >= Index + Size)
1840               break;
1841             RelCur->getTypeName(Name);
1842             error(getRelocationValueString(*RelCur, Val));
1843             outs() << format(Fmt.data(), SectionAddr + Addr) << Name << "\t"
1844                    << Val << "\n";
1845             ++RelCur;
1846           }
1847       }
1848     }
1849   }
1850 }
1851 
1852 void llvm::printRelocations(const ObjectFile *Obj) {
1853   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1854                                                  "%08" PRIx64;
1855   // Regular objdump doesn't print relocations in non-relocatable object
1856   // files.
1857   if (!Obj->isRelocatableObject())
1858     return;
1859 
1860   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1861     if (Section.relocation_begin() == Section.relocation_end())
1862       continue;
1863     StringRef SecName;
1864     error(Section.getName(SecName));
1865     outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
1866     for (const RelocationRef &Reloc : Section.relocations()) {
1867       uint64_t Address = Reloc.getOffset();
1868       SmallString<32> RelocName;
1869       SmallString<32> ValueStr;
1870       if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1871         continue;
1872       Reloc.getTypeName(RelocName);
1873       error(getRelocationValueString(Reloc, ValueStr));
1874       outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1875              << ValueStr << "\n";
1876     }
1877     outs() << "\n";
1878   }
1879 }
1880 
1881 void llvm::printDynamicRelocations(const ObjectFile *Obj) {
1882   // For the moment, this option is for ELF only
1883   if (!Obj->isELF())
1884     return;
1885 
1886   const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1887   if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1888     error("not a dynamic object");
1889     return;
1890   }
1891 
1892   std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1893   if (DynRelSec.empty())
1894     return;
1895 
1896   outs() << "DYNAMIC RELOCATION RECORDS\n";
1897   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1898   for (const SectionRef &Section : DynRelSec) {
1899     if (Section.relocation_begin() == Section.relocation_end())
1900       continue;
1901     for (const RelocationRef &Reloc : Section.relocations()) {
1902       uint64_t Address = Reloc.getOffset();
1903       SmallString<32> RelocName;
1904       SmallString<32> ValueStr;
1905       Reloc.getTypeName(RelocName);
1906       error(getRelocationValueString(Reloc, ValueStr));
1907       outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1908              << ValueStr << "\n";
1909     }
1910   }
1911 }
1912 
1913 void llvm::printSectionHeaders(const ObjectFile *Obj) {
1914   outs() << "Sections:\n"
1915             "Idx Name          Size      Address          Type\n";
1916   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1917     StringRef Name;
1918     error(Section.getName(Name));
1919     uint64_t Address = Section.getAddress();
1920     uint64_t Size = Section.getSize();
1921     bool Text = Section.isText();
1922     bool Data = Section.isData();
1923     bool BSS = Section.isBSS();
1924     std::string Type = (std::string(Text ? "TEXT " : "") +
1925                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1926     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1927                      (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1928                      Address, Type.c_str());
1929   }
1930   outs() << "\n";
1931 }
1932 
1933 void llvm::printSectionContents(const ObjectFile *Obj) {
1934   std::error_code EC;
1935   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1936     StringRef Name;
1937     StringRef Contents;
1938     error(Section.getName(Name));
1939     uint64_t BaseAddr = Section.getAddress();
1940     uint64_t Size = Section.getSize();
1941     if (!Size)
1942       continue;
1943 
1944     outs() << "Contents of section " << Name << ":\n";
1945     if (Section.isBSS()) {
1946       outs() << format("<skipping contents of bss section at [%04" PRIx64
1947                        ", %04" PRIx64 ")>\n",
1948                        BaseAddr, BaseAddr + Size);
1949       continue;
1950     }
1951 
1952     error(Section.getContents(Contents));
1953 
1954     // Dump out the content as hex and printable ascii characters.
1955     for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1956       outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1957       // Dump line of hex.
1958       for (std::size_t I = 0; I < 16; ++I) {
1959         if (I != 0 && I % 4 == 0)
1960           outs() << ' ';
1961         if (Addr + I < End)
1962           outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1963                  << hexdigit(Contents[Addr + I] & 0xF, true);
1964         else
1965           outs() << "  ";
1966       }
1967       // Print ascii.
1968       outs() << "  ";
1969       for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1970         if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1971           outs() << Contents[Addr + I];
1972         else
1973           outs() << ".";
1974       }
1975       outs() << "\n";
1976     }
1977   }
1978 }
1979 
1980 void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1981                             StringRef ArchitectureName) {
1982   outs() << "SYMBOL TABLE:\n";
1983 
1984   if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1985     printCOFFSymbolTable(Coff);
1986     return;
1987   }
1988 
1989   for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
1990     // Skip printing the special zero symbol when dumping an ELF file.
1991     // This makes the output consistent with the GNU objdump.
1992     if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
1993       continue;
1994 
1995     const SymbolRef &Symbol = *I;
1996     Expected<uint64_t> AddressOrError = Symbol.getAddress();
1997     if (!AddressOrError)
1998       report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(),
1999                    ArchitectureName);
2000     uint64_t Address = *AddressOrError;
2001     if ((Address < StartAddress) || (Address > StopAddress))
2002       continue;
2003     Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
2004     if (!TypeOrError)
2005       report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(),
2006                    ArchitectureName);
2007     SymbolRef::Type Type = *TypeOrError;
2008     uint32_t Flags = Symbol.getFlags();
2009     Expected<section_iterator> SectionOrErr = Symbol.getSection();
2010     if (!SectionOrErr)
2011       report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(),
2012                    ArchitectureName);
2013     section_iterator Section = *SectionOrErr;
2014     StringRef Name;
2015     if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
2016       Section->getName(Name);
2017     } else {
2018       Expected<StringRef> NameOrErr = Symbol.getName();
2019       if (!NameOrErr)
2020         report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(),
2021                      ArchitectureName);
2022       Name = *NameOrErr;
2023     }
2024 
2025     bool Global = Flags & SymbolRef::SF_Global;
2026     bool Weak = Flags & SymbolRef::SF_Weak;
2027     bool Absolute = Flags & SymbolRef::SF_Absolute;
2028     bool Common = Flags & SymbolRef::SF_Common;
2029     bool Hidden = Flags & SymbolRef::SF_Hidden;
2030 
2031     char GlobLoc = ' ';
2032     if (Type != SymbolRef::ST_Unknown)
2033       GlobLoc = Global ? 'g' : 'l';
2034     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2035                  ? 'd' : ' ';
2036     char FileFunc = ' ';
2037     if (Type == SymbolRef::ST_File)
2038       FileFunc = 'f';
2039     else if (Type == SymbolRef::ST_Function)
2040       FileFunc = 'F';
2041     else if (Type == SymbolRef::ST_Data)
2042       FileFunc = 'O';
2043 
2044     const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
2045                                                    "%08" PRIx64;
2046 
2047     outs() << format(Fmt, Address) << " "
2048            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2049            << (Weak ? 'w' : ' ') // Weak?
2050            << ' ' // Constructor. Not supported yet.
2051            << ' ' // Warning. Not supported yet.
2052            << ' ' // Indirect reference to another symbol.
2053            << Debug // Debugging (d) or dynamic (D) symbol.
2054            << FileFunc // Name of function (F), file (f) or object (O).
2055            << ' ';
2056     if (Absolute) {
2057       outs() << "*ABS*";
2058     } else if (Common) {
2059       outs() << "*COM*";
2060     } else if (Section == O->section_end()) {
2061       outs() << "*UND*";
2062     } else {
2063       if (const MachOObjectFile *MachO =
2064           dyn_cast<const MachOObjectFile>(O)) {
2065         DataRefImpl DR = Section->getRawDataRefImpl();
2066         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2067         outs() << SegmentName << ",";
2068       }
2069       StringRef SectionName;
2070       error(Section->getName(SectionName));
2071       outs() << SectionName;
2072     }
2073 
2074     outs() << '\t';
2075     if (Common || isa<ELFObjectFileBase>(O)) {
2076       uint64_t Val =
2077           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
2078       outs() << format("\t %08" PRIx64 " ", Val);
2079     }
2080 
2081     if (Hidden)
2082       outs() << ".hidden ";
2083 
2084     if (Demangle)
2085       outs() << demangle(Name) << '\n';
2086     else
2087       outs() << Name << '\n';
2088   }
2089 }
2090 
2091 static void printUnwindInfo(const ObjectFile *O) {
2092   outs() << "Unwind info:\n\n";
2093 
2094   if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
2095     printCOFFUnwindInfo(Coff);
2096   else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
2097     printMachOUnwindInfo(MachO);
2098   else
2099     // TODO: Extract DWARF dump tool to objdump.
2100     WithColor::error(errs(), ToolName)
2101         << "This operation is only currently supported "
2102            "for COFF and MachO object files.\n";
2103 }
2104 
2105 void llvm::printExportsTrie(const ObjectFile *o) {
2106   outs() << "Exports trie:\n";
2107   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2108     printMachOExportsTrie(MachO);
2109   else
2110     WithColor::error(errs(), ToolName)
2111         << "This operation is only currently supported "
2112            "for Mach-O executable files.\n";
2113 }
2114 
2115 void llvm::printRebaseTable(ObjectFile *o) {
2116   outs() << "Rebase table:\n";
2117   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2118     printMachORebaseTable(MachO);
2119   else
2120     WithColor::error(errs(), ToolName)
2121         << "This operation is only currently supported "
2122            "for Mach-O executable files.\n";
2123 }
2124 
2125 void llvm::printBindTable(ObjectFile *o) {
2126   outs() << "Bind table:\n";
2127   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2128     printMachOBindTable(MachO);
2129   else
2130     WithColor::error(errs(), ToolName)
2131         << "This operation is only currently supported "
2132            "for Mach-O executable files.\n";
2133 }
2134 
2135 void llvm::printLazyBindTable(ObjectFile *o) {
2136   outs() << "Lazy bind table:\n";
2137   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2138     printMachOLazyBindTable(MachO);
2139   else
2140     WithColor::error(errs(), ToolName)
2141         << "This operation is only currently supported "
2142            "for Mach-O executable files.\n";
2143 }
2144 
2145 void llvm::printWeakBindTable(ObjectFile *o) {
2146   outs() << "Weak bind table:\n";
2147   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2148     printMachOWeakBindTable(MachO);
2149   else
2150     WithColor::error(errs(), ToolName)
2151         << "This operation is only currently supported "
2152            "for Mach-O executable files.\n";
2153 }
2154 
2155 /// Dump the raw contents of the __clangast section so the output can be piped
2156 /// into llvm-bcanalyzer.
2157 void llvm::printRawClangAST(const ObjectFile *Obj) {
2158   if (outs().is_displayed()) {
2159     WithColor::error(errs(), ToolName)
2160         << "The -raw-clang-ast option will dump the raw binary contents of "
2161            "the clang ast section.\n"
2162            "Please redirect the output to a file or another program such as "
2163            "llvm-bcanalyzer.\n";
2164     return;
2165   }
2166 
2167   StringRef ClangASTSectionName("__clangast");
2168   if (isa<COFFObjectFile>(Obj)) {
2169     ClangASTSectionName = "clangast";
2170   }
2171 
2172   Optional<object::SectionRef> ClangASTSection;
2173   for (auto Sec : ToolSectionFilter(*Obj)) {
2174     StringRef Name;
2175     Sec.getName(Name);
2176     if (Name == ClangASTSectionName) {
2177       ClangASTSection = Sec;
2178       break;
2179     }
2180   }
2181   if (!ClangASTSection)
2182     return;
2183 
2184   StringRef ClangASTContents;
2185   error(ClangASTSection.getValue().getContents(ClangASTContents));
2186   outs().write(ClangASTContents.data(), ClangASTContents.size());
2187 }
2188 
2189 static void printFaultMaps(const ObjectFile *Obj) {
2190   StringRef FaultMapSectionName;
2191 
2192   if (isa<ELFObjectFileBase>(Obj)) {
2193     FaultMapSectionName = ".llvm_faultmaps";
2194   } else if (isa<MachOObjectFile>(Obj)) {
2195     FaultMapSectionName = "__llvm_faultmaps";
2196   } else {
2197     WithColor::error(errs(), ToolName)
2198         << "This operation is only currently supported "
2199            "for ELF and Mach-O executable files.\n";
2200     return;
2201   }
2202 
2203   Optional<object::SectionRef> FaultMapSection;
2204 
2205   for (auto Sec : ToolSectionFilter(*Obj)) {
2206     StringRef Name;
2207     Sec.getName(Name);
2208     if (Name == FaultMapSectionName) {
2209       FaultMapSection = Sec;
2210       break;
2211     }
2212   }
2213 
2214   outs() << "FaultMap table:\n";
2215 
2216   if (!FaultMapSection.hasValue()) {
2217     outs() << "<not found>\n";
2218     return;
2219   }
2220 
2221   StringRef FaultMapContents;
2222   error(FaultMapSection.getValue().getContents(FaultMapContents));
2223 
2224   FaultMapParser FMP(FaultMapContents.bytes_begin(),
2225                      FaultMapContents.bytes_end());
2226 
2227   outs() << FMP;
2228 }
2229 
2230 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
2231   if (O->isELF()) {
2232     printELFFileHeader(O);
2233     return printELFDynamicSection(O);
2234   }
2235   if (O->isCOFF())
2236     return printCOFFFileHeader(O);
2237   if (O->isWasm())
2238     return printWasmFileHeader(O);
2239   if (O->isMachO()) {
2240     printMachOFileHeader(O);
2241     if (!OnlyFirst)
2242       printMachOLoadCommands(O);
2243     return;
2244   }
2245   report_error(O->getFileName(), "Invalid/Unsupported object file format");
2246 }
2247 
2248 static void printFileHeaders(const ObjectFile *O) {
2249   if (!O->isELF() && !O->isCOFF())
2250     report_error(O->getFileName(), "Invalid/Unsupported object file format");
2251 
2252   Triple::ArchType AT = O->getArch();
2253   outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2254   Expected<uint64_t> StartAddrOrErr = O->getStartAddress();
2255   if (!StartAddrOrErr)
2256     report_error(O->getFileName(), StartAddrOrErr.takeError());
2257 
2258   StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2259   uint64_t Address = StartAddrOrErr.get();
2260   outs() << "start address: "
2261          << "0x" << format(Fmt.data(), Address) << "\n\n";
2262 }
2263 
2264 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2265   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2266   if (!ModeOrErr) {
2267     WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
2268     consumeError(ModeOrErr.takeError());
2269     return;
2270   }
2271   sys::fs::perms Mode = ModeOrErr.get();
2272   outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2273   outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2274   outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2275   outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2276   outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2277   outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2278   outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2279   outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2280   outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2281 
2282   outs() << " ";
2283 
2284   Expected<unsigned> UIDOrErr = C.getUID();
2285   if (!UIDOrErr)
2286     report_error(Filename, UIDOrErr.takeError());
2287   unsigned UID = UIDOrErr.get();
2288   outs() << format("%d/", UID);
2289 
2290   Expected<unsigned> GIDOrErr = C.getGID();
2291   if (!GIDOrErr)
2292     report_error(Filename, GIDOrErr.takeError());
2293   unsigned GID = GIDOrErr.get();
2294   outs() << format("%-d ", GID);
2295 
2296   Expected<uint64_t> Size = C.getRawSize();
2297   if (!Size)
2298     report_error(Filename, Size.takeError());
2299   outs() << format("%6" PRId64, Size.get()) << " ";
2300 
2301   StringRef RawLastModified = C.getRawLastModified();
2302   unsigned Seconds;
2303   if (RawLastModified.getAsInteger(10, Seconds))
2304     outs() << "(date: \"" << RawLastModified
2305            << "\" contains non-decimal chars) ";
2306   else {
2307     // Since ctime(3) returns a 26 character string of the form:
2308     // "Sun Sep 16 01:03:52 1973\n\0"
2309     // just print 24 characters.
2310     time_t t = Seconds;
2311     outs() << format("%.24s ", ctime(&t));
2312   }
2313 
2314   StringRef Name = "";
2315   Expected<StringRef> NameOrErr = C.getName();
2316   if (!NameOrErr) {
2317     consumeError(NameOrErr.takeError());
2318     Expected<StringRef> RawNameOrErr = C.getRawName();
2319     if (!RawNameOrErr)
2320       report_error(Filename, NameOrErr.takeError());
2321     Name = RawNameOrErr.get();
2322   } else {
2323     Name = NameOrErr.get();
2324   }
2325   outs() << Name << "\n";
2326 }
2327 
2328 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2329                        const Archive::Child *C = nullptr) {
2330   // Avoid other output when using a raw option.
2331   if (!RawClangAST) {
2332     outs() << '\n';
2333     if (A)
2334       outs() << A->getFileName() << "(" << O->getFileName() << ")";
2335     else
2336       outs() << O->getFileName();
2337     outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
2338   }
2339 
2340   StringRef ArchiveName = A ? A->getFileName() : "";
2341   if (FileHeaders)
2342     printFileHeaders(O);
2343   if (ArchiveHeaders && !MachOOpt && C)
2344     printArchiveChild(ArchiveName, *C);
2345   if (Disassemble)
2346     disassembleObject(O, Relocations);
2347   if (Relocations && !Disassemble)
2348     printRelocations(O);
2349   if (DynamicRelocations)
2350     printDynamicRelocations(O);
2351   if (SectionHeaders)
2352     printSectionHeaders(O);
2353   if (SectionContents)
2354     printSectionContents(O);
2355   if (SymbolTable)
2356     printSymbolTable(O, ArchiveName);
2357   if (UnwindInfo)
2358     printUnwindInfo(O);
2359   if (PrivateHeaders || FirstPrivateHeader)
2360     printPrivateFileHeaders(O, FirstPrivateHeader);
2361   if (ExportsTrie)
2362     printExportsTrie(O);
2363   if (Rebase)
2364     printRebaseTable(O);
2365   if (Bind)
2366     printBindTable(O);
2367   if (LazyBind)
2368     printLazyBindTable(O);
2369   if (WeakBind)
2370     printWeakBindTable(O);
2371   if (RawClangAST)
2372     printRawClangAST(O);
2373   if (PrintFaultMaps)
2374     printFaultMaps(O);
2375   if (DwarfDumpType != DIDT_Null) {
2376     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2377     // Dump the complete DWARF structure.
2378     DIDumpOptions DumpOpts;
2379     DumpOpts.DumpType = DwarfDumpType;
2380     DICtx->dump(outs(), DumpOpts);
2381   }
2382 }
2383 
2384 static void dumpObject(const COFFImportFile *I, const Archive *A,
2385                        const Archive::Child *C = nullptr) {
2386   StringRef ArchiveName = A ? A->getFileName() : "";
2387 
2388   // Avoid other output when using a raw option.
2389   if (!RawClangAST)
2390     outs() << '\n'
2391            << ArchiveName << "(" << I->getFileName() << ")"
2392            << ":\tfile format COFF-import-file"
2393            << "\n\n";
2394 
2395   if (ArchiveHeaders && !MachOOpt && C)
2396     printArchiveChild(ArchiveName, *C);
2397   if (SymbolTable)
2398     printCOFFSymbolTable(I);
2399 }
2400 
2401 /// Dump each object file in \a a;
2402 static void dumpArchive(const Archive *A) {
2403   Error Err = Error::success();
2404   for (auto &C : A->children(Err)) {
2405     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2406     if (!ChildOrErr) {
2407       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2408         report_error(A->getFileName(), C, std::move(E));
2409       continue;
2410     }
2411     if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2412       dumpObject(O, A, &C);
2413     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2414       dumpObject(I, A, &C);
2415     else
2416       report_error(A->getFileName(), object_error::invalid_file_type);
2417   }
2418   if (Err)
2419     report_error(A->getFileName(), std::move(Err));
2420 }
2421 
2422 /// Open file and figure out how to dump it.
2423 static void dumpInput(StringRef file) {
2424   // If we are using the Mach-O specific object file parser, then let it parse
2425   // the file and process the command line options.  So the -arch flags can
2426   // be used to select specific slices, etc.
2427   if (MachOOpt) {
2428     parseInputMachO(file);
2429     return;
2430   }
2431 
2432   // Attempt to open the binary.
2433   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2434   if (!BinaryOrErr)
2435     report_error(file, BinaryOrErr.takeError());
2436   Binary &Binary = *BinaryOrErr.get().getBinary();
2437 
2438   if (Archive *A = dyn_cast<Archive>(&Binary))
2439     dumpArchive(A);
2440   else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2441     dumpObject(O);
2442   else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2443     parseInputMachO(UB);
2444   else
2445     report_error(file, object_error::invalid_file_type);
2446 }
2447 
2448 int main(int argc, char **argv) {
2449   InitLLVM X(argc, argv);
2450 
2451   // Initialize targets and assembly printers/parsers.
2452   llvm::InitializeAllTargetInfos();
2453   llvm::InitializeAllTargetMCs();
2454   llvm::InitializeAllDisassemblers();
2455 
2456   // Register the target printer for --version.
2457   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2458 
2459   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2460 
2461   ToolName = argv[0];
2462 
2463   // Defaults to a.out if no filenames specified.
2464   if (InputFilenames.empty())
2465     InputFilenames.push_back("a.out");
2466 
2467   if (AllHeaders)
2468     FileHeaders = PrivateHeaders = Relocations = SectionHeaders = SymbolTable =
2469         true;
2470 
2471   if (DisassembleAll || PrintSource || PrintLines)
2472     Disassemble = true;
2473 
2474   if (!Disassemble
2475       && !Relocations
2476       && !DynamicRelocations
2477       && !SectionHeaders
2478       && !SectionContents
2479       && !SymbolTable
2480       && !UnwindInfo
2481       && !PrivateHeaders
2482       && !FileHeaders
2483       && !FirstPrivateHeader
2484       && !ExportsTrie
2485       && !Rebase
2486       && !Bind
2487       && !LazyBind
2488       && !WeakBind
2489       && !RawClangAST
2490       && !(UniversalHeaders && MachOOpt)
2491       && !ArchiveHeaders
2492       && !(IndirectSymbols && MachOOpt)
2493       && !(DataInCode && MachOOpt)
2494       && !(LinkOptHints && MachOOpt)
2495       && !(InfoPlist && MachOOpt)
2496       && !(DylibsUsed && MachOOpt)
2497       && !(DylibId && MachOOpt)
2498       && !(ObjcMetaData && MachOOpt)
2499       && !(!FilterSections.empty() && MachOOpt)
2500       && !PrintFaultMaps
2501       && DwarfDumpType == DIDT_Null) {
2502     cl::PrintHelpMessage();
2503     return 2;
2504   }
2505 
2506   DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2507                         DisassembleFunctions.end());
2508 
2509   llvm::for_each(InputFilenames, dumpInput);
2510 
2511   return EXIT_SUCCESS;
2512 }
2513