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