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