]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-objdump/llvm-objdump.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r308421, and update
[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/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 (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
874     fmt << format("0x%x", Val);
875     return;
876   } else if (isExtern) {
877     symbol_iterator SI = O->symbol_begin();
878     advance(SI, Val);
879     Expected<StringRef> SOrErr = SI->getName();
880     if (!SOrErr)
881       report_error(O->getFileName(), SOrErr.takeError());
882     S = *SOrErr;
883   } else {
884     section_iterator SI = O->section_begin();
885     // Adjust for the fact that sections are 1-indexed.
886     advance(SI, Val - 1);
887     SI->getName(S);
888   }
889
890   fmt << S;
891 }
892
893 static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
894                                                 const RelocationRef &RelRef,
895                                                 SmallVectorImpl<char> &Result) {
896   const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
897   std::string fmtbuf;
898   raw_string_ostream fmt(fmtbuf);
899   fmt << Rel.Index << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
900   fmt.flush();
901   Result.append(fmtbuf.begin(), fmtbuf.end());
902   return std::error_code();
903 }
904
905 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
906                                                 const RelocationRef &RelRef,
907                                                 SmallVectorImpl<char> &Result) {
908   DataRefImpl Rel = RelRef.getRawDataRefImpl();
909   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
910
911   unsigned Arch = Obj->getArch();
912
913   std::string fmtbuf;
914   raw_string_ostream fmt(fmtbuf);
915   unsigned Type = Obj->getAnyRelocationType(RE);
916   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
917
918   // Determine any addends that should be displayed with the relocation.
919   // These require decoding the relocation type, which is triple-specific.
920
921   // X86_64 has entirely custom relocation types.
922   if (Arch == Triple::x86_64) {
923     bool isPCRel = Obj->getAnyRelocationPCRel(RE);
924
925     switch (Type) {
926     case MachO::X86_64_RELOC_GOT_LOAD:
927     case MachO::X86_64_RELOC_GOT: {
928       printRelocationTargetName(Obj, RE, fmt);
929       fmt << "@GOT";
930       if (isPCRel)
931         fmt << "PCREL";
932       break;
933     }
934     case MachO::X86_64_RELOC_SUBTRACTOR: {
935       DataRefImpl RelNext = Rel;
936       Obj->moveRelocationNext(RelNext);
937       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
938
939       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
940       // X86_64_RELOC_UNSIGNED.
941       // NOTE: Scattered relocations don't exist on x86_64.
942       unsigned RType = Obj->getAnyRelocationType(RENext);
943       if (RType != MachO::X86_64_RELOC_UNSIGNED)
944         report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
945                      "X86_64_RELOC_SUBTRACTOR.");
946
947       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
948       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
949       printRelocationTargetName(Obj, RENext, fmt);
950       fmt << "-";
951       printRelocationTargetName(Obj, RE, fmt);
952       break;
953     }
954     case MachO::X86_64_RELOC_TLV:
955       printRelocationTargetName(Obj, RE, fmt);
956       fmt << "@TLV";
957       if (isPCRel)
958         fmt << "P";
959       break;
960     case MachO::X86_64_RELOC_SIGNED_1:
961       printRelocationTargetName(Obj, RE, fmt);
962       fmt << "-1";
963       break;
964     case MachO::X86_64_RELOC_SIGNED_2:
965       printRelocationTargetName(Obj, RE, fmt);
966       fmt << "-2";
967       break;
968     case MachO::X86_64_RELOC_SIGNED_4:
969       printRelocationTargetName(Obj, RE, fmt);
970       fmt << "-4";
971       break;
972     default:
973       printRelocationTargetName(Obj, RE, fmt);
974       break;
975     }
976     // X86 and ARM share some relocation types in common.
977   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
978              Arch == Triple::ppc) {
979     // Generic relocation types...
980     switch (Type) {
981     case MachO::GENERIC_RELOC_PAIR: // prints no info
982       return std::error_code();
983     case MachO::GENERIC_RELOC_SECTDIFF: {
984       DataRefImpl RelNext = Rel;
985       Obj->moveRelocationNext(RelNext);
986       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
987
988       // X86 sect diff's must be followed by a relocation of type
989       // GENERIC_RELOC_PAIR.
990       unsigned RType = Obj->getAnyRelocationType(RENext);
991
992       if (RType != MachO::GENERIC_RELOC_PAIR)
993         report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
994                      "GENERIC_RELOC_SECTDIFF.");
995
996       printRelocationTargetName(Obj, RE, fmt);
997       fmt << "-";
998       printRelocationTargetName(Obj, RENext, fmt);
999       break;
1000     }
1001     }
1002
1003     if (Arch == Triple::x86 || Arch == Triple::ppc) {
1004       switch (Type) {
1005       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1006         DataRefImpl RelNext = Rel;
1007         Obj->moveRelocationNext(RelNext);
1008         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1009
1010         // X86 sect diff's must be followed by a relocation of type
1011         // GENERIC_RELOC_PAIR.
1012         unsigned RType = Obj->getAnyRelocationType(RENext);
1013         if (RType != MachO::GENERIC_RELOC_PAIR)
1014           report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
1015                        "GENERIC_RELOC_LOCAL_SECTDIFF.");
1016
1017         printRelocationTargetName(Obj, RE, fmt);
1018         fmt << "-";
1019         printRelocationTargetName(Obj, RENext, fmt);
1020         break;
1021       }
1022       case MachO::GENERIC_RELOC_TLV: {
1023         printRelocationTargetName(Obj, RE, fmt);
1024         fmt << "@TLV";
1025         if (IsPCRel)
1026           fmt << "P";
1027         break;
1028       }
1029       default:
1030         printRelocationTargetName(Obj, RE, fmt);
1031       }
1032     } else { // ARM-specific relocations
1033       switch (Type) {
1034       case MachO::ARM_RELOC_HALF:
1035       case MachO::ARM_RELOC_HALF_SECTDIFF: {
1036         // Half relocations steal a bit from the length field to encode
1037         // whether this is an upper16 or a lower16 relocation.
1038         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
1039
1040         if (isUpper)
1041           fmt << ":upper16:(";
1042         else
1043           fmt << ":lower16:(";
1044         printRelocationTargetName(Obj, RE, fmt);
1045
1046         DataRefImpl RelNext = Rel;
1047         Obj->moveRelocationNext(RelNext);
1048         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1049
1050         // ARM half relocs must be followed by a relocation of type
1051         // ARM_RELOC_PAIR.
1052         unsigned RType = Obj->getAnyRelocationType(RENext);
1053         if (RType != MachO::ARM_RELOC_PAIR)
1054           report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1055                        "ARM_RELOC_HALF");
1056
1057         // NOTE: The half of the target virtual address is stashed in the
1058         // address field of the secondary relocation, but we can't reverse
1059         // engineer the constant offset from it without decoding the movw/movt
1060         // instruction to find the other half in its immediate field.
1061
1062         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1063         // symbol/section pointer of the follow-on relocation.
1064         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1065           fmt << "-";
1066           printRelocationTargetName(Obj, RENext, fmt);
1067         }
1068
1069         fmt << ")";
1070         break;
1071       }
1072       default: { printRelocationTargetName(Obj, RE, fmt); }
1073       }
1074     }
1075   } else
1076     printRelocationTargetName(Obj, RE, fmt);
1077
1078   fmt.flush();
1079   Result.append(fmtbuf.begin(), fmtbuf.end());
1080   return std::error_code();
1081 }
1082
1083 static std::error_code getRelocationValueString(const RelocationRef &Rel,
1084                                                 SmallVectorImpl<char> &Result) {
1085   const ObjectFile *Obj = Rel.getObject();
1086   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1087     return getRelocationValueString(ELF, Rel, Result);
1088   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1089     return getRelocationValueString(COFF, Rel, Result);
1090   if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
1091     return getRelocationValueString(Wasm, Rel, Result);
1092   if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
1093     return getRelocationValueString(MachO, Rel, Result);
1094   llvm_unreachable("unknown object file format");
1095 }
1096
1097 /// @brief Indicates whether this relocation should hidden when listing
1098 /// relocations, usually because it is the trailing part of a multipart
1099 /// relocation that will be printed as part of the leading relocation.
1100 static bool getHidden(RelocationRef RelRef) {
1101   const ObjectFile *Obj = RelRef.getObject();
1102   auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1103   if (!MachO)
1104     return false;
1105
1106   unsigned Arch = MachO->getArch();
1107   DataRefImpl Rel = RelRef.getRawDataRefImpl();
1108   uint64_t Type = MachO->getRelocationType(Rel);
1109
1110   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1111   // is always hidden.
1112   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1113     if (Type == MachO::GENERIC_RELOC_PAIR)
1114       return true;
1115   } else if (Arch == Triple::x86_64) {
1116     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1117     // an X86_64_RELOC_SUBTRACTOR.
1118     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1119       DataRefImpl RelPrev = Rel;
1120       RelPrev.d.a--;
1121       uint64_t PrevType = MachO->getRelocationType(RelPrev);
1122       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1123         return true;
1124     }
1125   }
1126
1127   return false;
1128 }
1129
1130 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1131   assert(Obj->isELF());
1132   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1133     return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1134   if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1135     return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1136   if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1137     return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1138   if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1139     return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1140   llvm_unreachable("Unsupported binary format");
1141 }
1142
1143 template <class ELFT> static void
1144 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1145                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1146   for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1147     uint8_t SymbolType = Symbol.getELFType();
1148     if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1149       continue;
1150
1151     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1152     if (!AddressOrErr)
1153       report_error(Obj->getFileName(), AddressOrErr.takeError());
1154     uint64_t Address = *AddressOrErr;
1155
1156     Expected<StringRef> Name = Symbol.getName();
1157     if (!Name)
1158       report_error(Obj->getFileName(), Name.takeError());
1159     if (Name->empty())
1160       continue;
1161
1162     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1163     if (!SectionOrErr)
1164       report_error(Obj->getFileName(), SectionOrErr.takeError());
1165     section_iterator SecI = *SectionOrErr;
1166     if (SecI == Obj->section_end())
1167       continue;
1168
1169     AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1170   }
1171 }
1172
1173 static void
1174 addDynamicElfSymbols(const ObjectFile *Obj,
1175                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1176   assert(Obj->isELF());
1177   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1178     addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1179   else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1180     addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1181   else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1182     addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1183   else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1184     addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1185   else
1186     llvm_unreachable("Unsupported binary format");
1187 }
1188
1189 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1190   if (StartAddress > StopAddress)
1191     error("Start address should be less than stop address");
1192
1193   const Target *TheTarget = getTarget(Obj);
1194
1195   // Package up features to be passed to target/subtarget
1196   SubtargetFeatures Features = Obj->getFeatures();
1197   if (MAttrs.size()) {
1198     for (unsigned i = 0; i != MAttrs.size(); ++i)
1199       Features.AddFeature(MAttrs[i]);
1200   }
1201
1202   std::unique_ptr<const MCRegisterInfo> MRI(
1203       TheTarget->createMCRegInfo(TripleName));
1204   if (!MRI)
1205     report_error(Obj->getFileName(), "no register info for target " +
1206                  TripleName);
1207
1208   // Set up disassembler.
1209   std::unique_ptr<const MCAsmInfo> AsmInfo(
1210       TheTarget->createMCAsmInfo(*MRI, TripleName));
1211   if (!AsmInfo)
1212     report_error(Obj->getFileName(), "no assembly info for target " +
1213                  TripleName);
1214   std::unique_ptr<const MCSubtargetInfo> STI(
1215       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1216   if (!STI)
1217     report_error(Obj->getFileName(), "no subtarget info for target " +
1218                  TripleName);
1219   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1220   if (!MII)
1221     report_error(Obj->getFileName(), "no instruction info for target " +
1222                  TripleName);
1223   MCObjectFileInfo MOFI;
1224   MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1225   // FIXME: for now initialize MCObjectFileInfo with default values
1226   MOFI.InitMCObjectFileInfo(Triple(TripleName), false, CodeModel::Default, Ctx);
1227
1228   std::unique_ptr<MCDisassembler> DisAsm(
1229     TheTarget->createMCDisassembler(*STI, Ctx));
1230   if (!DisAsm)
1231     report_error(Obj->getFileName(), "no disassembler for target " +
1232                  TripleName);
1233
1234   std::unique_ptr<const MCInstrAnalysis> MIA(
1235       TheTarget->createMCInstrAnalysis(MII.get()));
1236
1237   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1238   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1239       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1240   if (!IP)
1241     report_error(Obj->getFileName(), "no instruction printer for target " +
1242                  TripleName);
1243   IP->setPrintImmHex(PrintImmHex);
1244   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1245
1246   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
1247                                                  "\t\t\t%08" PRIx64 ":  ";
1248
1249   SourcePrinter SP(Obj, TheTarget->getName());
1250
1251   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1252   // in RelocSecs contain the relocations for section S.
1253   std::error_code EC;
1254   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1255   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1256     section_iterator Sec2 = Section.getRelocatedSection();
1257     if (Sec2 != Obj->section_end())
1258       SectionRelocMap[*Sec2].push_back(Section);
1259   }
1260
1261   // Create a mapping from virtual address to symbol name.  This is used to
1262   // pretty print the symbols while disassembling.
1263   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1264   for (const SymbolRef &Symbol : Obj->symbols()) {
1265     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1266     if (!AddressOrErr)
1267       report_error(Obj->getFileName(), AddressOrErr.takeError());
1268     uint64_t Address = *AddressOrErr;
1269
1270     Expected<StringRef> Name = Symbol.getName();
1271     if (!Name)
1272       report_error(Obj->getFileName(), Name.takeError());
1273     if (Name->empty())
1274       continue;
1275
1276     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1277     if (!SectionOrErr)
1278       report_error(Obj->getFileName(), SectionOrErr.takeError());
1279     section_iterator SecI = *SectionOrErr;
1280     if (SecI == Obj->section_end())
1281       continue;
1282
1283     uint8_t SymbolType = ELF::STT_NOTYPE;
1284     if (Obj->isELF())
1285       SymbolType = getElfSymbolType(Obj, Symbol);
1286
1287     AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1288
1289   }
1290   if (AllSymbols.empty() && Obj->isELF())
1291     addDynamicElfSymbols(Obj, AllSymbols);
1292
1293   // Create a mapping from virtual address to section.
1294   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1295   for (SectionRef Sec : Obj->sections())
1296     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1297   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1298
1299   // Linked executables (.exe and .dll files) typically don't include a real
1300   // symbol table but they might contain an export table.
1301   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1302     for (const auto &ExportEntry : COFFObj->export_directories()) {
1303       StringRef Name;
1304       error(ExportEntry.getSymbolName(Name));
1305       if (Name.empty())
1306         continue;
1307       uint32_t RVA;
1308       error(ExportEntry.getExportRVA(RVA));
1309
1310       uint64_t VA = COFFObj->getImageBase() + RVA;
1311       auto Sec = std::upper_bound(
1312           SectionAddresses.begin(), SectionAddresses.end(), VA,
1313           [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1314             return LHS < RHS.first;
1315           });
1316       if (Sec != SectionAddresses.begin())
1317         --Sec;
1318       else
1319         Sec = SectionAddresses.end();
1320
1321       if (Sec != SectionAddresses.end())
1322         AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1323     }
1324   }
1325
1326   // Sort all the symbols, this allows us to use a simple binary search to find
1327   // a symbol near an address.
1328   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1329     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1330
1331   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1332     if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1333       continue;
1334
1335     uint64_t SectionAddr = Section.getAddress();
1336     uint64_t SectSize = Section.getSize();
1337     if (!SectSize)
1338       continue;
1339
1340     // Get the list of all the symbols in this section.
1341     SectionSymbolsTy &Symbols = AllSymbols[Section];
1342     std::vector<uint64_t> DataMappingSymsAddr;
1343     std::vector<uint64_t> TextMappingSymsAddr;
1344     if (isArmElf(Obj)) {
1345       for (const auto &Symb : Symbols) {
1346         uint64_t Address = std::get<0>(Symb);
1347         StringRef Name = std::get<1>(Symb);
1348         if (Name.startswith("$d"))
1349           DataMappingSymsAddr.push_back(Address - SectionAddr);
1350         if (Name.startswith("$x"))
1351           TextMappingSymsAddr.push_back(Address - SectionAddr);
1352         if (Name.startswith("$a"))
1353           TextMappingSymsAddr.push_back(Address - SectionAddr);
1354         if (Name.startswith("$t"))
1355           TextMappingSymsAddr.push_back(Address - SectionAddr);
1356       }
1357     }
1358
1359     std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1360     std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
1361
1362     if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1363       // AMDGPU disassembler uses symbolizer for printing labels
1364       std::unique_ptr<MCRelocationInfo> RelInfo(
1365         TheTarget->createMCRelocationInfo(TripleName, Ctx));
1366       if (RelInfo) {
1367         std::unique_ptr<MCSymbolizer> Symbolizer(
1368           TheTarget->createMCSymbolizer(
1369             TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1370         DisAsm->setSymbolizer(std::move(Symbolizer));
1371       }
1372     }
1373
1374     // Make a list of all the relocations for this section.
1375     std::vector<RelocationRef> Rels;
1376     if (InlineRelocs) {
1377       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1378         for (const RelocationRef &Reloc : RelocSec.relocations()) {
1379           Rels.push_back(Reloc);
1380         }
1381       }
1382     }
1383
1384     // Sort relocations by address.
1385     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1386
1387     StringRef SegmentName = "";
1388     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1389       DataRefImpl DR = Section.getRawDataRefImpl();
1390       SegmentName = MachO->getSectionFinalSegmentName(DR);
1391     }
1392     StringRef name;
1393     error(Section.getName(name));
1394
1395     if ((SectionAddr <= StopAddress) &&
1396         (SectionAddr + SectSize) >= StartAddress) {
1397     outs() << "Disassembly of section ";
1398     if (!SegmentName.empty())
1399       outs() << SegmentName << ",";
1400     outs() << name << ':';
1401     }
1402
1403     // If the section has no symbol at the start, just insert a dummy one.
1404     if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1405       Symbols.insert(Symbols.begin(),
1406                      std::make_tuple(SectionAddr, name, Section.isText()
1407                                                             ? ELF::STT_FUNC
1408                                                             : ELF::STT_OBJECT));
1409     }
1410
1411     SmallString<40> Comments;
1412     raw_svector_ostream CommentStream(Comments);
1413
1414     StringRef BytesStr;
1415     error(Section.getContents(BytesStr));
1416     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1417                             BytesStr.size());
1418
1419     uint64_t Size;
1420     uint64_t Index;
1421
1422     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1423     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1424     // Disassemble symbol by symbol.
1425     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1426       uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
1427       // The end is either the section end or the beginning of the next
1428       // symbol.
1429       uint64_t End =
1430           (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
1431       // Don't try to disassemble beyond the end of section contents.
1432       if (End > SectSize)
1433         End = SectSize;
1434       // If this symbol has the same address as the next symbol, then skip it.
1435       if (Start >= End)
1436         continue;
1437
1438       // Check if we need to skip symbol
1439       // Skip if the symbol's data is not between StartAddress and StopAddress
1440       if (End + SectionAddr < StartAddress ||
1441           Start + SectionAddr > StopAddress) {
1442         continue;
1443       }
1444
1445       // Stop disassembly at the stop address specified
1446       if (End + SectionAddr > StopAddress)
1447         End = StopAddress - SectionAddr;
1448
1449       if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1450         // make size 4 bytes folded
1451         End = Start + ((End - Start) & ~0x3ull);
1452         if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1453           // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1454           Start += 256;
1455         }
1456         if (si == se - 1 ||
1457             std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1458           // cut trailing zeroes at the end of kernel
1459           // cut up to 256 bytes
1460           const uint64_t EndAlign = 256;
1461           const auto Limit = End - (std::min)(EndAlign, End - Start);
1462           while (End > Limit &&
1463             *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1464             End -= 4;
1465         }
1466       }
1467
1468       outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
1469
1470 #ifndef NDEBUG
1471       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1472 #else
1473       raw_ostream &DebugOut = nulls();
1474 #endif
1475
1476       for (Index = Start; Index < End; Index += Size) {
1477         MCInst Inst;
1478
1479         if (Index + SectionAddr < StartAddress ||
1480             Index + SectionAddr > StopAddress) {
1481           // skip byte by byte till StartAddress is reached
1482           Size = 1;
1483           continue;
1484         }
1485         // AArch64 ELF binaries can interleave data and text in the
1486         // same section. We rely on the markers introduced to
1487         // understand what we need to dump. If the data marker is within a
1488         // function, it is denoted as a word/short etc
1489         if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1490             !DisassembleAll) {
1491           uint64_t Stride = 0;
1492
1493           auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1494                                       DataMappingSymsAddr.end(), Index);
1495           if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1496             // Switch to data.
1497             while (Index < End) {
1498               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1499               outs() << "\t";
1500               if (Index + 4 <= End) {
1501                 Stride = 4;
1502                 dumpBytes(Bytes.slice(Index, 4), outs());
1503                 outs() << "\t.word\t";
1504                 uint32_t Data = 0;
1505                 if (Obj->isLittleEndian()) {
1506                   const auto Word =
1507                       reinterpret_cast<const support::ulittle32_t *>(
1508                           Bytes.data() + Index);
1509                   Data = *Word;
1510                 } else {
1511                   const auto Word = reinterpret_cast<const support::ubig32_t *>(
1512                       Bytes.data() + Index);
1513                   Data = *Word;
1514                 }
1515                 outs() << "0x" << format("%08" PRIx32, Data);
1516               } else if (Index + 2 <= End) {
1517                 Stride = 2;
1518                 dumpBytes(Bytes.slice(Index, 2), outs());
1519                 outs() << "\t\t.short\t";
1520                 uint16_t Data = 0;
1521                 if (Obj->isLittleEndian()) {
1522                   const auto Short =
1523                       reinterpret_cast<const support::ulittle16_t *>(
1524                           Bytes.data() + Index);
1525                   Data = *Short;
1526                 } else {
1527                   const auto Short =
1528                       reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1529                                                                   Index);
1530                   Data = *Short;
1531                 }
1532                 outs() << "0x" << format("%04" PRIx16, Data);
1533               } else {
1534                 Stride = 1;
1535                 dumpBytes(Bytes.slice(Index, 1), outs());
1536                 outs() << "\t\t.byte\t";
1537                 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1538               }
1539               Index += Stride;
1540               outs() << "\n";
1541               auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1542                                           TextMappingSymsAddr.end(), Index);
1543               if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1544                 break;
1545             }
1546           }
1547         }
1548
1549         // If there is a data symbol inside an ELF text section and we are only
1550         // disassembling text (applicable all architectures),
1551         // we are in a situation where we must print the data and not
1552         // disassemble it.
1553         if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1554             !DisassembleAll && Section.isText()) {
1555           // print out data up to 8 bytes at a time in hex and ascii
1556           uint8_t AsciiData[9] = {'\0'};
1557           uint8_t Byte;
1558           int NumBytes = 0;
1559
1560           for (Index = Start; Index < End; Index += 1) {
1561             if (((SectionAddr + Index) < StartAddress) ||
1562                 ((SectionAddr + Index) > StopAddress))
1563               continue;
1564             if (NumBytes == 0) {
1565               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1566               outs() << "\t";
1567             }
1568             Byte = Bytes.slice(Index)[0];
1569             outs() << format(" %02x", Byte);
1570             AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1571
1572             uint8_t IndentOffset = 0;
1573             NumBytes++;
1574             if (Index == End - 1 || NumBytes > 8) {
1575               // Indent the space for less than 8 bytes data.
1576               // 2 spaces for byte and one for space between bytes
1577               IndentOffset = 3 * (8 - NumBytes);
1578               for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1579                 AsciiData[Excess] = '\0';
1580               NumBytes = 8;
1581             }
1582             if (NumBytes == 8) {
1583               AsciiData[8] = '\0';
1584               outs() << std::string(IndentOffset, ' ') << "         ";
1585               outs() << reinterpret_cast<char *>(AsciiData);
1586               outs() << '\n';
1587               NumBytes = 0;
1588             }
1589           }
1590         }
1591         if (Index >= End)
1592           break;
1593
1594         // Disassemble a real instruction or a data when disassemble all is
1595         // provided
1596         bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1597                                                    SectionAddr + Index, DebugOut,
1598                                                    CommentStream);
1599         if (Size == 0)
1600           Size = 1;
1601
1602         PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1603                       Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1604                       *STI, &SP);
1605         outs() << CommentStream.str();
1606         Comments.clear();
1607
1608         // Try to resolve the target of a call, tail call, etc. to a specific
1609         // symbol.
1610         if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1611                     MIA->isConditionalBranch(Inst))) {
1612           uint64_t Target;
1613           if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1614             // In a relocatable object, the target's section must reside in
1615             // the same section as the call instruction or it is accessed
1616             // through a relocation.
1617             //
1618             // In a non-relocatable object, the target may be in any section.
1619             //
1620             // N.B. We don't walk the relocations in the relocatable case yet.
1621             auto *TargetSectionSymbols = &Symbols;
1622             if (!Obj->isRelocatableObject()) {
1623               auto SectionAddress = std::upper_bound(
1624                   SectionAddresses.begin(), SectionAddresses.end(), Target,
1625                   [](uint64_t LHS,
1626                       const std::pair<uint64_t, SectionRef> &RHS) {
1627                     return LHS < RHS.first;
1628                   });
1629               if (SectionAddress != SectionAddresses.begin()) {
1630                 --SectionAddress;
1631                 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1632               } else {
1633                 TargetSectionSymbols = nullptr;
1634               }
1635             }
1636
1637             // Find the first symbol in the section whose offset is less than
1638             // or equal to the target.
1639             if (TargetSectionSymbols) {
1640               auto TargetSym = std::upper_bound(
1641                   TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1642                   Target, [](uint64_t LHS,
1643                              const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1644                     return LHS < std::get<0>(RHS);
1645                   });
1646               if (TargetSym != TargetSectionSymbols->begin()) {
1647                 --TargetSym;
1648                 uint64_t TargetAddress = std::get<0>(*TargetSym);
1649                 StringRef TargetName = std::get<1>(*TargetSym);
1650                 outs() << " <" << TargetName;
1651                 uint64_t Disp = Target - TargetAddress;
1652                 if (Disp)
1653                   outs() << "+0x" << utohexstr(Disp);
1654                 outs() << '>';
1655               }
1656             }
1657           }
1658         }
1659         outs() << "\n";
1660
1661         // Print relocation for instruction.
1662         while (rel_cur != rel_end) {
1663           bool hidden = getHidden(*rel_cur);
1664           uint64_t addr = rel_cur->getOffset();
1665           SmallString<16> name;
1666           SmallString<32> val;
1667
1668           // If this relocation is hidden, skip it.
1669           if (hidden || ((SectionAddr + addr) < StartAddress)) {
1670             ++rel_cur;
1671             continue;
1672           }
1673
1674           // Stop when rel_cur's address is past the current instruction.
1675           if (addr >= Index + Size) break;
1676           rel_cur->getTypeName(name);
1677           error(getRelocationValueString(*rel_cur, val));
1678           outs() << format(Fmt.data(), SectionAddr + addr) << name
1679                  << "\t" << val << "\n";
1680           ++rel_cur;
1681         }
1682       }
1683     }
1684   }
1685 }
1686
1687 void llvm::PrintRelocations(const ObjectFile *Obj) {
1688   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1689                                                  "%08" PRIx64;
1690   // Regular objdump doesn't print relocations in non-relocatable object
1691   // files.
1692   if (!Obj->isRelocatableObject())
1693     return;
1694
1695   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1696     if (Section.relocation_begin() == Section.relocation_end())
1697       continue;
1698     StringRef secname;
1699     error(Section.getName(secname));
1700     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1701     for (const RelocationRef &Reloc : Section.relocations()) {
1702       bool hidden = getHidden(Reloc);
1703       uint64_t address = Reloc.getOffset();
1704       SmallString<32> relocname;
1705       SmallString<32> valuestr;
1706       if (address < StartAddress || address > StopAddress || hidden)
1707         continue;
1708       Reloc.getTypeName(relocname);
1709       error(getRelocationValueString(Reloc, valuestr));
1710       outs() << format(Fmt.data(), address) << " " << relocname << " "
1711              << valuestr << "\n";
1712     }
1713     outs() << "\n";
1714   }
1715 }
1716
1717 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1718   outs() << "Sections:\n"
1719             "Idx Name          Size      Address          Type\n";
1720   unsigned i = 0;
1721   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1722     StringRef Name;
1723     error(Section.getName(Name));
1724     uint64_t Address = Section.getAddress();
1725     uint64_t Size = Section.getSize();
1726     bool Text = Section.isText();
1727     bool Data = Section.isData();
1728     bool BSS = Section.isBSS();
1729     std::string Type = (std::string(Text ? "TEXT " : "") +
1730                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1731     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1732                      Name.str().c_str(), Size, Address, Type.c_str());
1733     ++i;
1734   }
1735 }
1736
1737 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1738   std::error_code EC;
1739   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1740     StringRef Name;
1741     StringRef Contents;
1742     error(Section.getName(Name));
1743     uint64_t BaseAddr = Section.getAddress();
1744     uint64_t Size = Section.getSize();
1745     if (!Size)
1746       continue;
1747
1748     outs() << "Contents of section " << Name << ":\n";
1749     if (Section.isBSS()) {
1750       outs() << format("<skipping contents of bss section at [%04" PRIx64
1751                        ", %04" PRIx64 ")>\n",
1752                        BaseAddr, BaseAddr + Size);
1753       continue;
1754     }
1755
1756     error(Section.getContents(Contents));
1757
1758     // Dump out the content as hex and printable ascii characters.
1759     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1760       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1761       // Dump line of hex.
1762       for (std::size_t i = 0; i < 16; ++i) {
1763         if (i != 0 && i % 4 == 0)
1764           outs() << ' ';
1765         if (addr + i < end)
1766           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1767                  << hexdigit(Contents[addr + i] & 0xF, true);
1768         else
1769           outs() << "  ";
1770       }
1771       // Print ascii.
1772       outs() << "  ";
1773       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1774         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1775           outs() << Contents[addr + i];
1776         else
1777           outs() << ".";
1778       }
1779       outs() << "\n";
1780     }
1781   }
1782 }
1783
1784 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1785                             StringRef ArchitectureName) {
1786   outs() << "SYMBOL TABLE:\n";
1787
1788   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1789     printCOFFSymbolTable(coff);
1790     return;
1791   }
1792   for (const SymbolRef &Symbol : o->symbols()) {
1793     Expected<uint64_t> AddressOrError = Symbol.getAddress();
1794     if (!AddressOrError)
1795       report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1796                    ArchitectureName);
1797     uint64_t Address = *AddressOrError;
1798     if ((Address < StartAddress) || (Address > StopAddress))
1799       continue;
1800     Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1801     if (!TypeOrError)
1802       report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1803                    ArchitectureName);
1804     SymbolRef::Type Type = *TypeOrError;
1805     uint32_t Flags = Symbol.getFlags();
1806     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1807     if (!SectionOrErr)
1808       report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1809                    ArchitectureName);
1810     section_iterator Section = *SectionOrErr;
1811     StringRef Name;
1812     if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1813       Section->getName(Name);
1814     } else {
1815       Expected<StringRef> NameOrErr = Symbol.getName();
1816       if (!NameOrErr)
1817         report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1818                      ArchitectureName);
1819       Name = *NameOrErr;
1820     }
1821
1822     bool Global = Flags & SymbolRef::SF_Global;
1823     bool Weak = Flags & SymbolRef::SF_Weak;
1824     bool Absolute = Flags & SymbolRef::SF_Absolute;
1825     bool Common = Flags & SymbolRef::SF_Common;
1826     bool Hidden = Flags & SymbolRef::SF_Hidden;
1827
1828     char GlobLoc = ' ';
1829     if (Type != SymbolRef::ST_Unknown)
1830       GlobLoc = Global ? 'g' : 'l';
1831     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1832                  ? 'd' : ' ';
1833     char FileFunc = ' ';
1834     if (Type == SymbolRef::ST_File)
1835       FileFunc = 'f';
1836     else if (Type == SymbolRef::ST_Function)
1837       FileFunc = 'F';
1838
1839     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1840                                                    "%08" PRIx64;
1841
1842     outs() << format(Fmt, Address) << " "
1843            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1844            << (Weak ? 'w' : ' ') // Weak?
1845            << ' ' // Constructor. Not supported yet.
1846            << ' ' // Warning. Not supported yet.
1847            << ' ' // Indirect reference to another symbol.
1848            << Debug // Debugging (d) or dynamic (D) symbol.
1849            << FileFunc // Name of function (F), file (f) or object (O).
1850            << ' ';
1851     if (Absolute) {
1852       outs() << "*ABS*";
1853     } else if (Common) {
1854       outs() << "*COM*";
1855     } else if (Section == o->section_end()) {
1856       outs() << "*UND*";
1857     } else {
1858       if (const MachOObjectFile *MachO =
1859           dyn_cast<const MachOObjectFile>(o)) {
1860         DataRefImpl DR = Section->getRawDataRefImpl();
1861         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1862         outs() << SegmentName << ",";
1863       }
1864       StringRef SectionName;
1865       error(Section->getName(SectionName));
1866       outs() << SectionName;
1867     }
1868
1869     outs() << '\t';
1870     if (Common || isa<ELFObjectFileBase>(o)) {
1871       uint64_t Val =
1872           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1873       outs() << format("\t %08" PRIx64 " ", Val);
1874     }
1875
1876     if (Hidden) {
1877       outs() << ".hidden ";
1878     }
1879     outs() << Name
1880            << '\n';
1881   }
1882 }
1883
1884 static void PrintUnwindInfo(const ObjectFile *o) {
1885   outs() << "Unwind info:\n\n";
1886
1887   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1888     printCOFFUnwindInfo(coff);
1889   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1890     printMachOUnwindInfo(MachO);
1891   else {
1892     // TODO: Extract DWARF dump tool to objdump.
1893     errs() << "This operation is only currently supported "
1894               "for COFF and MachO object files.\n";
1895     return;
1896   }
1897 }
1898
1899 void llvm::printExportsTrie(const ObjectFile *o) {
1900   outs() << "Exports trie:\n";
1901   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1902     printMachOExportsTrie(MachO);
1903   else {
1904     errs() << "This operation is only currently supported "
1905               "for Mach-O executable files.\n";
1906     return;
1907   }
1908 }
1909
1910 void llvm::printRebaseTable(ObjectFile *o) {
1911   outs() << "Rebase table:\n";
1912   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1913     printMachORebaseTable(MachO);
1914   else {
1915     errs() << "This operation is only currently supported "
1916               "for Mach-O executable files.\n";
1917     return;
1918   }
1919 }
1920
1921 void llvm::printBindTable(ObjectFile *o) {
1922   outs() << "Bind table:\n";
1923   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1924     printMachOBindTable(MachO);
1925   else {
1926     errs() << "This operation is only currently supported "
1927               "for Mach-O executable files.\n";
1928     return;
1929   }
1930 }
1931
1932 void llvm::printLazyBindTable(ObjectFile *o) {
1933   outs() << "Lazy bind table:\n";
1934   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1935     printMachOLazyBindTable(MachO);
1936   else {
1937     errs() << "This operation is only currently supported "
1938               "for Mach-O executable files.\n";
1939     return;
1940   }
1941 }
1942
1943 void llvm::printWeakBindTable(ObjectFile *o) {
1944   outs() << "Weak bind table:\n";
1945   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1946     printMachOWeakBindTable(MachO);
1947   else {
1948     errs() << "This operation is only currently supported "
1949               "for Mach-O executable files.\n";
1950     return;
1951   }
1952 }
1953
1954 /// Dump the raw contents of the __clangast section so the output can be piped
1955 /// into llvm-bcanalyzer.
1956 void llvm::printRawClangAST(const ObjectFile *Obj) {
1957   if (outs().is_displayed()) {
1958     errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1959               "the clang ast section.\n"
1960               "Please redirect the output to a file or another program such as "
1961               "llvm-bcanalyzer.\n";
1962     return;
1963   }
1964
1965   StringRef ClangASTSectionName("__clangast");
1966   if (isa<COFFObjectFile>(Obj)) {
1967     ClangASTSectionName = "clangast";
1968   }
1969
1970   Optional<object::SectionRef> ClangASTSection;
1971   for (auto Sec : ToolSectionFilter(*Obj)) {
1972     StringRef Name;
1973     Sec.getName(Name);
1974     if (Name == ClangASTSectionName) {
1975       ClangASTSection = Sec;
1976       break;
1977     }
1978   }
1979   if (!ClangASTSection)
1980     return;
1981
1982   StringRef ClangASTContents;
1983   error(ClangASTSection.getValue().getContents(ClangASTContents));
1984   outs().write(ClangASTContents.data(), ClangASTContents.size());
1985 }
1986
1987 static void printFaultMaps(const ObjectFile *Obj) {
1988   const char *FaultMapSectionName = nullptr;
1989
1990   if (isa<ELFObjectFileBase>(Obj)) {
1991     FaultMapSectionName = ".llvm_faultmaps";
1992   } else if (isa<MachOObjectFile>(Obj)) {
1993     FaultMapSectionName = "__llvm_faultmaps";
1994   } else {
1995     errs() << "This operation is only currently supported "
1996               "for ELF and Mach-O executable files.\n";
1997     return;
1998   }
1999
2000   Optional<object::SectionRef> FaultMapSection;
2001
2002   for (auto Sec : ToolSectionFilter(*Obj)) {
2003     StringRef Name;
2004     Sec.getName(Name);
2005     if (Name == FaultMapSectionName) {
2006       FaultMapSection = Sec;
2007       break;
2008     }
2009   }
2010
2011   outs() << "FaultMap table:\n";
2012
2013   if (!FaultMapSection.hasValue()) {
2014     outs() << "<not found>\n";
2015     return;
2016   }
2017
2018   StringRef FaultMapContents;
2019   error(FaultMapSection.getValue().getContents(FaultMapContents));
2020
2021   FaultMapParser FMP(FaultMapContents.bytes_begin(),
2022                      FaultMapContents.bytes_end());
2023
2024   outs() << FMP;
2025 }
2026
2027 static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
2028   if (o->isELF())
2029     return printELFFileHeader(o);
2030   if (o->isCOFF())
2031     return printCOFFFileHeader(o);
2032   if (o->isWasm())
2033     return printWasmFileHeader(o);
2034   if (o->isMachO()) {
2035     printMachOFileHeader(o);
2036     if (!onlyFirst)
2037       printMachOLoadCommands(o);
2038     return;
2039   }
2040   report_error(o->getFileName(), "Invalid/Unsupported object file format");
2041 }
2042
2043 static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
2044   StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
2045   // Avoid other output when using a raw option.
2046   if (!RawClangAST) {
2047     outs() << '\n';
2048     if (a)
2049       outs() << a->getFileName() << "(" << o->getFileName() << ")";
2050     else
2051       outs() << o->getFileName();
2052     outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
2053   }
2054
2055   if (Disassemble)
2056     DisassembleObject(o, Relocations);
2057   if (Relocations && !Disassemble)
2058     PrintRelocations(o);
2059   if (SectionHeaders)
2060     PrintSectionHeaders(o);
2061   if (SectionContents)
2062     PrintSectionContents(o);
2063   if (SymbolTable)
2064     PrintSymbolTable(o, ArchiveName);
2065   if (UnwindInfo)
2066     PrintUnwindInfo(o);
2067   if (PrivateHeaders || FirstPrivateHeader)
2068     printPrivateFileHeaders(o, FirstPrivateHeader);
2069   if (ExportsTrie)
2070     printExportsTrie(o);
2071   if (Rebase)
2072     printRebaseTable(o);
2073   if (Bind)
2074     printBindTable(o);
2075   if (LazyBind)
2076     printLazyBindTable(o);
2077   if (WeakBind)
2078     printWeakBindTable(o);
2079   if (RawClangAST)
2080     printRawClangAST(o);
2081   if (PrintFaultMaps)
2082     printFaultMaps(o);
2083   if (DwarfDumpType != DIDT_Null) {
2084     std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
2085     // Dump the complete DWARF structure.
2086     DIDumpOptions DumpOpts;
2087     DumpOpts.DumpType = DwarfDumpType;
2088     DumpOpts.DumpEH = true;
2089     DICtx->dump(outs(), DumpOpts);
2090   }
2091 }
2092
2093 static void DumpObject(const COFFImportFile *I, const Archive *A) {
2094   StringRef ArchiveName = A ? A->getFileName() : "";
2095
2096   // Avoid other output when using a raw option.
2097   if (!RawClangAST)
2098     outs() << '\n'
2099            << ArchiveName << "(" << I->getFileName() << ")"
2100            << ":\tfile format COFF-import-file"
2101            << "\n\n";
2102
2103   if (SymbolTable)
2104     printCOFFSymbolTable(I);
2105 }
2106
2107 /// @brief Dump each object file in \a a;
2108 static void DumpArchive(const Archive *a) {
2109   Error Err = Error::success();
2110   for (auto &C : a->children(Err)) {
2111     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2112     if (!ChildOrErr) {
2113       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2114         report_error(a->getFileName(), C, std::move(E));
2115       continue;
2116     }
2117     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2118       DumpObject(o, a);
2119     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2120       DumpObject(I, a);
2121     else
2122       report_error(a->getFileName(), object_error::invalid_file_type);
2123   }
2124   if (Err)
2125     report_error(a->getFileName(), std::move(Err));
2126 }
2127
2128 /// @brief Open file and figure out how to dump it.
2129 static void DumpInput(StringRef file) {
2130
2131   // If we are using the Mach-O specific object file parser, then let it parse
2132   // the file and process the command line options.  So the -arch flags can
2133   // be used to select specific slices, etc.
2134   if (MachOOpt) {
2135     ParseInputMachO(file);
2136     return;
2137   }
2138
2139   // Attempt to open the binary.
2140   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2141   if (!BinaryOrErr)
2142     report_error(file, BinaryOrErr.takeError());
2143   Binary &Binary = *BinaryOrErr.get().getBinary();
2144
2145   if (Archive *a = dyn_cast<Archive>(&Binary))
2146     DumpArchive(a);
2147   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
2148     DumpObject(o);
2149   else
2150     report_error(file, object_error::invalid_file_type);
2151 }
2152
2153 int main(int argc, char **argv) {
2154   // Print a stack trace if we signal out.
2155   sys::PrintStackTraceOnErrorSignal(argv[0]);
2156   PrettyStackTraceProgram X(argc, argv);
2157   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
2158
2159   // Initialize targets and assembly printers/parsers.
2160   llvm::InitializeAllTargetInfos();
2161   llvm::InitializeAllTargetMCs();
2162   llvm::InitializeAllDisassemblers();
2163
2164   // Register the target printer for --version.
2165   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2166
2167   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2168   TripleName = Triple::normalize(TripleName);
2169
2170   ToolName = argv[0];
2171
2172   // Defaults to a.out if no filenames specified.
2173   if (InputFilenames.size() == 0)
2174     InputFilenames.push_back("a.out");
2175
2176   if (DisassembleAll || PrintSource || PrintLines)
2177     Disassemble = true;
2178   if (!Disassemble
2179       && !Relocations
2180       && !SectionHeaders
2181       && !SectionContents
2182       && !SymbolTable
2183       && !UnwindInfo
2184       && !PrivateHeaders
2185       && !FirstPrivateHeader
2186       && !ExportsTrie
2187       && !Rebase
2188       && !Bind
2189       && !LazyBind
2190       && !WeakBind
2191       && !RawClangAST
2192       && !(UniversalHeaders && MachOOpt)
2193       && !(ArchiveHeaders && MachOOpt)
2194       && !(IndirectSymbols && MachOOpt)
2195       && !(DataInCode && MachOOpt)
2196       && !(LinkOptHints && MachOOpt)
2197       && !(InfoPlist && MachOOpt)
2198       && !(DylibsUsed && MachOOpt)
2199       && !(DylibId && MachOOpt)
2200       && !(ObjcMetaData && MachOOpt)
2201       && !(FilterSections.size() != 0 && MachOOpt)
2202       && !PrintFaultMaps
2203       && DwarfDumpType == DIDT_Null) {
2204     cl::PrintHelpMessage();
2205     return 2;
2206   }
2207
2208   std::for_each(InputFilenames.begin(), InputFilenames.end(),
2209                 DumpInput);
2210
2211   return EXIT_SUCCESS;
2212 }