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