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