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