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