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