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