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