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