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