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