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