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