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