xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision cec38094258c69be4421fae42fdecce97fd4c9da)
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 namespace {
282 struct SectionSymbol {
283   SectionSymbol(uint64_t Address, StringRef Name, uint8_t Type)
284       : Address(Address), Name(Name), Type(Type) {}
285 
286   bool operator<(const SectionSymbol &Other) const {
287     return std::tie(Address, Name, Type) <
288            std::tie(Other.Address, Other.Name, Other.Type);
289   }
290 
291   uint64_t Address;
292   StringRef Name;
293   uint8_t Type;
294 };
295 
296 typedef std::vector<SectionSymbol> SectionSymbolsTy;
297 
298 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
299 
300 class SectionFilterIterator {
301 public:
302   SectionFilterIterator(FilterPredicate P,
303                         llvm::object::section_iterator const &I,
304                         llvm::object::section_iterator const &E)
305       : Predicate(std::move(P)), Iterator(I), End(E) {
306     ScanPredicate();
307   }
308   const llvm::object::SectionRef &operator*() const { return *Iterator; }
309   SectionFilterIterator &operator++() {
310     ++Iterator;
311     ScanPredicate();
312     return *this;
313   }
314   bool operator!=(SectionFilterIterator const &Other) const {
315     return Iterator != Other.Iterator;
316   }
317 
318 private:
319   void ScanPredicate() {
320     while (Iterator != End && !Predicate(*Iterator)) {
321       ++Iterator;
322     }
323   }
324   FilterPredicate Predicate;
325   llvm::object::section_iterator Iterator;
326   llvm::object::section_iterator End;
327 };
328 
329 class SectionFilter {
330 public:
331   SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
332       : Predicate(std::move(P)), Object(O) {}
333   SectionFilterIterator begin() {
334     return SectionFilterIterator(Predicate, Object.section_begin(),
335                                  Object.section_end());
336   }
337   SectionFilterIterator end() {
338     return SectionFilterIterator(Predicate, Object.section_end(),
339                                  Object.section_end());
340   }
341 
342 private:
343   FilterPredicate Predicate;
344   llvm::object::ObjectFile const &Object;
345 };
346 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
347   return SectionFilter(
348       [](llvm::object::SectionRef const &S) {
349         if (FilterSections.empty())
350           return true;
351         llvm::StringRef String;
352         std::error_code error = S.getName(String);
353         if (error)
354           return false;
355         return is_contained(FilterSections, String);
356       },
357       O);
358 }
359 }
360 
361 void llvm::error(std::error_code EC) {
362   if (!EC)
363     return;
364   WithColor::error(errs(), ToolName)
365       << "reading file: " << EC.message() << ".\n";
366   errs().flush();
367   exit(1);
368 }
369 
370 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
371   WithColor::error(errs(), ToolName) << Message << ".\n";
372   errs().flush();
373   exit(1);
374 }
375 
376 void llvm::warn(StringRef Message) {
377   WithColor::warning(errs(), ToolName) << Message << ".\n";
378   errs().flush();
379 }
380 
381 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
382                                                 Twine Message) {
383   WithColor::error(errs(), ToolName)
384       << "'" << File << "': " << Message << ".\n";
385   exit(1);
386 }
387 
388 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
389                                                 std::error_code EC) {
390   assert(EC);
391   WithColor::error(errs(), ToolName)
392       << "'" << File << "': " << EC.message() << ".\n";
393   exit(1);
394 }
395 
396 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
397                                                 llvm::Error E) {
398   assert(E);
399   std::string Buf;
400   raw_string_ostream OS(Buf);
401   logAllUnhandledErrors(std::move(E), OS);
402   OS.flush();
403   WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
404   exit(1);
405 }
406 
407 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
408                                                 StringRef FileName,
409                                                 llvm::Error E,
410                                                 StringRef ArchitectureName) {
411   assert(E);
412   WithColor::error(errs(), ToolName);
413   if (ArchiveName != "")
414     errs() << ArchiveName << "(" << FileName << ")";
415   else
416     errs() << "'" << FileName << "'";
417   if (!ArchitectureName.empty())
418     errs() << " (for architecture " << ArchitectureName << ")";
419   std::string Buf;
420   raw_string_ostream OS(Buf);
421   logAllUnhandledErrors(std::move(E), OS);
422   OS.flush();
423   errs() << ": " << Buf;
424   exit(1);
425 }
426 
427 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
428                                                 const object::Archive::Child &C,
429                                                 llvm::Error E,
430                                                 StringRef ArchitectureName) {
431   Expected<StringRef> NameOrErr = C.getName();
432   // TODO: if we have a error getting the name then it would be nice to print
433   // the index of which archive member this is and or its offset in the
434   // archive instead of "???" as the name.
435   if (!NameOrErr) {
436     consumeError(NameOrErr.takeError());
437     llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
438   } else
439     llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
440                        ArchitectureName);
441 }
442 
443 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
444   // Figure out the target triple.
445   llvm::Triple TheTriple("unknown-unknown-unknown");
446   if (TripleName.empty()) {
447     if (Obj)
448       TheTriple = Obj->makeTriple();
449   } else {
450     TheTriple.setTriple(Triple::normalize(TripleName));
451 
452     // Use the triple, but also try to combine with ARM build attributes.
453     if (Obj) {
454       auto Arch = Obj->getArch();
455       if (Arch == Triple::arm || Arch == Triple::armeb)
456         Obj->setARMSubArch(TheTriple);
457     }
458   }
459 
460   // Get the target specific parser.
461   std::string Error;
462   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
463                                                          Error);
464   if (!TheTarget) {
465     if (Obj)
466       report_error(Obj->getFileName(), "can't find target: " + Error);
467     else
468       error("can't find target: " + Error);
469   }
470 
471   // Update the triple name and return the found target.
472   TripleName = TheTriple.getTriple();
473   return TheTarget;
474 }
475 
476 bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) {
477   return A.getOffset() < B.getOffset();
478 }
479 
480 template <class ELFT>
481 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
482                                                 const RelocationRef &RelRef,
483                                                 SmallVectorImpl<char> &Result) {
484   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
485   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
486   typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
487 
488   const ELFFile<ELFT> &EF = *Obj->getELFFile();
489   DataRefImpl Rel = RelRef.getRawDataRefImpl();
490   auto SecOrErr = EF.getSection(Rel.d.a);
491   if (!SecOrErr)
492     return errorToErrorCode(SecOrErr.takeError());
493 
494   int64_t Addend = 0;
495   // If there is no Symbol associated with the relocation, we set the undef
496   // boolean value to 'true'. This will prevent us from calling functions that
497   // requires the relocation to be associated with a symbol.
498   //
499   // In SHT_REL case we would need to read the addend from section data.
500   // GNU objdump does not do that and we just follow for simplicity.
501   bool Undef = false;
502   if ((*SecOrErr)->sh_type == ELF::SHT_RELA) {
503     const Elf_Rela *ERela = Obj->getRela(Rel);
504     Addend = ERela->r_addend;
505     Undef = ERela->getSymbol(false) == 0;
506   } else if ((*SecOrErr)->sh_type != ELF::SHT_REL) {
507     return object_error::parse_failed;
508   }
509 
510   // Default scheme is to print Target, as well as "+ <addend>" for nonzero
511   // addend. Should be acceptable for all normal purposes.
512   std::string FmtBuf;
513   raw_string_ostream Fmt(FmtBuf);
514 
515   if (!Undef) {
516     symbol_iterator SI = RelRef.getSymbol();
517     const Elf_Sym *Sym = Obj->getSymbol(SI->getRawDataRefImpl());
518     if (Sym->getType() == ELF::STT_SECTION) {
519       Expected<section_iterator> SymSI = SI->getSection();
520       if (!SymSI)
521         return errorToErrorCode(SymSI.takeError());
522       const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
523       auto SecName = EF.getSectionName(SymSec);
524       if (!SecName)
525         return errorToErrorCode(SecName.takeError());
526       Fmt << *SecName;
527     } else {
528       Expected<StringRef> SymName = SI->getName();
529       if (!SymName)
530         return errorToErrorCode(SymName.takeError());
531       if (Demangle)
532         Fmt << demangle(*SymName);
533       else
534         Fmt << *SymName;
535     }
536   } else {
537     Fmt << "*ABS*";
538   }
539 
540   if (Addend != 0)
541     Fmt << (Addend < 0 ? "" : "+") << Addend;
542   Fmt.flush();
543   Result.append(FmtBuf.begin(), FmtBuf.end());
544   return std::error_code();
545 }
546 
547 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
548                                                 const RelocationRef &Rel,
549                                                 SmallVectorImpl<char> &Result) {
550   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
551     return getRelocationValueString(ELF32LE, Rel, Result);
552   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
553     return getRelocationValueString(ELF64LE, Rel, Result);
554   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
555     return getRelocationValueString(ELF32BE, Rel, Result);
556   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
557   return getRelocationValueString(ELF64BE, Rel, Result);
558 }
559 
560 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
561                                                 const RelocationRef &Rel,
562                                                 SmallVectorImpl<char> &Result) {
563   symbol_iterator SymI = Rel.getSymbol();
564   Expected<StringRef> SymNameOrErr = SymI->getName();
565   if (!SymNameOrErr)
566     return errorToErrorCode(SymNameOrErr.takeError());
567   StringRef SymName = *SymNameOrErr;
568   Result.append(SymName.begin(), SymName.end());
569   return std::error_code();
570 }
571 
572 static void printRelocationTargetName(const MachOObjectFile *O,
573                                       const MachO::any_relocation_info &RE,
574                                       raw_string_ostream &Fmt) {
575   // Target of a scattered relocation is an address.  In the interest of
576   // generating pretty output, scan through the symbol table looking for a
577   // symbol that aligns with that address.  If we find one, print it.
578   // Otherwise, we just print the hex address of the target.
579   if (O->isRelocationScattered(RE)) {
580     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
581 
582     for (const SymbolRef &Symbol : O->symbols()) {
583       Expected<uint64_t> Addr = Symbol.getAddress();
584       if (!Addr)
585         report_error(O->getFileName(), Addr.takeError());
586       if (*Addr != Val)
587         continue;
588       Expected<StringRef> Name = Symbol.getName();
589       if (!Name)
590         report_error(O->getFileName(), Name.takeError());
591       Fmt << *Name;
592       return;
593     }
594 
595     // If we couldn't find a symbol that this relocation refers to, try
596     // to find a section beginning instead.
597     for (const SectionRef &Section : ToolSectionFilter(*O)) {
598       std::error_code ec;
599 
600       StringRef Name;
601       uint64_t Addr = Section.getAddress();
602       if (Addr != Val)
603         continue;
604       if ((ec = Section.getName(Name)))
605         report_error(O->getFileName(), ec);
606       Fmt << Name;
607       return;
608     }
609 
610     Fmt << format("0x%x", Val);
611     return;
612   }
613 
614   StringRef S;
615   bool isExtern = O->getPlainRelocationExternal(RE);
616   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
617 
618   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
619     Fmt << format("0x%0" PRIx64, Val);
620     return;
621   }
622 
623   if (isExtern) {
624     symbol_iterator SI = O->symbol_begin();
625     advance(SI, Val);
626     Expected<StringRef> SOrErr = SI->getName();
627     if (!SOrErr)
628       report_error(O->getFileName(), SOrErr.takeError());
629     S = *SOrErr;
630   } else {
631     section_iterator SI = O->section_begin();
632     // Adjust for the fact that sections are 1-indexed.
633     if (Val == 0) {
634       Fmt << "0 (?,?)";
635       return;
636     }
637     uint32_t I = Val - 1;
638     while (I != 0 && SI != O->section_end()) {
639       --I;
640       advance(SI, 1);
641     }
642     if (SI == O->section_end())
643       Fmt << Val << " (?,?)";
644     else
645       SI->getName(S);
646   }
647 
648   Fmt << S;
649 }
650 
651 static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
652                                                 const RelocationRef &RelRef,
653                                                 SmallVectorImpl<char> &Result) {
654   const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
655   symbol_iterator SI = RelRef.getSymbol();
656   std::string FmtBuf;
657   raw_string_ostream Fmt(FmtBuf);
658   if (SI == Obj->symbol_end()) {
659     // Not all wasm relocations have symbols associated with them.
660     // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
661     Fmt << Rel.Index;
662   } else {
663     Expected<StringRef> SymNameOrErr = SI->getName();
664     if (!SymNameOrErr)
665       return errorToErrorCode(SymNameOrErr.takeError());
666     StringRef SymName = *SymNameOrErr;
667     Result.append(SymName.begin(), SymName.end());
668   }
669   Fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
670   Fmt.flush();
671   Result.append(FmtBuf.begin(), FmtBuf.end());
672   return std::error_code();
673 }
674 
675 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
676                                                 const RelocationRef &RelRef,
677                                                 SmallVectorImpl<char> &Result) {
678   DataRefImpl Rel = RelRef.getRawDataRefImpl();
679   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
680 
681   unsigned Arch = Obj->getArch();
682 
683   std::string FmtBuf;
684   raw_string_ostream Fmt(FmtBuf);
685   unsigned Type = Obj->getAnyRelocationType(RE);
686   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
687 
688   // Determine any addends that should be displayed with the relocation.
689   // These require decoding the relocation type, which is triple-specific.
690 
691   // X86_64 has entirely custom relocation types.
692   if (Arch == Triple::x86_64) {
693     switch (Type) {
694     case MachO::X86_64_RELOC_GOT_LOAD:
695     case MachO::X86_64_RELOC_GOT: {
696       printRelocationTargetName(Obj, RE, Fmt);
697       Fmt << "@GOT";
698       if (IsPCRel)
699         Fmt << "PCREL";
700       break;
701     }
702     case MachO::X86_64_RELOC_SUBTRACTOR: {
703       DataRefImpl RelNext = Rel;
704       Obj->moveRelocationNext(RelNext);
705       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
706 
707       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
708       // X86_64_RELOC_UNSIGNED.
709       // NOTE: Scattered relocations don't exist on x86_64.
710       unsigned RType = Obj->getAnyRelocationType(RENext);
711       if (RType != MachO::X86_64_RELOC_UNSIGNED)
712         report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
713                      "X86_64_RELOC_SUBTRACTOR.");
714 
715       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
716       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
717       printRelocationTargetName(Obj, RENext, Fmt);
718       Fmt << "-";
719       printRelocationTargetName(Obj, RE, Fmt);
720       break;
721     }
722     case MachO::X86_64_RELOC_TLV:
723       printRelocationTargetName(Obj, RE, Fmt);
724       Fmt << "@TLV";
725       if (IsPCRel)
726         Fmt << "P";
727       break;
728     case MachO::X86_64_RELOC_SIGNED_1:
729       printRelocationTargetName(Obj, RE, Fmt);
730       Fmt << "-1";
731       break;
732     case MachO::X86_64_RELOC_SIGNED_2:
733       printRelocationTargetName(Obj, RE, Fmt);
734       Fmt << "-2";
735       break;
736     case MachO::X86_64_RELOC_SIGNED_4:
737       printRelocationTargetName(Obj, RE, Fmt);
738       Fmt << "-4";
739       break;
740     default:
741       printRelocationTargetName(Obj, RE, Fmt);
742       break;
743     }
744     // X86 and ARM share some relocation types in common.
745   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
746              Arch == Triple::ppc) {
747     // Generic relocation types...
748     switch (Type) {
749     case MachO::GENERIC_RELOC_PAIR: // prints no info
750       return std::error_code();
751     case MachO::GENERIC_RELOC_SECTDIFF: {
752       DataRefImpl RelNext = Rel;
753       Obj->moveRelocationNext(RelNext);
754       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
755 
756       // X86 sect diff's must be followed by a relocation of type
757       // GENERIC_RELOC_PAIR.
758       unsigned RType = Obj->getAnyRelocationType(RENext);
759 
760       if (RType != MachO::GENERIC_RELOC_PAIR)
761         report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
762                      "GENERIC_RELOC_SECTDIFF.");
763 
764       printRelocationTargetName(Obj, RE, Fmt);
765       Fmt << "-";
766       printRelocationTargetName(Obj, RENext, Fmt);
767       break;
768     }
769     }
770 
771     if (Arch == Triple::x86 || Arch == Triple::ppc) {
772       switch (Type) {
773       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
774         DataRefImpl RelNext = Rel;
775         Obj->moveRelocationNext(RelNext);
776         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
777 
778         // X86 sect diff's must be followed by a relocation of type
779         // GENERIC_RELOC_PAIR.
780         unsigned RType = Obj->getAnyRelocationType(RENext);
781         if (RType != MachO::GENERIC_RELOC_PAIR)
782           report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
783                        "GENERIC_RELOC_LOCAL_SECTDIFF.");
784 
785         printRelocationTargetName(Obj, RE, Fmt);
786         Fmt << "-";
787         printRelocationTargetName(Obj, RENext, Fmt);
788         break;
789       }
790       case MachO::GENERIC_RELOC_TLV: {
791         printRelocationTargetName(Obj, RE, Fmt);
792         Fmt << "@TLV";
793         if (IsPCRel)
794           Fmt << "P";
795         break;
796       }
797       default:
798         printRelocationTargetName(Obj, RE, Fmt);
799       }
800     } else { // ARM-specific relocations
801       switch (Type) {
802       case MachO::ARM_RELOC_HALF:
803       case MachO::ARM_RELOC_HALF_SECTDIFF: {
804         // Half relocations steal a bit from the length field to encode
805         // whether this is an upper16 or a lower16 relocation.
806         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
807 
808         if (isUpper)
809           Fmt << ":upper16:(";
810         else
811           Fmt << ":lower16:(";
812         printRelocationTargetName(Obj, RE, Fmt);
813 
814         DataRefImpl RelNext = Rel;
815         Obj->moveRelocationNext(RelNext);
816         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
817 
818         // ARM half relocs must be followed by a relocation of type
819         // ARM_RELOC_PAIR.
820         unsigned RType = Obj->getAnyRelocationType(RENext);
821         if (RType != MachO::ARM_RELOC_PAIR)
822           report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
823                        "ARM_RELOC_HALF");
824 
825         // NOTE: The half of the target virtual address is stashed in the
826         // address field of the secondary relocation, but we can't reverse
827         // engineer the constant offset from it without decoding the movw/movt
828         // instruction to find the other half in its immediate field.
829 
830         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
831         // symbol/section pointer of the follow-on relocation.
832         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
833           Fmt << "-";
834           printRelocationTargetName(Obj, RENext, Fmt);
835         }
836 
837         Fmt << ")";
838         break;
839       }
840       default: { printRelocationTargetName(Obj, RE, Fmt); }
841       }
842     }
843   } else
844     printRelocationTargetName(Obj, RE, Fmt);
845 
846   Fmt.flush();
847   Result.append(FmtBuf.begin(), FmtBuf.end());
848   return std::error_code();
849 }
850 
851 static std::error_code getRelocationValueString(const RelocationRef &Rel,
852                                                 SmallVectorImpl<char> &Result) {
853   const ObjectFile *Obj = Rel.getObject();
854   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
855     return getRelocationValueString(ELF, Rel, Result);
856   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
857     return getRelocationValueString(COFF, Rel, Result);
858   if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
859     return getRelocationValueString(Wasm, Rel, Result);
860   if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
861     return getRelocationValueString(MachO, Rel, Result);
862   llvm_unreachable("unknown object file format");
863 }
864 
865 /// Indicates whether this relocation should hidden when listing
866 /// relocations, usually because it is the trailing part of a multipart
867 /// relocation that will be printed as part of the leading relocation.
868 static bool getHidden(RelocationRef RelRef) {
869   auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
870   if (!MachO)
871     return false;
872 
873   unsigned Arch = MachO->getArch();
874   DataRefImpl Rel = RelRef.getRawDataRefImpl();
875   uint64_t Type = MachO->getRelocationType(Rel);
876 
877   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
878   // is always hidden.
879   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
880     return Type == MachO::GENERIC_RELOC_PAIR;
881 
882   if (Arch == Triple::x86_64) {
883     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
884     // an X86_64_RELOC_SUBTRACTOR.
885     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
886       DataRefImpl RelPrev = Rel;
887       RelPrev.d.a--;
888       uint64_t PrevType = MachO->getRelocationType(RelPrev);
889       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
890         return true;
891     }
892   }
893 
894   return false;
895 }
896 
897 namespace {
898 class SourcePrinter {
899 protected:
900   DILineInfo OldLineInfo;
901   const ObjectFile *Obj = nullptr;
902   std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
903   // File name to file contents of source
904   std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
905   // Mark the line endings of the cached source
906   std::unordered_map<std::string, std::vector<StringRef>> LineCache;
907 
908 private:
909   bool cacheSource(const DILineInfo& LineInfoFile);
910 
911 public:
912   SourcePrinter() = default;
913   SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
914     symbolize::LLVMSymbolizer::Options SymbolizerOpts(
915         DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
916         DefaultArch);
917     Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
918   }
919   virtual ~SourcePrinter() = default;
920   virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
921                                StringRef Delimiter = "; ");
922 };
923 
924 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
925   std::unique_ptr<MemoryBuffer> Buffer;
926   if (LineInfo.Source) {
927     Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
928   } else {
929     auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
930     if (!BufferOrError)
931       return false;
932     Buffer = std::move(*BufferOrError);
933   }
934   // Chomp the file to get lines
935   size_t BufferSize = Buffer->getBufferSize();
936   const char *BufferStart = Buffer->getBufferStart();
937   for (const char *Start = BufferStart, *End = BufferStart;
938        End < BufferStart + BufferSize; End++)
939     if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
940         (*End == '\r' && *(End + 1) == '\n')) {
941       LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
942       if (*End == '\r')
943         End++;
944       Start = End + 1;
945     }
946   SourceCache[LineInfo.FileName] = std::move(Buffer);
947   return true;
948 }
949 
950 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
951                                     StringRef Delimiter) {
952   if (!Symbolizer)
953     return;
954   DILineInfo LineInfo = DILineInfo();
955   auto ExpectecLineInfo =
956       Symbolizer->symbolizeCode(Obj->getFileName(), Address);
957   if (!ExpectecLineInfo)
958     consumeError(ExpectecLineInfo.takeError());
959   else
960     LineInfo = *ExpectecLineInfo;
961 
962   if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
963       LineInfo.Line == 0)
964     return;
965 
966   if (PrintLines)
967     OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
968   if (PrintSource) {
969     if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
970       if (!cacheSource(LineInfo))
971         return;
972     auto FileBuffer = SourceCache.find(LineInfo.FileName);
973     if (FileBuffer != SourceCache.end()) {
974       auto LineBuffer = LineCache.find(LineInfo.FileName);
975       if (LineBuffer != LineCache.end()) {
976         if (LineInfo.Line > LineBuffer->second.size())
977           return;
978         // Vector begins at 0, line numbers are non-zero
979         OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
980            << "\n";
981       }
982     }
983   }
984   OldLineInfo = LineInfo;
985 }
986 
987 static bool isArmElf(const ObjectFile *Obj) {
988   return (Obj->isELF() &&
989           (Obj->getArch() == Triple::aarch64 ||
990            Obj->getArch() == Triple::aarch64_be ||
991            Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
992            Obj->getArch() == Triple::thumb ||
993            Obj->getArch() == Triple::thumbeb));
994 }
995 
996 class PrettyPrinter {
997 public:
998   virtual ~PrettyPrinter() = default;
999   virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
1000                          ArrayRef<uint8_t> Bytes, uint64_t Address,
1001                          raw_ostream &OS, StringRef Annot,
1002                          MCSubtargetInfo const &STI, SourcePrinter *SP,
1003                          std::vector<RelocationRef> *Rels = nullptr) {
1004     if (SP && (PrintSource || PrintLines))
1005       SP->printSourceLine(OS, Address);
1006     if (!NoLeadingAddr)
1007       OS << format("%8" PRIx64 ":", Address);
1008     if (!NoShowRawInsn) {
1009       OS << "\t";
1010       dumpBytes(Bytes, OS);
1011     }
1012     if (MI)
1013       IP.printInst(MI, OS, "", STI);
1014     else
1015       OS << " <unknown>";
1016   }
1017 };
1018 PrettyPrinter PrettyPrinterInst;
1019 class HexagonPrettyPrinter : public PrettyPrinter {
1020 public:
1021   void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1022                  raw_ostream &OS) {
1023     uint32_t opcode =
1024       (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1025     if (!NoLeadingAddr)
1026       OS << format("%8" PRIx64 ":", Address);
1027     if (!NoShowRawInsn) {
1028       OS << "\t";
1029       dumpBytes(Bytes.slice(0, 4), OS);
1030       OS << format("%08" PRIx32, opcode);
1031     }
1032   }
1033   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1034                  uint64_t Address, raw_ostream &OS, StringRef Annot,
1035                  MCSubtargetInfo const &STI, SourcePrinter *SP,
1036                  std::vector<RelocationRef> *Rels) override {
1037     if (SP && (PrintSource || PrintLines))
1038       SP->printSourceLine(OS, Address, "");
1039     if (!MI) {
1040       printLead(Bytes, Address, OS);
1041       OS << " <unknown>";
1042       return;
1043     }
1044     std::string Buffer;
1045     {
1046       raw_string_ostream TempStream(Buffer);
1047       IP.printInst(MI, TempStream, "", STI);
1048     }
1049     StringRef Contents(Buffer);
1050     // Split off bundle attributes
1051     auto PacketBundle = Contents.rsplit('\n');
1052     // Split off first instruction from the rest
1053     auto HeadTail = PacketBundle.first.split('\n');
1054     auto Preamble = " { ";
1055     auto Separator = "";
1056     StringRef Fmt = "\t\t\t%08" PRIx64 ":  ";
1057     std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
1058     std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
1059 
1060     // Hexagon's packets require relocations to be inline rather than
1061     // clustered at the end of the packet.
1062     auto PrintReloc = [&]() -> void {
1063       while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) {
1064         if (RelCur->getOffset() == Address) {
1065           SmallString<16> Name;
1066           SmallString<32> Val;
1067           RelCur->getTypeName(Name);
1068           error(getRelocationValueString(*RelCur, Val));
1069           OS << Separator << format(Fmt.data(), Address) << Name << "\t" << Val
1070                 << "\n";
1071           return;
1072         }
1073         ++RelCur;
1074       }
1075     };
1076 
1077     while (!HeadTail.first.empty()) {
1078       OS << Separator;
1079       Separator = "\n";
1080       if (SP && (PrintSource || PrintLines))
1081         SP->printSourceLine(OS, Address, "");
1082       printLead(Bytes, Address, OS);
1083       OS << Preamble;
1084       Preamble = "   ";
1085       StringRef Inst;
1086       auto Duplex = HeadTail.first.split('\v');
1087       if (!Duplex.second.empty()) {
1088         OS << Duplex.first;
1089         OS << "; ";
1090         Inst = Duplex.second;
1091       }
1092       else
1093         Inst = HeadTail.first;
1094       OS << Inst;
1095       HeadTail = HeadTail.second.split('\n');
1096       if (HeadTail.first.empty())
1097         OS << " } " << PacketBundle.second;
1098       PrintReloc();
1099       Bytes = Bytes.slice(4);
1100       Address += 4;
1101     }
1102   }
1103 };
1104 HexagonPrettyPrinter HexagonPrettyPrinterInst;
1105 
1106 class AMDGCNPrettyPrinter : public PrettyPrinter {
1107 public:
1108   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1109                  uint64_t Address, raw_ostream &OS, StringRef Annot,
1110                  MCSubtargetInfo const &STI, SourcePrinter *SP,
1111                  std::vector<RelocationRef> *Rels) override {
1112     if (SP && (PrintSource || PrintLines))
1113       SP->printSourceLine(OS, Address);
1114 
1115     typedef support::ulittle32_t U32;
1116 
1117     if (MI) {
1118       SmallString<40> InstStr;
1119       raw_svector_ostream IS(InstStr);
1120 
1121       IP.printInst(MI, IS, "", STI);
1122 
1123       OS << left_justify(IS.str(), 60);
1124     } else {
1125       // an unrecognized encoding - this is probably data so represent it
1126       // using the .long directive, or .byte directive if fewer than 4 bytes
1127       // remaining
1128       if (Bytes.size() >= 4) {
1129         OS << format("\t.long 0x%08" PRIx32 " ",
1130                      static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1131         OS.indent(42);
1132       } else {
1133           OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1134           for (unsigned int i = 1; i < Bytes.size(); i++)
1135             OS << format(", 0x%02" PRIx8, Bytes[i]);
1136           OS.indent(55 - (6 * Bytes.size()));
1137       }
1138     }
1139 
1140     OS << format("// %012" PRIX64 ": ", Address);
1141     if (Bytes.size() >=4) {
1142       for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1143                                  Bytes.size() / sizeof(U32)))
1144         // D should be explicitly casted to uint32_t here as it is passed
1145         // by format to snprintf as vararg.
1146         OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1147     } else {
1148       for (unsigned int i = 0; i < Bytes.size(); i++)
1149         OS << format("%02" PRIX8 " ", Bytes[i]);
1150     }
1151 
1152     if (!Annot.empty())
1153       OS << "// " << Annot;
1154   }
1155 };
1156 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1157 
1158 class BPFPrettyPrinter : public PrettyPrinter {
1159 public:
1160   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1161                  uint64_t Address, raw_ostream &OS, StringRef Annot,
1162                  MCSubtargetInfo const &STI, SourcePrinter *SP,
1163                  std::vector<RelocationRef> *Rels) override {
1164     if (SP && (PrintSource || PrintLines))
1165       SP->printSourceLine(OS, Address);
1166     if (!NoLeadingAddr)
1167       OS << format("%8" PRId64 ":", Address / 8);
1168     if (!NoShowRawInsn) {
1169       OS << "\t";
1170       dumpBytes(Bytes, OS);
1171     }
1172     if (MI)
1173       IP.printInst(MI, OS, "", STI);
1174     else
1175       OS << " <unknown>";
1176   }
1177 };
1178 BPFPrettyPrinter BPFPrettyPrinterInst;
1179 
1180 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1181   switch(Triple.getArch()) {
1182   default:
1183     return PrettyPrinterInst;
1184   case Triple::hexagon:
1185     return HexagonPrettyPrinterInst;
1186   case Triple::amdgcn:
1187     return AMDGCNPrettyPrinterInst;
1188   case Triple::bpfel:
1189   case Triple::bpfeb:
1190     return BPFPrettyPrinterInst;
1191   }
1192 }
1193 }
1194 
1195 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1196   assert(Obj->isELF());
1197   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1198     return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1199   if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1200     return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1201   if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1202     return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1203   if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1204     return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1205   llvm_unreachable("Unsupported binary format");
1206 }
1207 
1208 template <class ELFT> static void
1209 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1210                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1211   for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1212     uint8_t SymbolType = Symbol.getELFType();
1213     if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1214       continue;
1215 
1216     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1217     if (!AddressOrErr)
1218       report_error(Obj->getFileName(), AddressOrErr.takeError());
1219 
1220     Expected<StringRef> Name = Symbol.getName();
1221     if (!Name)
1222       report_error(Obj->getFileName(), Name.takeError());
1223     if (Name->empty())
1224       continue;
1225 
1226     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1227     if (!SectionOrErr)
1228       report_error(Obj->getFileName(), SectionOrErr.takeError());
1229     section_iterator SecI = *SectionOrErr;
1230     if (SecI == Obj->section_end())
1231       continue;
1232 
1233     AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType);
1234   }
1235 }
1236 
1237 static void
1238 addDynamicElfSymbols(const ObjectFile *Obj,
1239                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1240   assert(Obj->isELF());
1241   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1242     addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1243   else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1244     addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1245   else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1246     addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1247   else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1248     addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1249   else
1250     llvm_unreachable("Unsupported binary format");
1251 }
1252 
1253 static void addPltEntries(const ObjectFile *Obj,
1254                           std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1255                           StringSaver &Saver) {
1256   Optional<SectionRef> Plt = None;
1257   for (const SectionRef &Section : Obj->sections()) {
1258     StringRef Name;
1259     if (Section.getName(Name))
1260       continue;
1261     if (Name == ".plt")
1262       Plt = Section;
1263   }
1264   if (!Plt)
1265     return;
1266   if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1267     for (auto PltEntry : ElfObj->getPltAddresses()) {
1268       SymbolRef Symbol(PltEntry.first, ElfObj);
1269       uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1270 
1271       Expected<StringRef> NameOrErr = Symbol.getName();
1272       if (!NameOrErr)
1273         report_error(Obj->getFileName(), NameOrErr.takeError());
1274       if (NameOrErr->empty())
1275         continue;
1276       StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1277 
1278       AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1279     }
1280   }
1281 }
1282 
1283 // Normally the disassembly output will skip blocks of zeroes. This function
1284 // returns the number of zero bytes that can be skipped when dumping the
1285 // disassembly of the instructions in Buf.
1286 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
1287   // When -z or --disassemble-zeroes are given we always dissasemble them.
1288   if (DisassembleZeroes)
1289     return 0;
1290 
1291   // Find the number of leading zeroes.
1292   size_t N = 0;
1293   while (N < Buf.size() && !Buf[N])
1294     ++N;
1295 
1296   // We may want to skip blocks of zero bytes, but unless we see
1297   // at least 8 of them in a row.
1298   if (N < 8)
1299     return 0;
1300 
1301   // We skip zeroes in multiples of 4 because do not want to truncate an
1302   // instruction if it starts with a zero byte.
1303   return N & ~0x3;
1304 }
1305 
1306 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1307   if (StartAddress > StopAddress)
1308     error("Start address should be less than stop address");
1309 
1310   const Target *TheTarget = getTarget(Obj);
1311 
1312   // Package up features to be passed to target/subtarget
1313   SubtargetFeatures Features = Obj->getFeatures();
1314   if (!MAttrs.empty())
1315     for (unsigned I = 0; I != MAttrs.size(); ++I)
1316       Features.AddFeature(MAttrs[I]);
1317 
1318   std::unique_ptr<const MCRegisterInfo> MRI(
1319       TheTarget->createMCRegInfo(TripleName));
1320   if (!MRI)
1321     report_error(Obj->getFileName(), "no register info for target " +
1322                  TripleName);
1323 
1324   // Set up disassembler.
1325   std::unique_ptr<const MCAsmInfo> AsmInfo(
1326       TheTarget->createMCAsmInfo(*MRI, TripleName));
1327   if (!AsmInfo)
1328     report_error(Obj->getFileName(), "no assembly info for target " +
1329                  TripleName);
1330   std::unique_ptr<const MCSubtargetInfo> STI(
1331       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1332   if (!STI)
1333     report_error(Obj->getFileName(), "no subtarget info for target " +
1334                  TripleName);
1335   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1336   if (!MII)
1337     report_error(Obj->getFileName(), "no instruction info for target " +
1338                  TripleName);
1339   MCObjectFileInfo MOFI;
1340   MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1341   // FIXME: for now initialize MCObjectFileInfo with default values
1342   MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1343 
1344   std::unique_ptr<MCDisassembler> DisAsm(
1345     TheTarget->createMCDisassembler(*STI, Ctx));
1346   if (!DisAsm)
1347     report_error(Obj->getFileName(), "no disassembler for target " +
1348                  TripleName);
1349 
1350   std::unique_ptr<const MCInstrAnalysis> MIA(
1351       TheTarget->createMCInstrAnalysis(MII.get()));
1352 
1353   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1354   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1355       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1356   if (!IP)
1357     report_error(Obj->getFileName(), "no instruction printer for target " +
1358                  TripleName);
1359   IP->setPrintImmHex(PrintImmHex);
1360   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1361 
1362   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
1363                                                  "\t\t\t%08" PRIx64 ":  ";
1364 
1365   SourcePrinter SP(Obj, TheTarget->getName());
1366 
1367   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1368   // in RelocSecs contain the relocations for section S.
1369   std::error_code EC;
1370   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1371   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1372     section_iterator Sec2 = Section.getRelocatedSection();
1373     if (Sec2 != Obj->section_end())
1374       SectionRelocMap[*Sec2].push_back(Section);
1375   }
1376 
1377   // Create a mapping from virtual address to symbol name.  This is used to
1378   // pretty print the symbols while disassembling.
1379   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1380   SectionSymbolsTy AbsoluteSymbols;
1381   for (const SymbolRef &Symbol : Obj->symbols()) {
1382     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1383     if (!AddressOrErr)
1384       report_error(Obj->getFileName(), AddressOrErr.takeError());
1385     uint64_t Address = *AddressOrErr;
1386 
1387     Expected<StringRef> Name = Symbol.getName();
1388     if (!Name)
1389       report_error(Obj->getFileName(), Name.takeError());
1390     if (Name->empty())
1391       continue;
1392 
1393     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1394     if (!SectionOrErr)
1395       report_error(Obj->getFileName(), SectionOrErr.takeError());
1396 
1397     uint8_t SymbolType = ELF::STT_NOTYPE;
1398     if (Obj->isELF())
1399       SymbolType = getElfSymbolType(Obj, Symbol);
1400 
1401     section_iterator SecI = *SectionOrErr;
1402     if (SecI != Obj->section_end())
1403       AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1404     else
1405       AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1406 
1407 
1408   }
1409   if (AllSymbols.empty() && Obj->isELF())
1410     addDynamicElfSymbols(Obj, AllSymbols);
1411 
1412   BumpPtrAllocator A;
1413   StringSaver Saver(A);
1414   addPltEntries(Obj, AllSymbols, Saver);
1415 
1416   // Create a mapping from virtual address to section.
1417   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1418   for (SectionRef Sec : Obj->sections())
1419     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1420   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1421 
1422   // Linked executables (.exe and .dll files) typically don't include a real
1423   // symbol table but they might contain an export table.
1424   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1425     for (const auto &ExportEntry : COFFObj->export_directories()) {
1426       StringRef Name;
1427       error(ExportEntry.getSymbolName(Name));
1428       if (Name.empty())
1429         continue;
1430       uint32_t RVA;
1431       error(ExportEntry.getExportRVA(RVA));
1432 
1433       uint64_t VA = COFFObj->getImageBase() + RVA;
1434       auto Sec = std::upper_bound(
1435           SectionAddresses.begin(), SectionAddresses.end(), VA,
1436           [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1437             return LHS < RHS.first;
1438           });
1439       if (Sec != SectionAddresses.begin())
1440         --Sec;
1441       else
1442         Sec = SectionAddresses.end();
1443 
1444       if (Sec != SectionAddresses.end())
1445         AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1446       else
1447         AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1448     }
1449   }
1450 
1451   // Sort all the symbols, this allows us to use a simple binary search to find
1452   // a symbol near an address.
1453   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1454     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1455   array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1456 
1457   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1458     if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1459       continue;
1460 
1461     uint64_t SectionAddr = Section.getAddress();
1462     uint64_t SectSize = Section.getSize();
1463     if (!SectSize)
1464       continue;
1465 
1466     // Get the list of all the symbols in this section.
1467     SectionSymbolsTy &Symbols = AllSymbols[Section];
1468     std::vector<uint64_t> DataMappingSymsAddr;
1469     std::vector<uint64_t> TextMappingSymsAddr;
1470     if (isArmElf(Obj)) {
1471       for (const auto &Symb : Symbols) {
1472         uint64_t Address = Symb.Address;
1473         StringRef Name = Symb.Name;
1474         if (Name.startswith("$d"))
1475           DataMappingSymsAddr.push_back(Address - SectionAddr);
1476         if (Name.startswith("$x"))
1477           TextMappingSymsAddr.push_back(Address - SectionAddr);
1478         if (Name.startswith("$a"))
1479           TextMappingSymsAddr.push_back(Address - SectionAddr);
1480         if (Name.startswith("$t"))
1481           TextMappingSymsAddr.push_back(Address - SectionAddr);
1482       }
1483     }
1484 
1485     llvm::sort(DataMappingSymsAddr);
1486     llvm::sort(TextMappingSymsAddr);
1487 
1488     if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1489       // AMDGPU disassembler uses symbolizer for printing labels
1490       std::unique_ptr<MCRelocationInfo> RelInfo(
1491         TheTarget->createMCRelocationInfo(TripleName, Ctx));
1492       if (RelInfo) {
1493         std::unique_ptr<MCSymbolizer> Symbolizer(
1494           TheTarget->createMCSymbolizer(
1495             TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1496         DisAsm->setSymbolizer(std::move(Symbolizer));
1497       }
1498     }
1499 
1500     // Make a list of all the relocations for this section.
1501     std::vector<RelocationRef> Rels;
1502     if (InlineRelocs) {
1503       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1504         for (const RelocationRef &Reloc : RelocSec.relocations()) {
1505           Rels.push_back(Reloc);
1506         }
1507       }
1508     }
1509 
1510     // Sort relocations by address.
1511     llvm::sort(Rels, isRelocAddressLess);
1512 
1513     StringRef SegmentName = "";
1514     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1515       DataRefImpl DR = Section.getRawDataRefImpl();
1516       SegmentName = MachO->getSectionFinalSegmentName(DR);
1517     }
1518     StringRef SectionName;
1519     error(Section.getName(SectionName));
1520 
1521     // If the section has no symbol at the start, just insert a dummy one.
1522     if (Symbols.empty() || Symbols[0].Address != 0) {
1523       Symbols.insert(
1524           Symbols.begin(),
1525           SectionSymbol(SectionAddr, SectionName,
1526                         Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1527     }
1528 
1529     SmallString<40> Comments;
1530     raw_svector_ostream CommentStream(Comments);
1531 
1532     StringRef BytesStr;
1533     error(Section.getContents(BytesStr));
1534     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1535                             BytesStr.size());
1536 
1537     uint64_t Size;
1538     uint64_t Index;
1539     bool PrintedSection = false;
1540 
1541     std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1542     std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1543     // Disassemble symbol by symbol.
1544     for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1545       uint64_t Start = Symbols[SI].Address - SectionAddr;
1546       // The end is either the section end or the beginning of the next
1547       // symbol.
1548       uint64_t End = (SI == SE - 1)
1549                          ? SectSize
1550                          : Symbols[SI + 1].Address - SectionAddr;
1551       // Don't try to disassemble beyond the end of section contents.
1552       if (End > SectSize)
1553         End = SectSize;
1554       // If this symbol has the same address as the next symbol, then skip it.
1555       if (Start >= End)
1556         continue;
1557 
1558       // Check if we need to skip symbol
1559       // Skip if the symbol's data is not between StartAddress and StopAddress
1560       if (End + SectionAddr < StartAddress ||
1561           Start + SectionAddr > StopAddress) {
1562         continue;
1563       }
1564 
1565       /// Skip if user requested specific symbols and this is not in the list
1566       if (!DisasmFuncsSet.empty() && !DisasmFuncsSet.count(Symbols[SI].Name))
1567         continue;
1568 
1569       if (!PrintedSection) {
1570         PrintedSection = true;
1571         outs() << "Disassembly of section ";
1572         if (!SegmentName.empty())
1573           outs() << SegmentName << ",";
1574         outs() << SectionName << ':';
1575       }
1576 
1577       // Stop disassembly at the stop address specified
1578       if (End + SectionAddr > StopAddress)
1579         End = StopAddress - SectionAddr;
1580 
1581       if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1582         if (Symbols[SI].Type == ELF::STT_AMDGPU_HSA_KERNEL) {
1583           // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1584           Start += 256;
1585         }
1586         if (SI == SE - 1 ||
1587             Symbols[SI + 1].Type == ELF::STT_AMDGPU_HSA_KERNEL) {
1588           // cut trailing zeroes at the end of kernel
1589           // cut up to 256 bytes
1590           const uint64_t EndAlign = 256;
1591           const auto Limit = End - (std::min)(EndAlign, End - Start);
1592           while (End > Limit &&
1593             *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1594             End -= 4;
1595         }
1596       }
1597 
1598       outs() << '\n';
1599       if (!NoLeadingAddr)
1600         outs() << format("%016" PRIx64 " ", SectionAddr + Start);
1601 
1602       StringRef SymbolName = Symbols[SI].Name;
1603       if (Demangle)
1604         outs() << demangle(SymbolName) << ":\n";
1605       else
1606         outs() << SymbolName << ":\n";
1607 
1608       // Don't print raw contents of a virtual section. A virtual section
1609       // doesn't have any contents in the file.
1610       if (Section.isVirtual()) {
1611         outs() << "...\n";
1612         continue;
1613       }
1614 
1615 #ifndef NDEBUG
1616       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1617 #else
1618       raw_ostream &DebugOut = nulls();
1619 #endif
1620 
1621       // Some targets (like WebAssembly) have a special prelude at the start
1622       // of each symbol.
1623       DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1624                             SectionAddr + Start, DebugOut, CommentStream);
1625       Start += Size;
1626 
1627       for (Index = Start; Index < End; Index += Size) {
1628         MCInst Inst;
1629 
1630         if (Index + SectionAddr < StartAddress ||
1631             Index + SectionAddr > StopAddress) {
1632           // skip byte by byte till StartAddress is reached
1633           Size = 1;
1634           continue;
1635         }
1636         // AArch64 ELF binaries can interleave data and text in the
1637         // same section. We rely on the markers introduced to
1638         // understand what we need to dump. If the data marker is within a
1639         // function, it is denoted as a word/short etc
1640         if (isArmElf(Obj) && Symbols[SI].Type != ELF::STT_OBJECT &&
1641             !DisassembleAll) {
1642           uint64_t Stride = 0;
1643 
1644           auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1645                                       DataMappingSymsAddr.end(), Index);
1646           if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1647             // Switch to data.
1648             while (Index < End) {
1649               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1650               outs() << "\t";
1651               if (Index + 4 <= End) {
1652                 Stride = 4;
1653                 dumpBytes(Bytes.slice(Index, 4), outs());
1654                 outs() << "\t.word\t";
1655                 uint32_t Data = 0;
1656                 if (Obj->isLittleEndian()) {
1657                   const auto Word =
1658                       reinterpret_cast<const support::ulittle32_t *>(
1659                           Bytes.data() + Index);
1660                   Data = *Word;
1661                 } else {
1662                   const auto Word = reinterpret_cast<const support::ubig32_t *>(
1663                       Bytes.data() + Index);
1664                   Data = *Word;
1665                 }
1666                 outs() << "0x" << format("%08" PRIx32, Data);
1667               } else if (Index + 2 <= End) {
1668                 Stride = 2;
1669                 dumpBytes(Bytes.slice(Index, 2), outs());
1670                 outs() << "\t\t.short\t";
1671                 uint16_t Data = 0;
1672                 if (Obj->isLittleEndian()) {
1673                   const auto Short =
1674                       reinterpret_cast<const support::ulittle16_t *>(
1675                           Bytes.data() + Index);
1676                   Data = *Short;
1677                 } else {
1678                   const auto Short =
1679                       reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1680                                                                   Index);
1681                   Data = *Short;
1682                 }
1683                 outs() << "0x" << format("%04" PRIx16, Data);
1684               } else {
1685                 Stride = 1;
1686                 dumpBytes(Bytes.slice(Index, 1), outs());
1687                 outs() << "\t\t.byte\t";
1688                 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1689               }
1690               Index += Stride;
1691               outs() << "\n";
1692               auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1693                                           TextMappingSymsAddr.end(), Index);
1694               if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1695                 break;
1696             }
1697           }
1698         }
1699 
1700         // If there is a data symbol inside an ELF text section and we are only
1701         // disassembling text (applicable all architectures),
1702         // we are in a situation where we must print the data and not
1703         // disassemble it.
1704         if (Obj->isELF() && Symbols[SI].Type == ELF::STT_OBJECT &&
1705             !DisassembleAll && Section.isText()) {
1706           // print out data up to 8 bytes at a time in hex and ascii
1707           uint8_t AsciiData[9] = {'\0'};
1708           uint8_t Byte;
1709           int NumBytes = 0;
1710 
1711           for (Index = Start; Index < End; Index += 1) {
1712             if (((SectionAddr + Index) < StartAddress) ||
1713                 ((SectionAddr + Index) > StopAddress))
1714               continue;
1715             if (NumBytes == 0) {
1716               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1717               outs() << "\t";
1718             }
1719             Byte = Bytes.slice(Index)[0];
1720             outs() << format(" %02x", Byte);
1721             AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1722 
1723             uint8_t IndentOffset = 0;
1724             NumBytes++;
1725             if (Index == End - 1 || NumBytes > 8) {
1726               // Indent the space for less than 8 bytes data.
1727               // 2 spaces for byte and one for space between bytes
1728               IndentOffset = 3 * (8 - NumBytes);
1729               for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1730                 AsciiData[Excess] = '\0';
1731               NumBytes = 8;
1732             }
1733             if (NumBytes == 8) {
1734               AsciiData[8] = '\0';
1735               outs() << std::string(IndentOffset, ' ') << "         ";
1736               outs() << reinterpret_cast<char *>(AsciiData);
1737               outs() << '\n';
1738               NumBytes = 0;
1739             }
1740           }
1741         }
1742         if (Index >= End)
1743           break;
1744 
1745         if (size_t N =
1746                 countSkippableZeroBytes(Bytes.slice(Index, End - Index))) {
1747           outs() << "\t\t..." << '\n';
1748           Index += N;
1749           if (Index >= End)
1750             break;
1751         }
1752 
1753         // Disassemble a real instruction or a data when disassemble all is
1754         // provided
1755         bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1756                                                    SectionAddr + Index, DebugOut,
1757                                                    CommentStream);
1758         if (Size == 0)
1759           Size = 1;
1760 
1761         PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1762                       Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1763                       *STI, &SP, &Rels);
1764         outs() << CommentStream.str();
1765         Comments.clear();
1766 
1767         // Try to resolve the target of a call, tail call, etc. to a specific
1768         // symbol.
1769         if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1770                     MIA->isConditionalBranch(Inst))) {
1771           uint64_t Target;
1772           if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1773             // In a relocatable object, the target's section must reside in
1774             // the same section as the call instruction or it is accessed
1775             // through a relocation.
1776             //
1777             // In a non-relocatable object, the target may be in any section.
1778             //
1779             // N.B. We don't walk the relocations in the relocatable case yet.
1780             auto *TargetSectionSymbols = &Symbols;
1781             if (!Obj->isRelocatableObject()) {
1782               auto SectionAddress = std::upper_bound(
1783                   SectionAddresses.begin(), SectionAddresses.end(), Target,
1784                   [](uint64_t LHS,
1785                       const std::pair<uint64_t, SectionRef> &RHS) {
1786                     return LHS < RHS.first;
1787                   });
1788               if (SectionAddress != SectionAddresses.begin()) {
1789                 --SectionAddress;
1790                 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1791               } else {
1792                 TargetSectionSymbols = &AbsoluteSymbols;
1793               }
1794             }
1795 
1796             // Find the first symbol in the section whose offset is less than
1797             // or equal to the target. If there isn't a section that contains
1798             // the target, find the nearest preceding absolute symbol.
1799             auto TargetSym = std::upper_bound(
1800                 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1801                 Target, [](uint64_t LHS, const SectionSymbol &RHS) {
1802                   return LHS < RHS.Address;
1803                 });
1804             if (TargetSym == TargetSectionSymbols->begin()) {
1805               TargetSectionSymbols = &AbsoluteSymbols;
1806               TargetSym = std::upper_bound(
1807                   AbsoluteSymbols.begin(), AbsoluteSymbols.end(), Target,
1808                   [](uint64_t LHS, const SectionSymbol &RHS) {
1809                     return LHS < RHS.Address;
1810                   });
1811             }
1812             if (TargetSym != TargetSectionSymbols->begin()) {
1813               --TargetSym;
1814               outs() << " <" << TargetSym->Name;
1815               uint64_t Disp = Target - TargetSym->Address;
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