OSDN Git Service

[llvm-objdump] Add `Version References` dumper
[android-x86/external-llvm.git] / tools / llvm-objdump / llvm-objdump.cpp
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   // Find the number of leading zeroes.
875   size_t N = 0;
876   while (N < Buf.size() && !Buf[N])
877     ++N;
878
879   // We may want to skip blocks of zero bytes, but unless we see
880   // at least 8 of them in a row.
881   if (N < 8)
882     return 0;
883
884   // We skip zeroes in multiples of 4 because do not want to truncate an
885   // instruction if it starts with a zero byte.
886   return N & ~0x3;
887 }
888
889 // Returns a map from sections to their relocations.
890 static std::map<SectionRef, std::vector<RelocationRef>>
891 getRelocsMap(llvm::object::ObjectFile const &Obj) {
892   std::map<SectionRef, std::vector<RelocationRef>> Ret;
893   for (const SectionRef &Section : ToolSectionFilter(Obj)) {
894     section_iterator RelSec = Section.getRelocatedSection();
895     if (RelSec == Obj.section_end())
896       continue;
897     std::vector<RelocationRef> &V = Ret[*RelSec];
898     for (const RelocationRef &R : Section.relocations())
899       V.push_back(R);
900     // Sort relocations by address.
901     llvm::sort(V, isRelocAddressLess);
902   }
903   return Ret;
904 }
905
906 // Used for --adjust-vma to check if address should be adjusted by the
907 // specified value for a given section.
908 // For ELF we do not adjust non-allocatable sections like debug ones,
909 // because they are not loadable.
910 // TODO: implement for other file formats.
911 static bool shouldAdjustVA(const SectionRef &Section) {
912   const ObjectFile *Obj = Section.getObject();
913   if (isa<object::ELFObjectFileBase>(Obj))
914     return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
915   return false;
916 }
917
918 static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
919                               MCContext &Ctx, MCDisassembler *DisAsm,
920                               const MCInstrAnalysis *MIA, MCInstPrinter *IP,
921                               const MCSubtargetInfo *STI, PrettyPrinter &PIP,
922                               SourcePrinter &SP, bool InlineRelocs) {
923   std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
924   if (InlineRelocs)
925     RelocMap = getRelocsMap(*Obj);
926
927   // Create a mapping from virtual address to symbol name.  This is used to
928   // pretty print the symbols while disassembling.
929   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
930   SectionSymbolsTy AbsoluteSymbols;
931   for (const SymbolRef &Symbol : Obj->symbols()) {
932     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
933     if (!AddressOrErr)
934       report_error(Obj->getFileName(), AddressOrErr.takeError());
935     uint64_t Address = *AddressOrErr;
936
937     Expected<StringRef> Name = Symbol.getName();
938     if (!Name)
939       report_error(Obj->getFileName(), Name.takeError());
940     if (Name->empty())
941       continue;
942
943     Expected<section_iterator> SectionOrErr = Symbol.getSection();
944     if (!SectionOrErr)
945       report_error(Obj->getFileName(), SectionOrErr.takeError());
946
947     uint8_t SymbolType = ELF::STT_NOTYPE;
948     if (Obj->isELF()) {
949       SymbolType = getElfSymbolType(Obj, Symbol);
950       if (SymbolType == ELF::STT_SECTION)
951         continue;
952     }
953
954     section_iterator SecI = *SectionOrErr;
955     if (SecI != Obj->section_end())
956       AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
957     else
958       AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
959
960
961   }
962   if (AllSymbols.empty() && Obj->isELF())
963     addDynamicElfSymbols(Obj, AllSymbols);
964
965   BumpPtrAllocator A;
966   StringSaver Saver(A);
967   addPltEntries(Obj, AllSymbols, Saver);
968
969   // Create a mapping from virtual address to section.
970   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
971   for (SectionRef Sec : Obj->sections())
972     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
973   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
974
975   // Linked executables (.exe and .dll files) typically don't include a real
976   // symbol table but they might contain an export table.
977   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
978     for (const auto &ExportEntry : COFFObj->export_directories()) {
979       StringRef Name;
980       error(ExportEntry.getSymbolName(Name));
981       if (Name.empty())
982         continue;
983       uint32_t RVA;
984       error(ExportEntry.getExportRVA(RVA));
985
986       uint64_t VA = COFFObj->getImageBase() + RVA;
987       auto Sec = std::upper_bound(
988           SectionAddresses.begin(), SectionAddresses.end(), VA,
989           [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
990             return LHS < RHS.first;
991           });
992       if (Sec != SectionAddresses.begin())
993         --Sec;
994       else
995         Sec = SectionAddresses.end();
996
997       if (Sec != SectionAddresses.end())
998         AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
999       else
1000         AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1001     }
1002   }
1003
1004   // Sort all the symbols, this allows us to use a simple binary search to find
1005   // a symbol near an address.
1006   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1007     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1008   array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1009
1010   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1011     if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1012       continue;
1013
1014     uint64_t SectionAddr = Section.getAddress();
1015     uint64_t SectSize = Section.getSize();
1016     if (!SectSize)
1017       continue;
1018
1019     // Get the list of all the symbols in this section.
1020     SectionSymbolsTy &Symbols = AllSymbols[Section];
1021     std::vector<uint64_t> DataMappingSymsAddr;
1022     std::vector<uint64_t> TextMappingSymsAddr;
1023     if (isArmElf(Obj)) {
1024       for (const auto &Symb : Symbols) {
1025         uint64_t Address = std::get<0>(Symb);
1026         StringRef Name = std::get<1>(Symb);
1027         if (Name.startswith("$d"))
1028           DataMappingSymsAddr.push_back(Address - SectionAddr);
1029         if (Name.startswith("$x"))
1030           TextMappingSymsAddr.push_back(Address - SectionAddr);
1031         if (Name.startswith("$a"))
1032           TextMappingSymsAddr.push_back(Address - SectionAddr);
1033         if (Name.startswith("$t"))
1034           TextMappingSymsAddr.push_back(Address - SectionAddr);
1035       }
1036     }
1037
1038     llvm::sort(DataMappingSymsAddr);
1039     llvm::sort(TextMappingSymsAddr);
1040
1041     if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1042       // AMDGPU disassembler uses symbolizer for printing labels
1043       std::unique_ptr<MCRelocationInfo> RelInfo(
1044         TheTarget->createMCRelocationInfo(TripleName, Ctx));
1045       if (RelInfo) {
1046         std::unique_ptr<MCSymbolizer> Symbolizer(
1047           TheTarget->createMCSymbolizer(
1048             TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1049         DisAsm->setSymbolizer(std::move(Symbolizer));
1050       }
1051     }
1052
1053     StringRef SegmentName = "";
1054     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1055       DataRefImpl DR = Section.getRawDataRefImpl();
1056       SegmentName = MachO->getSectionFinalSegmentName(DR);
1057     }
1058     StringRef SectionName;
1059     error(Section.getName(SectionName));
1060
1061     // If the section has no symbol at the start, just insert a dummy one.
1062     if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1063       Symbols.insert(
1064           Symbols.begin(),
1065           std::make_tuple(SectionAddr, SectionName,
1066                           Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1067     }
1068
1069     SmallString<40> Comments;
1070     raw_svector_ostream CommentStream(Comments);
1071
1072     StringRef BytesStr;
1073     error(Section.getContents(BytesStr));
1074     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1075                             BytesStr.size());
1076
1077     uint64_t VMAAdjustment = 0;
1078     if (shouldAdjustVA(Section))
1079       VMAAdjustment = AdjustVMA;
1080
1081     uint64_t Size;
1082     uint64_t Index;
1083     bool PrintedSection = false;
1084     std::vector<RelocationRef> Rels = RelocMap[Section];
1085     std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1086     std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
1087     // Disassemble symbol by symbol.
1088     for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
1089       uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr;
1090       // The end is either the section end or the beginning of the next
1091       // symbol.
1092       uint64_t End = (SI == SE - 1)
1093                          ? SectSize
1094                          : std::get<0>(Symbols[SI + 1]) - SectionAddr;
1095       // Don't try to disassemble beyond the end of section contents.
1096       if (End > SectSize)
1097         End = SectSize;
1098       // If this symbol has the same address as the next symbol, then skip it.
1099       if (Start >= End)
1100         continue;
1101
1102       // Check if we need to skip symbol
1103       // Skip if the symbol's data is not between StartAddress and StopAddress
1104       if (End + SectionAddr < StartAddress ||
1105           Start + SectionAddr > StopAddress) {
1106         continue;
1107       }
1108
1109       /// Skip if user requested specific symbols and this is not in the list
1110       if (!DisasmFuncsSet.empty() &&
1111           !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
1112         continue;
1113
1114       if (!PrintedSection) {
1115         PrintedSection = true;
1116         outs() << "Disassembly of section ";
1117         if (!SegmentName.empty())
1118           outs() << SegmentName << ",";
1119         outs() << SectionName << ':';
1120       }
1121
1122       // Stop disassembly at the stop address specified
1123       if (End + SectionAddr > StopAddress)
1124         End = StopAddress - SectionAddr;
1125
1126       if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1127         if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1128           // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1129           Start += 256;
1130         }
1131         if (SI == SE - 1 ||
1132             std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1133           // cut trailing zeroes at the end of kernel
1134           // cut up to 256 bytes
1135           const uint64_t EndAlign = 256;
1136           const auto Limit = End - (std::min)(EndAlign, End - Start);
1137           while (End > Limit &&
1138             *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1139             End -= 4;
1140         }
1141       }
1142
1143       outs() << '\n';
1144       if (!NoLeadingAddr)
1145         outs() << format("%016" PRIx64 " ",
1146                          SectionAddr + Start + VMAAdjustment);
1147
1148       StringRef SymbolName = std::get<1>(Symbols[SI]);
1149       if (Demangle)
1150         outs() << demangle(SymbolName) << ":\n";
1151       else
1152         outs() << SymbolName << ":\n";
1153
1154       // Don't print raw contents of a virtual section. A virtual section
1155       // doesn't have any contents in the file.
1156       if (Section.isVirtual()) {
1157         outs() << "...\n";
1158         continue;
1159       }
1160
1161 #ifndef NDEBUG
1162       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1163 #else
1164       raw_ostream &DebugOut = nulls();
1165 #endif
1166
1167       // Some targets (like WebAssembly) have a special prelude at the start
1168       // of each symbol.
1169       DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1170                             SectionAddr + Start, DebugOut, CommentStream);
1171       Start += Size;
1172
1173       for (Index = Start; Index < End; Index += Size) {
1174         MCInst Inst;
1175
1176         if (Index + SectionAddr < StartAddress ||
1177             Index + SectionAddr > StopAddress) {
1178           // skip byte by byte till StartAddress is reached
1179           Size = 1;
1180           continue;
1181         }
1182         // AArch64 ELF binaries can interleave data and text in the
1183         // same section. We rely on the markers introduced to
1184         // understand what we need to dump. If the data marker is within a
1185         // function, it is denoted as a word/short etc
1186         if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
1187             !DisassembleAll) {
1188           uint64_t Stride = 0;
1189
1190           auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1191                                       DataMappingSymsAddr.end(), Index);
1192           if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1193             // Switch to data.
1194             while (Index < End) {
1195               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1196               outs() << "\t";
1197               if (Index + 4 <= End) {
1198                 Stride = 4;
1199                 dumpBytes(Bytes.slice(Index, 4), outs());
1200                 outs() << "\t.word\t";
1201                 uint32_t Data = 0;
1202                 if (Obj->isLittleEndian()) {
1203                   const auto Word =
1204                       reinterpret_cast<const support::ulittle32_t *>(
1205                           Bytes.data() + Index);
1206                   Data = *Word;
1207                 } else {
1208                   const auto Word = reinterpret_cast<const support::ubig32_t *>(
1209                       Bytes.data() + Index);
1210                   Data = *Word;
1211                 }
1212                 outs() << "0x" << format("%08" PRIx32, Data);
1213               } else if (Index + 2 <= End) {
1214                 Stride = 2;
1215                 dumpBytes(Bytes.slice(Index, 2), outs());
1216                 outs() << "\t\t.short\t";
1217                 uint16_t Data = 0;
1218                 if (Obj->isLittleEndian()) {
1219                   const auto Short =
1220                       reinterpret_cast<const support::ulittle16_t *>(
1221                           Bytes.data() + Index);
1222                   Data = *Short;
1223                 } else {
1224                   const auto Short =
1225                       reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1226                                                                   Index);
1227                   Data = *Short;
1228                 }
1229                 outs() << "0x" << format("%04" PRIx16, Data);
1230               } else {
1231                 Stride = 1;
1232                 dumpBytes(Bytes.slice(Index, 1), outs());
1233                 outs() << "\t\t.byte\t";
1234                 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1235               }
1236               Index += Stride;
1237               outs() << "\n";
1238               auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1239                                           TextMappingSymsAddr.end(), Index);
1240               if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1241                 break;
1242             }
1243           }
1244         }
1245
1246         // If there is a data symbol inside an ELF text section and we are only
1247         // disassembling text (applicable all architectures),
1248         // we are in a situation where we must print the data and not
1249         // disassemble it.
1250         if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
1251             !DisassembleAll && Section.isText()) {
1252           // print out data up to 8 bytes at a time in hex and ascii
1253           uint8_t AsciiData[9] = {'\0'};
1254           uint8_t Byte;
1255           int NumBytes = 0;
1256
1257           for (Index = Start; Index < End; Index += 1) {
1258             if (((SectionAddr + Index) < StartAddress) ||
1259                 ((SectionAddr + Index) > StopAddress))
1260               continue;
1261             if (NumBytes == 0) {
1262               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1263               outs() << "\t";
1264             }
1265             Byte = Bytes.slice(Index)[0];
1266             outs() << format(" %02x", Byte);
1267             AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1268
1269             uint8_t IndentOffset = 0;
1270             NumBytes++;
1271             if (Index == End - 1 || NumBytes > 8) {
1272               // Indent the space for less than 8 bytes data.
1273               // 2 spaces for byte and one for space between bytes
1274               IndentOffset = 3 * (8 - NumBytes);
1275               for (int Excess = NumBytes; Excess < 8; Excess++)
1276                 AsciiData[Excess] = '\0';
1277               NumBytes = 8;
1278             }
1279             if (NumBytes == 8) {
1280               AsciiData[8] = '\0';
1281               outs() << std::string(IndentOffset, ' ') << "         ";
1282               outs() << reinterpret_cast<char *>(AsciiData);
1283               outs() << '\n';
1284               NumBytes = 0;
1285             }
1286           }
1287         }
1288         if (Index >= End)
1289           break;
1290
1291         // When -z or --disassemble-zeroes are given we always dissasemble them.
1292         // Otherwise we might want to skip zero bytes we see.
1293         if (!DisassembleZeroes) {
1294           uint64_t MaxOffset = End - Index;
1295           // For -reloc: print zero blocks patched by relocations, so that
1296           // relocations can be shown in the dump.
1297           if (RelCur != RelEnd)
1298             MaxOffset = RelCur->getOffset() - Index;
1299
1300           if (size_t N =
1301                   countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1302             outs() << "\t\t..." << '\n';
1303             Index += N;
1304             if (Index >= End)
1305               break;
1306           }
1307         }
1308
1309         // Disassemble a real instruction or a data when disassemble all is
1310         // provided
1311         bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1312                                                    SectionAddr + Index, DebugOut,
1313                                                    CommentStream);
1314         if (Size == 0)
1315           Size = 1;
1316
1317         PIP.printInst(
1318             *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
1319             SectionAddr + Index + VMAAdjustment, outs(), "", *STI, &SP, &Rels);
1320         outs() << CommentStream.str();
1321         Comments.clear();
1322
1323         // Try to resolve the target of a call, tail call, etc. to a specific
1324         // symbol.
1325         if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1326                     MIA->isConditionalBranch(Inst))) {
1327           uint64_t Target;
1328           if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1329             // In a relocatable object, the target's section must reside in
1330             // the same section as the call instruction or it is accessed
1331             // through a relocation.
1332             //
1333             // In a non-relocatable object, the target may be in any section.
1334             //
1335             // N.B. We don't walk the relocations in the relocatable case yet.
1336             auto *TargetSectionSymbols = &Symbols;
1337             if (!Obj->isRelocatableObject()) {
1338               auto SectionAddress = std::upper_bound(
1339                   SectionAddresses.begin(), SectionAddresses.end(), Target,
1340                   [](uint64_t LHS,
1341                       const std::pair<uint64_t, SectionRef> &RHS) {
1342                     return LHS < RHS.first;
1343                   });
1344               if (SectionAddress != SectionAddresses.begin()) {
1345                 --SectionAddress;
1346                 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1347               } else {
1348                 TargetSectionSymbols = &AbsoluteSymbols;
1349               }
1350             }
1351
1352             // Find the first symbol in the section whose offset is less than
1353             // or equal to the target. If there isn't a section that contains
1354             // the target, find the nearest preceding absolute symbol.
1355             auto TargetSym = std::upper_bound(
1356                 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1357                 Target, [](uint64_t LHS,
1358                            const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1359                   return LHS < std::get<0>(RHS);
1360                 });
1361             if (TargetSym == TargetSectionSymbols->begin()) {
1362               TargetSectionSymbols = &AbsoluteSymbols;
1363               TargetSym = std::upper_bound(
1364                   AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1365                   Target, [](uint64_t LHS,
1366                              const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1367                             return LHS < std::get<0>(RHS);
1368                           });
1369             }
1370             if (TargetSym != TargetSectionSymbols->begin()) {
1371               --TargetSym;
1372               uint64_t TargetAddress = std::get<0>(*TargetSym);
1373               StringRef TargetName = std::get<1>(*TargetSym);
1374               outs() << " <" << TargetName;
1375               uint64_t Disp = Target - TargetAddress;
1376               if (Disp)
1377                 outs() << "+0x" << Twine::utohexstr(Disp);
1378               outs() << '>';
1379             }
1380           }
1381         }
1382         outs() << "\n";
1383
1384         // Hexagon does this in pretty printer
1385         if (Obj->getArch() != Triple::hexagon) {
1386           // Print relocation for instruction.
1387           while (RelCur != RelEnd) {
1388             uint64_t Offset = RelCur->getOffset();
1389             // If this relocation is hidden, skip it.
1390             if (getHidden(*RelCur) || ((SectionAddr + Offset) < StartAddress)) {
1391               ++RelCur;
1392               continue;
1393             }
1394
1395             // Stop when RelCur's offset is past the current instruction.
1396             if (Offset >= Index + Size)
1397               break;
1398
1399             // When --adjust-vma is used, update the address printed.
1400             if (RelCur->getSymbol() != Obj->symbol_end()) {
1401               Expected<section_iterator> SymSI =
1402                   RelCur->getSymbol()->getSection();
1403               if (SymSI && *SymSI != Obj->section_end() &&
1404                   (shouldAdjustVA(**SymSI)))
1405                 Offset += AdjustVMA;
1406             }
1407
1408             printRelocation(*RelCur, SectionAddr + Offset,
1409                             Obj->getBytesInAddress());
1410             ++RelCur;
1411           }
1412         }
1413       }
1414     }
1415   }
1416 }
1417
1418 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1419   if (StartAddress > StopAddress)
1420     error("Start address should be less than stop address");
1421
1422   const Target *TheTarget = getTarget(Obj);
1423
1424   // Package up features to be passed to target/subtarget
1425   SubtargetFeatures Features = Obj->getFeatures();
1426   if (!MAttrs.empty())
1427     for (unsigned I = 0; I != MAttrs.size(); ++I)
1428       Features.AddFeature(MAttrs[I]);
1429
1430   std::unique_ptr<const MCRegisterInfo> MRI(
1431       TheTarget->createMCRegInfo(TripleName));
1432   if (!MRI)
1433     report_error(Obj->getFileName(),
1434                  "no register info for target " + TripleName);
1435
1436   // Set up disassembler.
1437   std::unique_ptr<const MCAsmInfo> AsmInfo(
1438       TheTarget->createMCAsmInfo(*MRI, TripleName));
1439   if (!AsmInfo)
1440     report_error(Obj->getFileName(),
1441                  "no assembly info for target " + TripleName);
1442   std::unique_ptr<const MCSubtargetInfo> STI(
1443       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1444   if (!STI)
1445     report_error(Obj->getFileName(),
1446                  "no subtarget info for target " + TripleName);
1447   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1448   if (!MII)
1449     report_error(Obj->getFileName(),
1450                  "no instruction info for target " + TripleName);
1451   MCObjectFileInfo MOFI;
1452   MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1453   // FIXME: for now initialize MCObjectFileInfo with default values
1454   MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1455
1456   std::unique_ptr<MCDisassembler> DisAsm(
1457       TheTarget->createMCDisassembler(*STI, Ctx));
1458   if (!DisAsm)
1459     report_error(Obj->getFileName(),
1460                  "no disassembler for target " + TripleName);
1461
1462   std::unique_ptr<const MCInstrAnalysis> MIA(
1463       TheTarget->createMCInstrAnalysis(MII.get()));
1464
1465   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1466   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1467       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1468   if (!IP)
1469     report_error(Obj->getFileName(),
1470                  "no instruction printer for target " + TripleName);
1471   IP->setPrintImmHex(PrintImmHex);
1472
1473   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1474   SourcePrinter SP(Obj, TheTarget->getName());
1475
1476   disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(),
1477                     STI.get(), PIP, SP, InlineRelocs);
1478 }
1479
1480 void llvm::printRelocations(const ObjectFile *Obj) {
1481   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1482                                                  "%08" PRIx64;
1483   // Regular objdump doesn't print relocations in non-relocatable object
1484   // files.
1485   if (!Obj->isRelocatableObject())
1486     return;
1487
1488   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1489     if (Section.relocation_begin() == Section.relocation_end())
1490       continue;
1491     StringRef SecName;
1492     error(Section.getName(SecName));
1493     outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
1494     for (const RelocationRef &Reloc : Section.relocations()) {
1495       uint64_t Address = Reloc.getOffset();
1496       SmallString<32> RelocName;
1497       SmallString<32> ValueStr;
1498       if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1499         continue;
1500       Reloc.getTypeName(RelocName);
1501       error(getRelocationValueString(Reloc, ValueStr));
1502       outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1503              << ValueStr << "\n";
1504     }
1505     outs() << "\n";
1506   }
1507 }
1508
1509 void llvm::printDynamicRelocations(const ObjectFile *Obj) {
1510   // For the moment, this option is for ELF only
1511   if (!Obj->isELF())
1512     return;
1513
1514   const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1515   if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1516     error("not a dynamic object");
1517     return;
1518   }
1519
1520   std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1521   if (DynRelSec.empty())
1522     return;
1523
1524   outs() << "DYNAMIC RELOCATION RECORDS\n";
1525   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1526   for (const SectionRef &Section : DynRelSec) {
1527     if (Section.relocation_begin() == Section.relocation_end())
1528       continue;
1529     for (const RelocationRef &Reloc : Section.relocations()) {
1530       uint64_t Address = Reloc.getOffset();
1531       SmallString<32> RelocName;
1532       SmallString<32> ValueStr;
1533       Reloc.getTypeName(RelocName);
1534       error(getRelocationValueString(Reloc, ValueStr));
1535       outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1536              << ValueStr << "\n";
1537     }
1538   }
1539 }
1540
1541 // Returns true if we need to show LMA column when dumping section headers. We
1542 // show it only when the platform is ELF and either we have at least one section
1543 // whose VMA and LMA are different and/or when --show-lma flag is used.
1544 static bool shouldDisplayLMA(const ObjectFile *Obj) {
1545   if (!Obj->isELF())
1546     return false;
1547   for (const SectionRef &S : ToolSectionFilter(*Obj))
1548     if (S.getAddress() != getELFSectionLMA(S))
1549       return true;
1550   return ShowLMA;
1551 }
1552
1553 void llvm::printSectionHeaders(const ObjectFile *Obj) {
1554   bool HasLMAColumn = shouldDisplayLMA(Obj);
1555   if (HasLMAColumn)
1556     outs() << "Sections:\n"
1557               "Idx Name          Size     VMA              LMA              "
1558               "Type\n";
1559   else
1560     outs() << "Sections:\n"
1561               "Idx Name          Size     VMA          Type\n";
1562
1563   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1564     StringRef Name;
1565     error(Section.getName(Name));
1566     uint64_t VMA = Section.getAddress();
1567     if (shouldAdjustVA(Section))
1568       VMA += AdjustVMA;
1569
1570     uint64_t Size = Section.getSize();
1571     bool Text = Section.isText();
1572     bool Data = Section.isData();
1573     bool BSS = Section.isBSS();
1574     std::string Type = (std::string(Text ? "TEXT " : "") +
1575                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1576
1577     if (HasLMAColumn)
1578       outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64
1579                        " %s\n",
1580                        (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1581                        VMA, getELFSectionLMA(Section), Type.c_str());
1582     else
1583       outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1584                        (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1585                        VMA, Type.c_str());
1586   }
1587   outs() << "\n";
1588 }
1589
1590 void llvm::printSectionContents(const ObjectFile *Obj) {
1591   std::error_code EC;
1592   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1593     StringRef Name;
1594     StringRef Contents;
1595     error(Section.getName(Name));
1596     uint64_t BaseAddr = Section.getAddress();
1597     uint64_t Size = Section.getSize();
1598     if (!Size)
1599       continue;
1600
1601     outs() << "Contents of section " << Name << ":\n";
1602     if (Section.isBSS()) {
1603       outs() << format("<skipping contents of bss section at [%04" PRIx64
1604                        ", %04" PRIx64 ")>\n",
1605                        BaseAddr, BaseAddr + Size);
1606       continue;
1607     }
1608
1609     error(Section.getContents(Contents));
1610
1611     // Dump out the content as hex and printable ascii characters.
1612     for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1613       outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
1614       // Dump line of hex.
1615       for (std::size_t I = 0; I < 16; ++I) {
1616         if (I != 0 && I % 4 == 0)
1617           outs() << ' ';
1618         if (Addr + I < End)
1619           outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1620                  << hexdigit(Contents[Addr + I] & 0xF, true);
1621         else
1622           outs() << "  ";
1623       }
1624       // Print ascii.
1625       outs() << "  ";
1626       for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1627         if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1628           outs() << Contents[Addr + I];
1629         else
1630           outs() << ".";
1631       }
1632       outs() << "\n";
1633     }
1634   }
1635 }
1636
1637 void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1638                             StringRef ArchitectureName) {
1639   outs() << "SYMBOL TABLE:\n";
1640
1641   if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1642     printCOFFSymbolTable(Coff);
1643     return;
1644   }
1645
1646   for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
1647     // Skip printing the special zero symbol when dumping an ELF file.
1648     // This makes the output consistent with the GNU objdump.
1649     if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
1650       continue;
1651
1652     const SymbolRef &Symbol = *I;
1653     Expected<uint64_t> AddressOrError = Symbol.getAddress();
1654     if (!AddressOrError)
1655       report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(),
1656                    ArchitectureName);
1657     uint64_t Address = *AddressOrError;
1658     if ((Address < StartAddress) || (Address > StopAddress))
1659       continue;
1660     Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1661     if (!TypeOrError)
1662       report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(),
1663                    ArchitectureName);
1664     SymbolRef::Type Type = *TypeOrError;
1665     uint32_t Flags = Symbol.getFlags();
1666     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1667     if (!SectionOrErr)
1668       report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(),
1669                    ArchitectureName);
1670     section_iterator Section = *SectionOrErr;
1671     StringRef Name;
1672     if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
1673       Section->getName(Name);
1674     } else {
1675       Expected<StringRef> NameOrErr = Symbol.getName();
1676       if (!NameOrErr)
1677         report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(),
1678                      ArchitectureName);
1679       Name = *NameOrErr;
1680     }
1681
1682     bool Global = Flags & SymbolRef::SF_Global;
1683     bool Weak = Flags & SymbolRef::SF_Weak;
1684     bool Absolute = Flags & SymbolRef::SF_Absolute;
1685     bool Common = Flags & SymbolRef::SF_Common;
1686     bool Hidden = Flags & SymbolRef::SF_Hidden;
1687
1688     char GlobLoc = ' ';
1689     if (Type != SymbolRef::ST_Unknown)
1690       GlobLoc = Global ? 'g' : 'l';
1691     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1692                  ? 'd' : ' ';
1693     char FileFunc = ' ';
1694     if (Type == SymbolRef::ST_File)
1695       FileFunc = 'f';
1696     else if (Type == SymbolRef::ST_Function)
1697       FileFunc = 'F';
1698     else if (Type == SymbolRef::ST_Data)
1699       FileFunc = 'O';
1700
1701     const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
1702                                                    "%08" PRIx64;
1703
1704     outs() << format(Fmt, Address) << " "
1705            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1706            << (Weak ? 'w' : ' ') // Weak?
1707            << ' ' // Constructor. Not supported yet.
1708            << ' ' // Warning. Not supported yet.
1709            << ' ' // Indirect reference to another symbol.
1710            << Debug // Debugging (d) or dynamic (D) symbol.
1711            << FileFunc // Name of function (F), file (f) or object (O).
1712            << ' ';
1713     if (Absolute) {
1714       outs() << "*ABS*";
1715     } else if (Common) {
1716       outs() << "*COM*";
1717     } else if (Section == O->section_end()) {
1718       outs() << "*UND*";
1719     } else {
1720       if (const MachOObjectFile *MachO =
1721           dyn_cast<const MachOObjectFile>(O)) {
1722         DataRefImpl DR = Section->getRawDataRefImpl();
1723         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1724         outs() << SegmentName << ",";
1725       }
1726       StringRef SectionName;
1727       error(Section->getName(SectionName));
1728       outs() << SectionName;
1729     }
1730
1731     outs() << '\t';
1732     if (Common || isa<ELFObjectFileBase>(O)) {
1733       uint64_t Val =
1734           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1735       outs() << format("\t %08" PRIx64 " ", Val);
1736     }
1737
1738     if (Hidden)
1739       outs() << ".hidden ";
1740
1741     if (Demangle)
1742       outs() << demangle(Name) << '\n';
1743     else
1744       outs() << Name << '\n';
1745   }
1746 }
1747
1748 static void printUnwindInfo(const ObjectFile *O) {
1749   outs() << "Unwind info:\n\n";
1750
1751   if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1752     printCOFFUnwindInfo(Coff);
1753   else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
1754     printMachOUnwindInfo(MachO);
1755   else
1756     // TODO: Extract DWARF dump tool to objdump.
1757     WithColor::error(errs(), ToolName)
1758         << "This operation is only currently supported "
1759            "for COFF and MachO object files.\n";
1760 }
1761
1762 void llvm::printExportsTrie(const ObjectFile *o) {
1763   outs() << "Exports trie:\n";
1764   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1765     printMachOExportsTrie(MachO);
1766   else
1767     WithColor::error(errs(), ToolName)
1768         << "This operation is only currently supported "
1769            "for Mach-O executable files.\n";
1770 }
1771
1772 void llvm::printRebaseTable(ObjectFile *o) {
1773   outs() << "Rebase table:\n";
1774   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1775     printMachORebaseTable(MachO);
1776   else
1777     WithColor::error(errs(), ToolName)
1778         << "This operation is only currently supported "
1779            "for Mach-O executable files.\n";
1780 }
1781
1782 void llvm::printBindTable(ObjectFile *o) {
1783   outs() << "Bind table:\n";
1784   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1785     printMachOBindTable(MachO);
1786   else
1787     WithColor::error(errs(), ToolName)
1788         << "This operation is only currently supported "
1789            "for Mach-O executable files.\n";
1790 }
1791
1792 void llvm::printLazyBindTable(ObjectFile *o) {
1793   outs() << "Lazy bind table:\n";
1794   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1795     printMachOLazyBindTable(MachO);
1796   else
1797     WithColor::error(errs(), ToolName)
1798         << "This operation is only currently supported "
1799            "for Mach-O executable files.\n";
1800 }
1801
1802 void llvm::printWeakBindTable(ObjectFile *o) {
1803   outs() << "Weak bind table:\n";
1804   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1805     printMachOWeakBindTable(MachO);
1806   else
1807     WithColor::error(errs(), ToolName)
1808         << "This operation is only currently supported "
1809            "for Mach-O executable files.\n";
1810 }
1811
1812 /// Dump the raw contents of the __clangast section so the output can be piped
1813 /// into llvm-bcanalyzer.
1814 void llvm::printRawClangAST(const ObjectFile *Obj) {
1815   if (outs().is_displayed()) {
1816     WithColor::error(errs(), ToolName)
1817         << "The -raw-clang-ast option will dump the raw binary contents of "
1818            "the clang ast section.\n"
1819            "Please redirect the output to a file or another program such as "
1820            "llvm-bcanalyzer.\n";
1821     return;
1822   }
1823
1824   StringRef ClangASTSectionName("__clangast");
1825   if (isa<COFFObjectFile>(Obj)) {
1826     ClangASTSectionName = "clangast";
1827   }
1828
1829   Optional<object::SectionRef> ClangASTSection;
1830   for (auto Sec : ToolSectionFilter(*Obj)) {
1831     StringRef Name;
1832     Sec.getName(Name);
1833     if (Name == ClangASTSectionName) {
1834       ClangASTSection = Sec;
1835       break;
1836     }
1837   }
1838   if (!ClangASTSection)
1839     return;
1840
1841   StringRef ClangASTContents;
1842   error(ClangASTSection.getValue().getContents(ClangASTContents));
1843   outs().write(ClangASTContents.data(), ClangASTContents.size());
1844 }
1845
1846 static void printFaultMaps(const ObjectFile *Obj) {
1847   StringRef FaultMapSectionName;
1848
1849   if (isa<ELFObjectFileBase>(Obj)) {
1850     FaultMapSectionName = ".llvm_faultmaps";
1851   } else if (isa<MachOObjectFile>(Obj)) {
1852     FaultMapSectionName = "__llvm_faultmaps";
1853   } else {
1854     WithColor::error(errs(), ToolName)
1855         << "This operation is only currently supported "
1856            "for ELF and Mach-O executable files.\n";
1857     return;
1858   }
1859
1860   Optional<object::SectionRef> FaultMapSection;
1861
1862   for (auto Sec : ToolSectionFilter(*Obj)) {
1863     StringRef Name;
1864     Sec.getName(Name);
1865     if (Name == FaultMapSectionName) {
1866       FaultMapSection = Sec;
1867       break;
1868     }
1869   }
1870
1871   outs() << "FaultMap table:\n";
1872
1873   if (!FaultMapSection.hasValue()) {
1874     outs() << "<not found>\n";
1875     return;
1876   }
1877
1878   StringRef FaultMapContents;
1879   error(FaultMapSection.getValue().getContents(FaultMapContents));
1880
1881   FaultMapParser FMP(FaultMapContents.bytes_begin(),
1882                      FaultMapContents.bytes_end());
1883
1884   outs() << FMP;
1885 }
1886
1887 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
1888   if (O->isELF()) {
1889     printELFFileHeader(O);
1890     printELFDynamicSection(O);
1891     printELFSymbolVersionInfo(O);
1892     return;
1893   }
1894   if (O->isCOFF())
1895     return printCOFFFileHeader(O);
1896   if (O->isWasm())
1897     return printWasmFileHeader(O);
1898   if (O->isMachO()) {
1899     printMachOFileHeader(O);
1900     if (!OnlyFirst)
1901       printMachOLoadCommands(O);
1902     return;
1903   }
1904   report_error(O->getFileName(), "Invalid/Unsupported object file format");
1905 }
1906
1907 static void printFileHeaders(const ObjectFile *O) {
1908   if (!O->isELF() && !O->isCOFF())
1909     report_error(O->getFileName(), "Invalid/Unsupported object file format");
1910
1911   Triple::ArchType AT = O->getArch();
1912   outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
1913   Expected<uint64_t> StartAddrOrErr = O->getStartAddress();
1914   if (!StartAddrOrErr)
1915     report_error(O->getFileName(), StartAddrOrErr.takeError());
1916
1917   StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
1918   uint64_t Address = StartAddrOrErr.get();
1919   outs() << "start address: "
1920          << "0x" << format(Fmt.data(), Address) << "\n\n";
1921 }
1922
1923 static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
1924   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1925   if (!ModeOrErr) {
1926     WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
1927     consumeError(ModeOrErr.takeError());
1928     return;
1929   }
1930   sys::fs::perms Mode = ModeOrErr.get();
1931   outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1932   outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1933   outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1934   outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1935   outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1936   outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1937   outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1938   outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1939   outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1940
1941   outs() << " ";
1942
1943   Expected<unsigned> UIDOrErr = C.getUID();
1944   if (!UIDOrErr)
1945     report_error(Filename, UIDOrErr.takeError());
1946   unsigned UID = UIDOrErr.get();
1947   outs() << format("%d/", UID);
1948
1949   Expected<unsigned> GIDOrErr = C.getGID();
1950   if (!GIDOrErr)
1951     report_error(Filename, GIDOrErr.takeError());
1952   unsigned GID = GIDOrErr.get();
1953   outs() << format("%-d ", GID);
1954
1955   Expected<uint64_t> Size = C.getRawSize();
1956   if (!Size)
1957     report_error(Filename, Size.takeError());
1958   outs() << format("%6" PRId64, Size.get()) << " ";
1959
1960   StringRef RawLastModified = C.getRawLastModified();
1961   unsigned Seconds;
1962   if (RawLastModified.getAsInteger(10, Seconds))
1963     outs() << "(date: \"" << RawLastModified
1964            << "\" contains non-decimal chars) ";
1965   else {
1966     // Since ctime(3) returns a 26 character string of the form:
1967     // "Sun Sep 16 01:03:52 1973\n\0"
1968     // just print 24 characters.
1969     time_t t = Seconds;
1970     outs() << format("%.24s ", ctime(&t));
1971   }
1972
1973   StringRef Name = "";
1974   Expected<StringRef> NameOrErr = C.getName();
1975   if (!NameOrErr) {
1976     consumeError(NameOrErr.takeError());
1977     Expected<StringRef> RawNameOrErr = C.getRawName();
1978     if (!RawNameOrErr)
1979       report_error(Filename, NameOrErr.takeError());
1980     Name = RawNameOrErr.get();
1981   } else {
1982     Name = NameOrErr.get();
1983   }
1984   outs() << Name << "\n";
1985 }
1986
1987 static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
1988                        const Archive::Child *C = nullptr) {
1989   // Avoid other output when using a raw option.
1990   if (!RawClangAST) {
1991     outs() << '\n';
1992     if (A)
1993       outs() << A->getFileName() << "(" << O->getFileName() << ")";
1994     else
1995       outs() << O->getFileName();
1996     outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
1997   }
1998
1999   StringRef ArchiveName = A ? A->getFileName() : "";
2000   if (FileHeaders)
2001     printFileHeaders(O);
2002   if (ArchiveHeaders && !MachOOpt && C)
2003     printArchiveChild(ArchiveName, *C);
2004   if (Disassemble)
2005     disassembleObject(O, Relocations);
2006   if (Relocations && !Disassemble)
2007     printRelocations(O);
2008   if (DynamicRelocations)
2009     printDynamicRelocations(O);
2010   if (SectionHeaders)
2011     printSectionHeaders(O);
2012   if (SectionContents)
2013     printSectionContents(O);
2014   if (SymbolTable)
2015     printSymbolTable(O, ArchiveName);
2016   if (UnwindInfo)
2017     printUnwindInfo(O);
2018   if (PrivateHeaders || FirstPrivateHeader)
2019     printPrivateFileHeaders(O, FirstPrivateHeader);
2020   if (ExportsTrie)
2021     printExportsTrie(O);
2022   if (Rebase)
2023     printRebaseTable(O);
2024   if (Bind)
2025     printBindTable(O);
2026   if (LazyBind)
2027     printLazyBindTable(O);
2028   if (WeakBind)
2029     printWeakBindTable(O);
2030   if (RawClangAST)
2031     printRawClangAST(O);
2032   if (PrintFaultMaps)
2033     printFaultMaps(O);
2034   if (DwarfDumpType != DIDT_Null) {
2035     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
2036     // Dump the complete DWARF structure.
2037     DIDumpOptions DumpOpts;
2038     DumpOpts.DumpType = DwarfDumpType;
2039     DICtx->dump(outs(), DumpOpts);
2040   }
2041 }
2042
2043 static void dumpObject(const COFFImportFile *I, const Archive *A,
2044                        const Archive::Child *C = nullptr) {
2045   StringRef ArchiveName = A ? A->getFileName() : "";
2046
2047   // Avoid other output when using a raw option.
2048   if (!RawClangAST)
2049     outs() << '\n'
2050            << ArchiveName << "(" << I->getFileName() << ")"
2051            << ":\tfile format COFF-import-file"
2052            << "\n\n";
2053
2054   if (ArchiveHeaders && !MachOOpt && C)
2055     printArchiveChild(ArchiveName, *C);
2056   if (SymbolTable)
2057     printCOFFSymbolTable(I);
2058 }
2059
2060 /// Dump each object file in \a a;
2061 static void dumpArchive(const Archive *A) {
2062   Error Err = Error::success();
2063   for (auto &C : A->children(Err)) {
2064     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2065     if (!ChildOrErr) {
2066       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2067         report_error(A->getFileName(), C, std::move(E));
2068       continue;
2069     }
2070     if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2071       dumpObject(O, A, &C);
2072     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2073       dumpObject(I, A, &C);
2074     else
2075       report_error(A->getFileName(), object_error::invalid_file_type);
2076   }
2077   if (Err)
2078     report_error(A->getFileName(), std::move(Err));
2079 }
2080
2081 /// Open file and figure out how to dump it.
2082 static void dumpInput(StringRef file) {
2083   // If we are using the Mach-O specific object file parser, then let it parse
2084   // the file and process the command line options.  So the -arch flags can
2085   // be used to select specific slices, etc.
2086   if (MachOOpt) {
2087     parseInputMachO(file);
2088     return;
2089   }
2090
2091   // Attempt to open the binary.
2092   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2093   if (!BinaryOrErr)
2094     report_error(file, BinaryOrErr.takeError());
2095   Binary &Binary = *BinaryOrErr.get().getBinary();
2096
2097   if (Archive *A = dyn_cast<Archive>(&Binary))
2098     dumpArchive(A);
2099   else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2100     dumpObject(O);
2101   else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2102     parseInputMachO(UB);
2103   else
2104     report_error(file, object_error::invalid_file_type);
2105 }
2106
2107 int main(int argc, char **argv) {
2108   InitLLVM X(argc, argv);
2109
2110   // Initialize targets and assembly printers/parsers.
2111   llvm::InitializeAllTargetInfos();
2112   llvm::InitializeAllTargetMCs();
2113   llvm::InitializeAllDisassemblers();
2114
2115   // Register the target printer for --version.
2116   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2117
2118   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2119
2120   ToolName = argv[0];
2121
2122   // Defaults to a.out if no filenames specified.
2123   if (InputFilenames.empty())
2124     InputFilenames.push_back("a.out");
2125
2126   if (AllHeaders)
2127     ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2128         SectionHeaders = SymbolTable = true;
2129
2130   if (DisassembleAll || PrintSource || PrintLines)
2131     Disassemble = true;
2132
2133   if (!Disassemble
2134       && !Relocations
2135       && !DynamicRelocations
2136       && !SectionHeaders
2137       && !SectionContents
2138       && !SymbolTable
2139       && !UnwindInfo
2140       && !PrivateHeaders
2141       && !FileHeaders
2142       && !FirstPrivateHeader
2143       && !ExportsTrie
2144       && !Rebase
2145       && !Bind
2146       && !LazyBind
2147       && !WeakBind
2148       && !RawClangAST
2149       && !(UniversalHeaders && MachOOpt)
2150       && !ArchiveHeaders
2151       && !(IndirectSymbols && MachOOpt)
2152       && !(DataInCode && MachOOpt)
2153       && !(LinkOptHints && MachOOpt)
2154       && !(InfoPlist && MachOOpt)
2155       && !(DylibsUsed && MachOOpt)
2156       && !(DylibId && MachOOpt)
2157       && !(ObjcMetaData && MachOOpt)
2158       && !(!FilterSections.empty() && MachOOpt)
2159       && !PrintFaultMaps
2160       && DwarfDumpType == DIDT_Null) {
2161     cl::PrintHelpMessage();
2162     return 2;
2163   }
2164
2165   DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2166                         DisassembleFunctions.end());
2167
2168   llvm::for_each(InputFilenames, dumpInput);
2169
2170   return EXIT_SUCCESS;
2171 }