xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision e799405e5368033d602f531fcebb81229471cec0)
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.
1206   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1207   for (SectionRef Sec : Obj->sections())
1208     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1209   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1210 
1211   // Linked executables (.exe and .dll files) typically don't include a real
1212   // symbol table but they might contain an export table.
1213   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1214     for (const auto &ExportEntry : COFFObj->export_directories()) {
1215       StringRef Name;
1216       if (std::error_code EC = ExportEntry.getSymbolName(Name))
1217         reportError(errorCodeToError(EC), Obj->getFileName());
1218       if (Name.empty())
1219         continue;
1220 
1221       uint32_t RVA;
1222       if (std::error_code EC = ExportEntry.getExportRVA(RVA))
1223         reportError(errorCodeToError(EC), Obj->getFileName());
1224 
1225       uint64_t VA = COFFObj->getImageBase() + RVA;
1226       auto Sec = partition_point(
1227           SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) {
1228             return O.first <= VA;
1229           });
1230       if (Sec != SectionAddresses.begin()) {
1231         --Sec;
1232         AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1233       } else
1234         AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1235     }
1236   }
1237 
1238   // Sort all the symbols, this allows us to use a simple binary search to find
1239   // a symbol near an address.
1240   StringSet<> FoundDisasmSymbolSet;
1241   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1242     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1243   array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1244 
1245   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1246     if (FilterSections.empty() && !DisassembleAll &&
1247         (!Section.isText() || Section.isVirtual()))
1248       continue;
1249 
1250     uint64_t SectionAddr = Section.getAddress();
1251     uint64_t SectSize = Section.getSize();
1252     if (!SectSize)
1253       continue;
1254 
1255     // Get the list of all the symbols in this section.
1256     SectionSymbolsTy &Symbols = AllSymbols[Section];
1257     std::vector<MappingSymbolPair> MappingSymbols;
1258     if (hasMappingSymbols(Obj)) {
1259       for (const auto &Symb : Symbols) {
1260         uint64_t Address = Symb.Addr;
1261         StringRef Name = Symb.Name;
1262         if (Name.startswith("$d"))
1263           MappingSymbols.emplace_back(Address - SectionAddr, 'd');
1264         if (Name.startswith("$x"))
1265           MappingSymbols.emplace_back(Address - SectionAddr, 'x');
1266         if (Name.startswith("$a"))
1267           MappingSymbols.emplace_back(Address - SectionAddr, 'a');
1268         if (Name.startswith("$t"))
1269           MappingSymbols.emplace_back(Address - SectionAddr, 't');
1270       }
1271     }
1272 
1273     llvm::sort(MappingSymbols);
1274 
1275     if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1276       // AMDGPU disassembler uses symbolizer for printing labels
1277       std::unique_ptr<MCRelocationInfo> RelInfo(
1278         TheTarget->createMCRelocationInfo(TripleName, Ctx));
1279       if (RelInfo) {
1280         std::unique_ptr<MCSymbolizer> Symbolizer(
1281           TheTarget->createMCSymbolizer(
1282             TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1283         DisAsm->setSymbolizer(std::move(Symbolizer));
1284       }
1285     }
1286 
1287     StringRef SegmentName = "";
1288     if (MachO) {
1289       DataRefImpl DR = Section.getRawDataRefImpl();
1290       SegmentName = MachO->getSectionFinalSegmentName(DR);
1291     }
1292 
1293     StringRef SectionName = unwrapOrError(Section.getName(), Obj->getFileName());
1294     // If the section has no symbol at the start, just insert a dummy one.
1295     if (Symbols.empty() || Symbols[0].Addr != 0) {
1296       Symbols.insert(
1297           Symbols.begin(),
1298            SymbolInfoTy(SectionAddr, SectionName,
1299                           Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1300     }
1301 
1302     SmallString<40> Comments;
1303     raw_svector_ostream CommentStream(Comments);
1304 
1305     ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
1306         unwrapOrError(Section.getContents(), Obj->getFileName()));
1307 
1308     uint64_t VMAAdjustment = 0;
1309     if (shouldAdjustVA(Section))
1310       VMAAdjustment = AdjustVMA;
1311 
1312     uint64_t Size;
1313     uint64_t Index;
1314     bool PrintedSection = false;
1315     std::vector<RelocationRef> Rels = RelocMap[Section];
1316     std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1317     std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1318     // Disassemble symbol by symbol.
1319     for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1320       std::string SymbolName = Symbols[SI].Name.str();
1321       if (Demangle)
1322         SymbolName = demangle(SymbolName);
1323 
1324       // Skip if --disassemble-symbols is not empty and the symbol is not in
1325       // the list.
1326       if (!DisasmSymbolSet.empty() && !DisasmSymbolSet.count(SymbolName))
1327         continue;
1328 
1329       uint64_t Start = Symbols[SI].Addr;
1330       if (Start < SectionAddr || StopAddress <= Start)
1331         continue;
1332       else
1333         FoundDisasmSymbolSet.insert(SymbolName);
1334 
1335       // The end is the section end, the beginning of the next symbol, or
1336       // --stop-address.
1337       uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
1338       if (SI + 1 < SE)
1339         End = std::min(End, Symbols[SI + 1].Addr);
1340       if (Start >= End || End <= StartAddress)
1341         continue;
1342       Start -= SectionAddr;
1343       End -= SectionAddr;
1344 
1345       if (!PrintedSection) {
1346         PrintedSection = true;
1347         outs() << "\nDisassembly of section ";
1348         if (!SegmentName.empty())
1349           outs() << SegmentName << ",";
1350         outs() << SectionName << ":\n";
1351       }
1352 
1353       if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1354         if (Symbols[SI].Type == ELF::STT_AMDGPU_HSA_KERNEL) {
1355           // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1356           Start += 256;
1357         }
1358         if (SI == SE - 1 ||
1359             Symbols[SI + 1].Type == ELF::STT_AMDGPU_HSA_KERNEL) {
1360           // cut trailing zeroes at the end of kernel
1361           // cut up to 256 bytes
1362           const uint64_t EndAlign = 256;
1363           const auto Limit = End - (std::min)(EndAlign, End - Start);
1364           while (End > Limit &&
1365             *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1366             End -= 4;
1367         }
1368       }
1369 
1370       outs() << '\n';
1371       if (!NoLeadingAddr)
1372         outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ",
1373                          SectionAddr + Start + VMAAdjustment);
1374 
1375       outs() << '<' << SymbolName << ">:\n";
1376 
1377       // Don't print raw contents of a virtual section. A virtual section
1378       // doesn't have any contents in the file.
1379       if (Section.isVirtual()) {
1380         outs() << "...\n";
1381         continue;
1382       }
1383 
1384       // Some targets (like WebAssembly) have a special prelude at the start
1385       // of each symbol.
1386       DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1387                             SectionAddr + Start, CommentStream);
1388       Start += Size;
1389 
1390       Index = Start;
1391       if (SectionAddr < StartAddress)
1392         Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
1393 
1394       // If there is a data/common symbol inside an ELF text section and we are
1395       // only disassembling text (applicable all architectures), we are in a
1396       // situation where we must print the data and not disassemble it.
1397       if (Obj->isELF() && !DisassembleAll && Section.isText()) {
1398         uint8_t SymTy = Symbols[SI].Type;
1399         if (SymTy == ELF::STT_OBJECT || SymTy == ELF::STT_COMMON) {
1400           dumpELFData(SectionAddr, Index, End, Bytes);
1401           Index = End;
1402         }
1403       }
1404 
1405       bool CheckARMELFData = hasMappingSymbols(Obj) &&
1406                              Symbols[SI].Type != ELF::STT_OBJECT &&
1407                              !DisassembleAll;
1408       while (Index < End) {
1409         // ARM and AArch64 ELF binaries can interleave data and text in the
1410         // same section. We rely on the markers introduced to understand what
1411         // we need to dump. If the data marker is within a function, it is
1412         // denoted as a word/short etc.
1413         if (CheckARMELFData &&
1414             getMappingSymbolKind(MappingSymbols, Index) == 'd') {
1415           Index = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
1416                                  MappingSymbols);
1417           continue;
1418         }
1419 
1420         // When -z or --disassemble-zeroes are given we always dissasemble
1421         // them. Otherwise we might want to skip zero bytes we see.
1422         if (!DisassembleZeroes) {
1423           uint64_t MaxOffset = End - Index;
1424           // For -reloc: print zero blocks patched by relocations, so that
1425           // relocations can be shown in the dump.
1426           if (RelCur != RelEnd)
1427             MaxOffset = RelCur->getOffset() - Index;
1428 
1429           if (size_t N =
1430                   countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1431             outs() << "\t\t..." << '\n';
1432             Index += N;
1433             continue;
1434           }
1435         }
1436 
1437         if (SecondarySTI) {
1438           if (getMappingSymbolKind(MappingSymbols, Index) == 'a') {
1439             STI = PrimaryIsThumb ? SecondarySTI : PrimarySTI;
1440             DisAsm = PrimaryIsThumb ? SecondaryDisAsm : PrimaryDisAsm;
1441           } else if (getMappingSymbolKind(MappingSymbols, Index) == 't') {
1442             STI = PrimaryIsThumb ? PrimarySTI : SecondarySTI;
1443             DisAsm = PrimaryIsThumb ? PrimaryDisAsm : SecondaryDisAsm;
1444           }
1445         }
1446 
1447         // Disassemble a real instruction or a data when disassemble all is
1448         // provided
1449         MCInst Inst;
1450         bool Disassembled = DisAsm->getInstruction(
1451             Inst, Size, Bytes.slice(Index), SectionAddr + Index, CommentStream);
1452         if (Size == 0)
1453           Size = 1;
1454 
1455         PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1456                       Bytes.slice(Index, Size),
1457                       {SectionAddr + Index + VMAAdjustment, Section.getIndex()},
1458                       outs(), "", *STI, &SP, Obj->getFileName(), &Rels);
1459         outs() << CommentStream.str();
1460         Comments.clear();
1461 
1462         // If disassembly has failed, continue with the next instruction, to
1463         // avoid analysing invalid/incomplete instruction information.
1464         if (!Disassembled) {
1465           outs() << "\n";
1466           Index += Size;
1467           continue;
1468         }
1469 
1470         // Try to resolve the target of a call, tail call, etc. to a specific
1471         // symbol.
1472         if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1473                     MIA->isConditionalBranch(Inst))) {
1474           uint64_t Target;
1475           if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1476             // In a relocatable object, the target's section must reside in
1477             // the same section as the call instruction or it is accessed
1478             // through a relocation.
1479             //
1480             // In a non-relocatable object, the target may be in any section.
1481             //
1482             // N.B. We don't walk the relocations in the relocatable case yet.
1483             auto *TargetSectionSymbols = &Symbols;
1484             if (!Obj->isRelocatableObject()) {
1485               auto It = partition_point(
1486                   SectionAddresses,
1487                   [=](const std::pair<uint64_t, SectionRef> &O) {
1488                     return O.first <= Target;
1489                   });
1490               if (It != SectionAddresses.begin()) {
1491                 --It;
1492                 TargetSectionSymbols = &AllSymbols[It->second];
1493               } else {
1494                 TargetSectionSymbols = &AbsoluteSymbols;
1495               }
1496             }
1497 
1498             // Find the last symbol in the section whose offset is less than
1499             // or equal to the target. If there isn't a section that contains
1500             // the target, find the nearest preceding absolute symbol.
1501             auto TargetSym = partition_point(
1502                 *TargetSectionSymbols,
1503                 [=](const SymbolInfoTy &O) {
1504                   return O.Addr <= Target;
1505                 });
1506             if (TargetSym == TargetSectionSymbols->begin()) {
1507               TargetSectionSymbols = &AbsoluteSymbols;
1508               TargetSym = partition_point(
1509                   AbsoluteSymbols,
1510                   [=](const SymbolInfoTy &O) {
1511                     return O.Addr <= Target;
1512                   });
1513             }
1514             if (TargetSym != TargetSectionSymbols->begin()) {
1515               --TargetSym;
1516               uint64_t TargetAddress = TargetSym->Addr;
1517               StringRef TargetName = TargetSym->Name;
1518               outs() << " <" << TargetName;
1519               uint64_t Disp = Target - TargetAddress;
1520               if (Disp)
1521                 outs() << "+0x" << Twine::utohexstr(Disp);
1522               outs() << '>';
1523             }
1524           }
1525         }
1526         outs() << "\n";
1527 
1528         // Hexagon does this in pretty printer
1529         if (Obj->getArch() != Triple::hexagon) {
1530           // Print relocation for instruction.
1531           while (RelCur != RelEnd) {
1532             uint64_t Offset = RelCur->getOffset();
1533             // If this relocation is hidden, skip it.
1534             if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
1535               ++RelCur;
1536               continue;
1537             }
1538 
1539             // Stop when RelCur's offset is past the current instruction.
1540             if (Offset >= Index + Size)
1541               break;
1542 
1543             // When --adjust-vma is used, update the address printed.
1544             if (RelCur->getSymbol() != Obj->symbol_end()) {
1545               Expected<section_iterator> SymSI =
1546                   RelCur->getSymbol()->getSection();
1547               if (SymSI && *SymSI != Obj->section_end() &&
1548                   shouldAdjustVA(**SymSI))
1549                 Offset += AdjustVMA;
1550             }
1551 
1552             printRelocation(Obj->getFileName(), *RelCur, SectionAddr + Offset,
1553                             Is64Bits);
1554             ++RelCur;
1555           }
1556         }
1557 
1558         Index += Size;
1559       }
1560     }
1561   }
1562   StringSet<> MissingDisasmSymbolSet =
1563       set_difference(DisasmSymbolSet, FoundDisasmSymbolSet);
1564   for (StringRef Sym : MissingDisasmSymbolSet.keys())
1565     reportWarning("failed to disassemble missing symbol " + Sym, FileName);
1566 }
1567 
1568 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1569   const Target *TheTarget = getTarget(Obj);
1570 
1571   // Package up features to be passed to target/subtarget
1572   SubtargetFeatures Features = Obj->getFeatures();
1573   if (!MAttrs.empty())
1574     for (unsigned I = 0; I != MAttrs.size(); ++I)
1575       Features.AddFeature(MAttrs[I]);
1576 
1577   std::unique_ptr<const MCRegisterInfo> MRI(
1578       TheTarget->createMCRegInfo(TripleName));
1579   if (!MRI)
1580     reportError(Obj->getFileName(),
1581                 "no register info for target " + TripleName);
1582 
1583   // Set up disassembler.
1584   MCTargetOptions MCOptions;
1585   std::unique_ptr<const MCAsmInfo> AsmInfo(
1586       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
1587   if (!AsmInfo)
1588     reportError(Obj->getFileName(),
1589                 "no assembly info for target " + TripleName);
1590   std::unique_ptr<const MCSubtargetInfo> STI(
1591       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1592   if (!STI)
1593     reportError(Obj->getFileName(),
1594                 "no subtarget info for target " + TripleName);
1595   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1596   if (!MII)
1597     reportError(Obj->getFileName(),
1598                 "no instruction info for target " + TripleName);
1599   MCObjectFileInfo MOFI;
1600   MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1601   // FIXME: for now initialize MCObjectFileInfo with default values
1602   MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1603 
1604   std::unique_ptr<MCDisassembler> DisAsm(
1605       TheTarget->createMCDisassembler(*STI, Ctx));
1606   if (!DisAsm)
1607     reportError(Obj->getFileName(), "no disassembler for target " + TripleName);
1608 
1609   // If we have an ARM object file, we need a second disassembler, because
1610   // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode.
1611   // We use mapping symbols to switch between the two assemblers, where
1612   // appropriate.
1613   std::unique_ptr<MCDisassembler> SecondaryDisAsm;
1614   std::unique_ptr<const MCSubtargetInfo> SecondarySTI;
1615   if (isArmElf(Obj) && !STI->checkFeatures("+mclass")) {
1616     if (STI->checkFeatures("+thumb-mode"))
1617       Features.AddFeature("-thumb-mode");
1618     else
1619       Features.AddFeature("+thumb-mode");
1620     SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU,
1621                                                         Features.getString()));
1622     SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx));
1623   }
1624 
1625   std::unique_ptr<const MCInstrAnalysis> MIA(
1626       TheTarget->createMCInstrAnalysis(MII.get()));
1627 
1628   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1629   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1630       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1631   if (!IP)
1632     reportError(Obj->getFileName(),
1633                 "no instruction printer for target " + TripleName);
1634   IP->setPrintImmHex(PrintImmHex);
1635 
1636   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1637   SourcePrinter SP(Obj, TheTarget->getName());
1638 
1639   for (StringRef Opt : DisassemblerOptions)
1640     if (!IP->applyTargetSpecificCLOption(Opt))
1641       reportError(Obj->getFileName(),
1642                   "Unrecognized disassembler option: " + Opt);
1643 
1644   disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(),
1645                     MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP,
1646                     SP, InlineRelocs);
1647 }
1648 
1649 void printRelocations(const ObjectFile *Obj) {
1650   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1651                                                  "%08" PRIx64;
1652   // Regular objdump doesn't print relocations in non-relocatable object
1653   // files.
1654   if (!Obj->isRelocatableObject())
1655     return;
1656 
1657   // Build a mapping from relocation target to a vector of relocation
1658   // sections. Usually, there is an only one relocation section for
1659   // each relocated section.
1660   MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
1661   uint64_t Ndx;
1662   for (const SectionRef &Section : ToolSectionFilter(*Obj, &Ndx)) {
1663     if (Section.relocation_begin() == Section.relocation_end())
1664       continue;
1665     Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
1666     if (!SecOrErr)
1667       reportError(Obj->getFileName(),
1668                   "section (" + Twine(Ndx) +
1669                       "): unable to get a relocation target: " +
1670                       toString(SecOrErr.takeError()));
1671     SecToRelSec[**SecOrErr].push_back(Section);
1672   }
1673 
1674   for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
1675     StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName());
1676     outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
1677     uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8);
1678     uint32_t TypePadding = 24;
1679     outs() << left_justify("OFFSET", OffsetPadding) << " "
1680            << left_justify("TYPE", TypePadding) << " "
1681            << "VALUE\n";
1682 
1683     for (SectionRef Section : P.second) {
1684       for (const RelocationRef &Reloc : Section.relocations()) {
1685         uint64_t Address = Reloc.getOffset();
1686         SmallString<32> RelocName;
1687         SmallString<32> ValueStr;
1688         if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1689           continue;
1690         Reloc.getTypeName(RelocName);
1691         if (Error E = getRelocationValueString(Reloc, ValueStr))
1692           reportError(std::move(E), Obj->getFileName());
1693 
1694         outs() << format(Fmt.data(), Address) << " "
1695                << left_justify(RelocName, TypePadding) << " " << ValueStr
1696                << "\n";
1697       }
1698     }
1699     outs() << "\n";
1700   }
1701 }
1702 
1703 void printDynamicRelocations(const ObjectFile *Obj) {
1704   // For the moment, this option is for ELF only
1705   if (!Obj->isELF())
1706     return;
1707 
1708   const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1709   if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1710     reportError(Obj->getFileName(), "not a dynamic object");
1711     return;
1712   }
1713 
1714   std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1715   if (DynRelSec.empty())
1716     return;
1717 
1718   outs() << "DYNAMIC RELOCATION RECORDS\n";
1719   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1720   for (const SectionRef &Section : DynRelSec)
1721     for (const RelocationRef &Reloc : Section.relocations()) {
1722       uint64_t Address = Reloc.getOffset();
1723       SmallString<32> RelocName;
1724       SmallString<32> ValueStr;
1725       Reloc.getTypeName(RelocName);
1726       if (Error E = getRelocationValueString(Reloc, ValueStr))
1727         reportError(std::move(E), Obj->getFileName());
1728       outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1729              << ValueStr << "\n";
1730     }
1731 }
1732 
1733 // Returns true if we need to show LMA column when dumping section headers. We
1734 // show it only when the platform is ELF and either we have at least one section
1735 // whose VMA and LMA are different and/or when --show-lma flag is used.
1736 static bool shouldDisplayLMA(const ObjectFile *Obj) {
1737   if (!Obj->isELF())
1738     return false;
1739   for (const SectionRef &S : ToolSectionFilter(*Obj))
1740     if (S.getAddress() != getELFSectionLMA(S))
1741       return true;
1742   return ShowLMA;
1743 }
1744 
1745 static size_t getMaxSectionNameWidth(const ObjectFile *Obj) {
1746   // Default column width for names is 13 even if no names are that long.
1747   size_t MaxWidth = 13;
1748   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1749     StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1750     MaxWidth = std::max(MaxWidth, Name.size());
1751   }
1752   return MaxWidth;
1753 }
1754 
1755 void printSectionHeaders(const ObjectFile *Obj) {
1756   size_t NameWidth = getMaxSectionNameWidth(Obj);
1757   size_t AddressWidth = 2 * Obj->getBytesInAddress();
1758   bool HasLMAColumn = shouldDisplayLMA(Obj);
1759   if (HasLMAColumn)
1760     outs() << "Sections:\n"
1761               "Idx "
1762            << left_justify("Name", NameWidth) << " Size     "
1763            << left_justify("VMA", AddressWidth) << " "
1764            << left_justify("LMA", AddressWidth) << " Type\n";
1765   else
1766     outs() << "Sections:\n"
1767               "Idx "
1768            << left_justify("Name", NameWidth) << " Size     "
1769            << left_justify("VMA", AddressWidth) << " Type\n";
1770 
1771   uint64_t Idx;
1772   for (const SectionRef &Section : ToolSectionFilter(*Obj, &Idx)) {
1773     StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1774     uint64_t VMA = Section.getAddress();
1775     if (shouldAdjustVA(Section))
1776       VMA += AdjustVMA;
1777 
1778     uint64_t Size = Section.getSize();
1779 
1780     std::string Type = Section.isText() ? "TEXT" : "";
1781     if (Section.isData())
1782       Type += Type.empty() ? "DATA" : " DATA";
1783     if (Section.isBSS())
1784       Type += Type.empty() ? "BSS" : " BSS";
1785 
1786     if (HasLMAColumn)
1787       outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
1788                        Name.str().c_str(), Size)
1789              << format_hex_no_prefix(VMA, AddressWidth) << " "
1790              << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth)
1791              << " " << Type << "\n";
1792     else
1793       outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth,
1794                        Name.str().c_str(), Size)
1795              << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n";
1796   }
1797   outs() << "\n";
1798 }
1799 
1800 void printSectionContents(const ObjectFile *Obj) {
1801   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1802     StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName());
1803     uint64_t BaseAddr = Section.getAddress();
1804     uint64_t Size = Section.getSize();
1805     if (!Size)
1806       continue;
1807 
1808     outs() << "Contents of section " << Name << ":\n";
1809     if (Section.isBSS()) {
1810       outs() << format("<skipping contents of bss section at [%04" PRIx64
1811                        ", %04" PRIx64 ")>\n",
1812                        BaseAddr, BaseAddr + Size);
1813       continue;
1814     }
1815 
1816     StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
1817 
1818     // Dump out the content as hex and printable ascii characters.
1819     for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1820       outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1821       // Dump line of hex.
1822       for (std::size_t I = 0; I < 16; ++I) {
1823         if (I != 0 && I % 4 == 0)
1824           outs() << ' ';
1825         if (Addr + I < End)
1826           outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1827                  << hexdigit(Contents[Addr + I] & 0xF, true);
1828         else
1829           outs() << "  ";
1830       }
1831       // Print ascii.
1832       outs() << "  ";
1833       for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1834         if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1835           outs() << Contents[Addr + I];
1836         else
1837           outs() << ".";
1838       }
1839       outs() << "\n";
1840     }
1841   }
1842 }
1843 
1844 void printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1845                       StringRef ArchitectureName) {
1846   outs() << "SYMBOL TABLE:\n";
1847 
1848   if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1849     printCOFFSymbolTable(Coff);
1850     return;
1851   }
1852 
1853   const StringRef FileName = O->getFileName();
1854   const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(O);
1855   for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
1856     const SymbolRef &Symbol = *I;
1857     uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName,
1858                                      ArchitectureName);
1859     if ((Address < StartAddress) || (Address > StopAddress))
1860       continue;
1861     SymbolRef::Type Type = unwrapOrError(Symbol.getType(), FileName,
1862                                          ArchiveName, ArchitectureName);
1863     uint32_t Flags = Symbol.getFlags();
1864 
1865     // Don't ask a Mach-O STAB symbol for its section unless you know that
1866     // STAB symbol's section field refers to a valid section index. Otherwise
1867     // the symbol may error trying to load a section that does not exist.
1868     bool isSTAB = false;
1869     if (MachO) {
1870       DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
1871       uint8_t NType = (MachO->is64Bit() ?
1872                        MachO->getSymbol64TableEntry(SymDRI).n_type:
1873                        MachO->getSymbolTableEntry(SymDRI).n_type);
1874       if (NType & MachO::N_STAB)
1875         isSTAB = true;
1876     }
1877     section_iterator Section = isSTAB ? O->section_end() :
1878                                unwrapOrError(Symbol.getSection(), FileName,
1879                                              ArchiveName, ArchitectureName);
1880 
1881     StringRef Name;
1882     if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
1883       if (Expected<StringRef> NameOrErr = Section->getName())
1884         Name = *NameOrErr;
1885       else
1886         consumeError(NameOrErr.takeError());
1887 
1888     } else {
1889       Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName,
1890                            ArchitectureName);
1891     }
1892 
1893     bool Global = Flags & SymbolRef::SF_Global;
1894     bool Weak = Flags & SymbolRef::SF_Weak;
1895     bool Absolute = Flags & SymbolRef::SF_Absolute;
1896     bool Common = Flags & SymbolRef::SF_Common;
1897     bool Hidden = Flags & SymbolRef::SF_Hidden;
1898 
1899     char GlobLoc = ' ';
1900     if ((Section != O->section_end() || Absolute) && !Weak)
1901       GlobLoc = Global ? 'g' : 'l';
1902     char IFunc = ' ';
1903     if (auto *ELF = dyn_cast<ELFObjectFileBase>(O)) {
1904       if (ELFSymbolRef(*I).getELFType() == ELF::STT_GNU_IFUNC)
1905         IFunc = 'i';
1906     }
1907     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1908                  ? 'd' : ' ';
1909     char FileFunc = ' ';
1910     if (Type == SymbolRef::ST_File)
1911       FileFunc = 'f';
1912     else if (Type == SymbolRef::ST_Function)
1913       FileFunc = 'F';
1914     else if (Type == SymbolRef::ST_Data)
1915       FileFunc = 'O';
1916 
1917     const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
1918                                                    "%08" PRIx64;
1919 
1920     outs() << format(Fmt, Address) << " "
1921            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1922            << (Weak ? 'w' : ' ') // Weak?
1923            << ' ' // Constructor. Not supported yet.
1924            << ' ' // Warning. Not supported yet.
1925            << IFunc
1926            << Debug // Debugging (d) or dynamic (D) symbol.
1927            << FileFunc // Name of function (F), file (f) or object (O).
1928            << ' ';
1929     if (Absolute) {
1930       outs() << "*ABS*";
1931     } else if (Common) {
1932       outs() << "*COM*";
1933     } else if (Section == O->section_end()) {
1934       outs() << "*UND*";
1935     } else {
1936       if (const MachOObjectFile *MachO =
1937           dyn_cast<const MachOObjectFile>(O)) {
1938         DataRefImpl DR = Section->getRawDataRefImpl();
1939         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1940         outs() << SegmentName << ",";
1941       }
1942       StringRef SectionName =
1943           unwrapOrError(Section->getName(), O->getFileName());
1944       outs() << SectionName;
1945     }
1946 
1947     if (Common || isa<ELFObjectFileBase>(O)) {
1948       uint64_t Val =
1949           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1950       outs() << '\t' << format(Fmt, Val);
1951     }
1952 
1953     if (isa<ELFObjectFileBase>(O)) {
1954       uint8_t Other = ELFSymbolRef(Symbol).getOther();
1955       switch (Other) {
1956       case ELF::STV_DEFAULT:
1957         break;
1958       case ELF::STV_INTERNAL:
1959         outs() << " .internal";
1960         break;
1961       case ELF::STV_HIDDEN:
1962         outs() << " .hidden";
1963         break;
1964       case ELF::STV_PROTECTED:
1965         outs() << " .protected";
1966         break;
1967       default:
1968         outs() << format(" 0x%02x", Other);
1969         break;
1970       }
1971     } else if (Hidden) {
1972       outs() << " .hidden";
1973     }
1974 
1975     if (Demangle)
1976       outs() << ' ' << demangle(std::string(Name)) << '\n';
1977     else
1978       outs() << ' ' << Name << '\n';
1979   }
1980 }
1981 
1982 static void printUnwindInfo(const ObjectFile *O) {
1983   outs() << "Unwind info:\n\n";
1984 
1985   if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1986     printCOFFUnwindInfo(Coff);
1987   else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
1988     printMachOUnwindInfo(MachO);
1989   else
1990     // TODO: Extract DWARF dump tool to objdump.
1991     WithColor::error(errs(), ToolName)
1992         << "This operation is only currently supported "
1993            "for COFF and MachO object files.\n";
1994 }
1995 
1996 /// Dump the raw contents of the __clangast section so the output can be piped
1997 /// into llvm-bcanalyzer.
1998 void printRawClangAST(const ObjectFile *Obj) {
1999   if (outs().is_displayed()) {
2000     WithColor::error(errs(), ToolName)
2001         << "The -raw-clang-ast option will dump the raw binary contents of "
2002            "the clang ast section.\n"
2003            "Please redirect the output to a file or another program such as "
2004            "llvm-bcanalyzer.\n";
2005     return;
2006   }
2007 
2008   StringRef ClangASTSectionName("__clangast");
2009   if (isa<COFFObjectFile>(Obj)) {
2010     ClangASTSectionName = "clangast";
2011   }
2012 
2013   Optional<object::SectionRef> ClangASTSection;
2014   for (auto Sec : ToolSectionFilter(*Obj)) {
2015     StringRef Name;
2016     if (Expected<StringRef> NameOrErr = Sec.getName())
2017       Name = *NameOrErr;
2018     else
2019       consumeError(NameOrErr.takeError());
2020 
2021     if (Name == ClangASTSectionName) {
2022       ClangASTSection = Sec;
2023       break;
2024     }
2025   }
2026   if (!ClangASTSection)
2027     return;
2028 
2029   StringRef ClangASTContents = unwrapOrError(
2030       ClangASTSection.getValue().getContents(), Obj->getFileName());
2031   outs().write(ClangASTContents.data(), ClangASTContents.size());
2032 }
2033 
2034 static void printFaultMaps(const ObjectFile *Obj) {
2035   StringRef FaultMapSectionName;
2036 
2037   if (isa<ELFObjectFileBase>(Obj)) {
2038     FaultMapSectionName = ".llvm_faultmaps";
2039   } else if (isa<MachOObjectFile>(Obj)) {
2040     FaultMapSectionName = "__llvm_faultmaps";
2041   } else {
2042     WithColor::error(errs(), ToolName)
2043         << "This operation is only currently supported "
2044            "for ELF and Mach-O executable files.\n";
2045     return;
2046   }
2047 
2048   Optional<object::SectionRef> FaultMapSection;
2049 
2050   for (auto Sec : ToolSectionFilter(*Obj)) {
2051     StringRef Name;
2052     if (Expected<StringRef> NameOrErr = Sec.getName())
2053       Name = *NameOrErr;
2054     else
2055       consumeError(NameOrErr.takeError());
2056 
2057     if (Name == FaultMapSectionName) {
2058       FaultMapSection = Sec;
2059       break;
2060     }
2061   }
2062 
2063   outs() << "FaultMap table:\n";
2064 
2065   if (!FaultMapSection.hasValue()) {
2066     outs() << "<not found>\n";
2067     return;
2068   }
2069 
2070   StringRef FaultMapContents =
2071       unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName());
2072   FaultMapParser FMP(FaultMapContents.bytes_begin(),
2073                      FaultMapContents.bytes_end());
2074 
2075   outs() << FMP;
2076 }
2077 
2078 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
2079   if (O->isELF()) {
2080     printELFFileHeader(O);
2081     printELFDynamicSection(O);
2082     printELFSymbolVersionInfo(O);
2083     return;
2084   }
2085   if (O->isCOFF())
2086     return printCOFFFileHeader(O);
2087   if (O->isWasm())
2088     return printWasmFileHeader(O);
2089   if (O->isMachO()) {
2090     printMachOFileHeader(O);
2091     if (!OnlyFirst)
2092       printMachOLoadCommands(O);
2093     return;
2094   }
2095   reportError(O->getFileName(), "Invalid/Unsupported object file format");
2096 }
2097 
2098 static void printFileHeaders(const ObjectFile *O) {
2099   if (!O->isELF() && !O->isCOFF())
2100     reportError(O->getFileName(), "Invalid/Unsupported object file format");
2101 
2102   Triple::ArchType AT = O->getArch();
2103   outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2104   uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
2105 
2106   StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
2107   outs() << "start address: "
2108          << "0x" << format(Fmt.data(), Address) << "\n\n";
2109 }
2110 
2111 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2112   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2113   if (!ModeOrErr) {
2114     WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
2115     consumeError(ModeOrErr.takeError());
2116     return;
2117   }
2118   sys::fs::perms Mode = ModeOrErr.get();
2119   outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2120   outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2121   outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2122   outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2123   outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2124   outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2125   outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2126   outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2127   outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2128 
2129   outs() << " ";
2130 
2131   outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
2132                    unwrapOrError(C.getGID(), Filename),
2133                    unwrapOrError(C.getRawSize(), Filename));
2134 
2135   StringRef RawLastModified = C.getRawLastModified();
2136   unsigned Seconds;
2137   if (RawLastModified.getAsInteger(10, Seconds))
2138     outs() << "(date: \"" << RawLastModified
2139            << "\" contains non-decimal chars) ";
2140   else {
2141     // Since ctime(3) returns a 26 character string of the form:
2142     // "Sun Sep 16 01:03:52 1973\n\0"
2143     // just print 24 characters.
2144     time_t t = Seconds;
2145     outs() << format("%.24s ", ctime(&t));
2146   }
2147 
2148   StringRef Name = "";
2149   Expected<StringRef> NameOrErr = C.getName();
2150   if (!NameOrErr) {
2151     consumeError(NameOrErr.takeError());
2152     Name = unwrapOrError(C.getRawName(), Filename);
2153   } else {
2154     Name = NameOrErr.get();
2155   }
2156   outs() << Name << "\n";
2157 }
2158 
2159 // For ELF only now.
2160 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) {
2161   if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) {
2162     if (Elf->getEType() != ELF::ET_REL)
2163       return true;
2164   }
2165   return false;
2166 }
2167 
2168 static void checkForInvalidStartStopAddress(ObjectFile *Obj,
2169                                             uint64_t Start, uint64_t Stop) {
2170   if (!shouldWarnForInvalidStartStopAddress(Obj))
2171     return;
2172 
2173   for (const SectionRef &Section : Obj->sections())
2174     if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) {
2175       uint64_t BaseAddr = Section.getAddress();
2176       uint64_t Size = Section.getSize();
2177       if ((Start < BaseAddr + Size) && Stop > BaseAddr)
2178         return;
2179     }
2180 
2181   if (StartAddress.getNumOccurrences() == 0)
2182     reportWarning("no section has address less than 0x" +
2183                       Twine::utohexstr(Stop) + " specified by --stop-address",
2184                   Obj->getFileName());
2185   else if (StopAddress.getNumOccurrences() == 0)
2186     reportWarning("no section has address greater than or equal to 0x" +
2187                       Twine::utohexstr(Start) + " specified by --start-address",
2188                   Obj->getFileName());
2189   else
2190     reportWarning("no section overlaps the range [0x" +
2191                       Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) +
2192                       ") specified by --start-address/--stop-address",
2193                   Obj->getFileName());
2194 }
2195 
2196 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2197                        const Archive::Child *C = nullptr) {
2198   // Avoid other output when using a raw option.
2199   if (!RawClangAST) {
2200     outs() << '\n';
2201     if (A)
2202       outs() << A->getFileName() << "(" << O->getFileName() << ")";
2203     else
2204       outs() << O->getFileName();
2205     outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n\n";
2206   }
2207 
2208   if (StartAddress.getNumOccurrences() || StopAddress.getNumOccurrences())
2209     checkForInvalidStartStopAddress(O, StartAddress, StopAddress);
2210 
2211   // Note: the order here matches GNU objdump for compatability.
2212   StringRef ArchiveName = A ? A->getFileName() : "";
2213   if (ArchiveHeaders && !MachOOpt && C)
2214     printArchiveChild(ArchiveName, *C);
2215   if (FileHeaders)
2216     printFileHeaders(O);
2217   if (PrivateHeaders || FirstPrivateHeader)
2218     printPrivateFileHeaders(O, FirstPrivateHeader);
2219   if (SectionHeaders)
2220     printSectionHeaders(O);
2221   if (SymbolTable)
2222     printSymbolTable(O, ArchiveName);
2223   if (DwarfDumpType != DIDT_Null) {
2224     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2225     // Dump the complete DWARF structure.
2226     DIDumpOptions DumpOpts;
2227     DumpOpts.DumpType = DwarfDumpType;
2228     DICtx->dump(outs(), DumpOpts);
2229   }
2230   if (Relocations && !Disassemble)
2231     printRelocations(O);
2232   if (DynamicRelocations)
2233     printDynamicRelocations(O);
2234   if (SectionContents)
2235     printSectionContents(O);
2236   if (Disassemble)
2237     disassembleObject(O, Relocations);
2238   if (UnwindInfo)
2239     printUnwindInfo(O);
2240 
2241   // Mach-O specific options:
2242   if (ExportsTrie)
2243     printExportsTrie(O);
2244   if (Rebase)
2245     printRebaseTable(O);
2246   if (Bind)
2247     printBindTable(O);
2248   if (LazyBind)
2249     printLazyBindTable(O);
2250   if (WeakBind)
2251     printWeakBindTable(O);
2252 
2253   // Other special sections:
2254   if (RawClangAST)
2255     printRawClangAST(O);
2256   if (FaultMapSection)
2257     printFaultMaps(O);
2258 }
2259 
2260 static void dumpObject(const COFFImportFile *I, const Archive *A,
2261                        const Archive::Child *C = nullptr) {
2262   StringRef ArchiveName = A ? A->getFileName() : "";
2263 
2264   // Avoid other output when using a raw option.
2265   if (!RawClangAST)
2266     outs() << '\n'
2267            << ArchiveName << "(" << I->getFileName() << ")"
2268            << ":\tfile format COFF-import-file"
2269            << "\n\n";
2270 
2271   if (ArchiveHeaders && !MachOOpt && C)
2272     printArchiveChild(ArchiveName, *C);
2273   if (SymbolTable)
2274     printCOFFSymbolTable(I);
2275 }
2276 
2277 /// Dump each object file in \a a;
2278 static void dumpArchive(const Archive *A) {
2279   Error Err = Error::success();
2280   unsigned I = -1;
2281   for (auto &C : A->children(Err)) {
2282     ++I;
2283     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2284     if (!ChildOrErr) {
2285       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2286         reportError(std::move(E), getFileNameForError(C, I), A->getFileName());
2287       continue;
2288     }
2289     if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2290       dumpObject(O, A, &C);
2291     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2292       dumpObject(I, A, &C);
2293     else
2294       reportError(errorCodeToError(object_error::invalid_file_type),
2295                   A->getFileName());
2296   }
2297   if (Err)
2298     reportError(std::move(Err), A->getFileName());
2299 }
2300 
2301 /// Open file and figure out how to dump it.
2302 static void dumpInput(StringRef file) {
2303   // If we are using the Mach-O specific object file parser, then let it parse
2304   // the file and process the command line options.  So the -arch flags can
2305   // be used to select specific slices, etc.
2306   if (MachOOpt) {
2307     parseInputMachO(file);
2308     return;
2309   }
2310 
2311   // Attempt to open the binary.
2312   OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
2313   Binary &Binary = *OBinary.getBinary();
2314 
2315   if (Archive *A = dyn_cast<Archive>(&Binary))
2316     dumpArchive(A);
2317   else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2318     dumpObject(O);
2319   else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2320     parseInputMachO(UB);
2321   else
2322     reportError(errorCodeToError(object_error::invalid_file_type), file);
2323 }
2324 } // namespace llvm
2325 
2326 int main(int argc, char **argv) {
2327   using namespace llvm;
2328   InitLLVM X(argc, argv);
2329   const cl::OptionCategory *OptionFilters[] = {&ObjdumpCat, &MachOCat};
2330   cl::HideUnrelatedOptions(OptionFilters);
2331 
2332   // Initialize targets and assembly printers/parsers.
2333   InitializeAllTargetInfos();
2334   InitializeAllTargetMCs();
2335   InitializeAllDisassemblers();
2336 
2337   // Register the target printer for --version.
2338   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2339 
2340   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2341 
2342   if (StartAddress >= StopAddress)
2343     reportCmdLineError("start address should be less than stop address");
2344 
2345   ToolName = argv[0];
2346 
2347   // Defaults to a.out if no filenames specified.
2348   if (InputFilenames.empty())
2349     InputFilenames.push_back("a.out");
2350 
2351   if (AllHeaders)
2352     ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2353         SectionHeaders = SymbolTable = true;
2354 
2355   if (DisassembleAll || PrintSource || PrintLines ||
2356       !DisassembleSymbols.empty())
2357     Disassemble = true;
2358 
2359   if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
2360       !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
2361       !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
2362       !UnwindInfo && !FaultMapSection &&
2363       !(MachOOpt &&
2364         (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie ||
2365          FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind ||
2366          LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders ||
2367          WeakBind || !FilterSections.empty()))) {
2368     cl::PrintHelpMessage();
2369     return 2;
2370   }
2371 
2372   DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end());
2373 
2374   llvm::for_each(InputFilenames, dumpInput);
2375 
2376   warnOnNoMatchForSections();
2377 
2378   return EXIT_SUCCESS;
2379 }
2380