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