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