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