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