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