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