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