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