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