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