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