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