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