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