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