OSDN Git Service

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