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