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