llvm-objdump: Replace the -macho -raw option with a generic -raw-clang-ast
[oota-llvm.git] / tools / llvm-objdump / llvm-objdump.cpp
1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
12 // flags.
13 //
14 // The flags and output of this program should be near identical to those of
15 // binutils objdump.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm-objdump.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/FaultMaps.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrAnalysis.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCObjectFileInfo.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCRelocationInfo.h"
35 #include "llvm/MC/MCSubtargetInfo.h"
36 #include "llvm/Object/Archive.h"
37 #include "llvm/Object/ELFObjectFile.h"
38 #include "llvm/Object/COFF.h"
39 #include "llvm/Object/MachO.h"
40 #include "llvm/Object/ObjectFile.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/Errc.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/GraphWriter.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/ManagedStatic.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/PrettyStackTrace.h"
52 #include "llvm/Support/Signals.h"
53 #include "llvm/Support/SourceMgr.h"
54 #include "llvm/Support/TargetRegistry.h"
55 #include "llvm/Support/TargetSelect.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <algorithm>
58 #include <cctype>
59 #include <cstring>
60 #include <system_error>
61
62 using namespace llvm;
63 using namespace object;
64
65 static cl::list<std::string>
66 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
67
68 cl::opt<bool>
69 llvm::Disassemble("disassemble",
70   cl::desc("Display assembler mnemonics for the machine instructions"));
71 static cl::alias
72 Disassembled("d", cl::desc("Alias for --disassemble"),
73              cl::aliasopt(Disassemble));
74
75 cl::opt<bool>
76 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
77
78 cl::opt<bool>
79 llvm::SectionContents("s", cl::desc("Display the content of each section"));
80
81 cl::opt<bool>
82 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
83
84 cl::opt<bool>
85 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
86
87 cl::opt<bool>
88 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
89
90 cl::opt<bool>
91 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
92
93 cl::opt<bool>
94 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
95
96 cl::opt<bool>
97 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
98
99 cl::opt<bool>
100 llvm::RawClangAST("raw-clang-ast",
101     cl::desc("Dump the raw binary contents of the clang AST section"));
102
103 static cl::opt<bool>
104 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
105 static cl::alias
106 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
107
108 cl::opt<std::string>
109 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
110                                     "see -version for available targets"));
111
112 cl::opt<std::string>
113 llvm::MCPU("mcpu",
114      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
115      cl::value_desc("cpu-name"),
116      cl::init(""));
117
118 cl::opt<std::string>
119 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
120                                 "see -version for available targets"));
121
122 cl::opt<bool>
123 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
124                                                  "headers for each section."));
125 static cl::alias
126 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
127                     cl::aliasopt(SectionHeaders));
128 static cl::alias
129 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
130                       cl::aliasopt(SectionHeaders));
131
132 cl::list<std::string>
133 llvm::MAttrs("mattr",
134   cl::CommaSeparated,
135   cl::desc("Target specific attributes"),
136   cl::value_desc("a1,+a2,-a3,..."));
137
138 cl::opt<bool>
139 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
140                                                  "instructions, do not print "
141                                                  "the instruction bytes."));
142
143 cl::opt<bool>
144 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
145
146 static cl::alias
147 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
148                 cl::aliasopt(UnwindInfo));
149
150 cl::opt<bool>
151 llvm::PrivateHeaders("private-headers",
152                      cl::desc("Display format specific file headers"));
153
154 static cl::alias
155 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
156                     cl::aliasopt(PrivateHeaders));
157
158 cl::opt<bool>
159     llvm::PrintImmHex("print-imm-hex",
160                       cl::desc("Use hex format for immediate values"));
161
162 cl::opt<bool> PrintFaultMaps("fault-map-section",
163                              cl::desc("Display contents of faultmap section"));
164
165 static StringRef ToolName;
166 static int ReturnValue = EXIT_SUCCESS;
167
168 bool llvm::error(std::error_code EC) {
169   if (!EC)
170     return false;
171
172   outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
173   outs().flush();
174   ReturnValue = EXIT_FAILURE;
175   return true;
176 }
177
178 static void report_error(StringRef File, std::error_code EC) {
179   assert(EC);
180   errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
181   ReturnValue = EXIT_FAILURE;
182 }
183
184 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
185   // Figure out the target triple.
186   llvm::Triple TheTriple("unknown-unknown-unknown");
187   if (TripleName.empty()) {
188     if (Obj) {
189       TheTriple.setArch(Triple::ArchType(Obj->getArch()));
190       // TheTriple defaults to ELF, and COFF doesn't have an environment:
191       // the best we can do here is indicate that it is mach-o.
192       if (Obj->isMachO())
193         TheTriple.setObjectFormat(Triple::MachO);
194
195       if (Obj->isCOFF()) {
196         const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
197         if (COFFObj->getArch() == Triple::thumb)
198           TheTriple.setTriple("thumbv7-windows");
199       }
200     }
201   } else
202     TheTriple.setTriple(Triple::normalize(TripleName));
203
204   // Get the target specific parser.
205   std::string Error;
206   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
207                                                          Error);
208   if (!TheTarget) {
209     errs() << ToolName << ": " << Error;
210     return nullptr;
211   }
212
213   // Update the triple name and return the found target.
214   TripleName = TheTriple.getTriple();
215   return TheTarget;
216 }
217
218 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
219   return a.getOffset() < b.getOffset();
220 }
221
222 namespace {
223 class PrettyPrinter {
224 public:
225   virtual ~PrettyPrinter(){}
226   virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
227                          ArrayRef<uint8_t> Bytes, uint64_t Address,
228                          raw_ostream &OS, StringRef Annot,
229                          MCSubtargetInfo const &STI) {
230     outs() << format("%8" PRIx64 ":", Address);
231     if (!NoShowRawInsn) {
232       outs() << "\t";
233       dumpBytes(Bytes, outs());
234     }
235     IP.printInst(MI, outs(), "", STI);
236   }
237 };
238 PrettyPrinter PrettyPrinterInst;
239 class HexagonPrettyPrinter : public PrettyPrinter {
240 public:
241   void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
242                  raw_ostream &OS) {
243     uint32_t opcode =
244       (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
245     OS << format("%8" PRIx64 ":", Address);
246     if (!NoShowRawInsn) {
247       OS << "\t";
248       dumpBytes(Bytes.slice(0, 4), OS);
249       OS << format("%08" PRIx32, opcode);
250     }
251   }
252   void printInst(MCInstPrinter &IP, const MCInst *MI,
253                  ArrayRef<uint8_t> Bytes, uint64_t Address,
254                  raw_ostream &OS, StringRef Annot,
255                  MCSubtargetInfo const &STI) override {
256     std::string Buffer;
257     {
258       raw_string_ostream TempStream(Buffer);
259       IP.printInst(MI, TempStream, "", STI);
260     }
261     StringRef Contents(Buffer);
262     // Split off bundle attributes
263     auto PacketBundle = Contents.rsplit('\n');
264     // Split off first instruction from the rest
265     auto HeadTail = PacketBundle.first.split('\n');
266     auto Preamble = " { ";
267     auto Separator = "";
268     while(!HeadTail.first.empty()) {
269       OS << Separator;
270       Separator = "\n";
271       printLead(Bytes, Address, OS);
272       OS << Preamble;
273       Preamble = "   ";
274       StringRef Inst;
275       auto Duplex = HeadTail.first.split('\v');
276       if(!Duplex.second.empty()){
277         OS << Duplex.first;
278         OS << "; ";
279         Inst = Duplex.second;
280       }
281       else
282         Inst = HeadTail.first;
283       OS << Inst;
284       Bytes = Bytes.slice(4);
285       Address += 4;
286       HeadTail = HeadTail.second.split('\n');
287     }
288     OS << " } " << PacketBundle.second;
289   }
290 };
291 HexagonPrettyPrinter HexagonPrettyPrinterInst;
292 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
293   switch(Triple.getArch()) {
294   default:
295     return PrettyPrinterInst;
296   case Triple::hexagon:
297     return HexagonPrettyPrinterInst;
298   }
299 }
300 }
301
302 template <class ELFT>
303 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
304                                                 DataRefImpl Rel,
305                                                 SmallVectorImpl<char> &Result) {
306   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
307   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
308   typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
309   typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
310
311   const ELFFile<ELFT> &EF = *Obj->getELFFile();
312
313   ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
314   if (std::error_code EC = SecOrErr.getError())
315     return EC;
316   const Elf_Shdr *Sec = *SecOrErr;
317   ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
318   if (std::error_code EC = SymTabOrErr.getError())
319     return EC;
320   const Elf_Shdr *SymTab = *SymTabOrErr;
321   assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
322          SymTab->sh_type == ELF::SHT_DYNSYM);
323   ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
324   if (std::error_code EC = StrTabSec.getError())
325     return EC;
326   ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
327   if (std::error_code EC = StrTabOrErr.getError())
328     return EC;
329   StringRef StrTab = *StrTabOrErr;
330   uint8_t type;
331   StringRef res;
332   int64_t addend = 0;
333   uint16_t symbol_index = 0;
334   switch (Sec->sh_type) {
335   default:
336     return object_error::parse_failed;
337   case ELF::SHT_REL: {
338     const Elf_Rel *ERel = Obj->getRel(Rel);
339     type = ERel->getType(EF.isMips64EL());
340     symbol_index = ERel->getSymbol(EF.isMips64EL());
341     // TODO: Read implicit addend from section data.
342     break;
343   }
344   case ELF::SHT_RELA: {
345     const Elf_Rela *ERela = Obj->getRela(Rel);
346     type = ERela->getType(EF.isMips64EL());
347     symbol_index = ERela->getSymbol(EF.isMips64EL());
348     addend = ERela->r_addend;
349     break;
350   }
351   }
352   const Elf_Sym *symb =
353       EF.template getEntry<Elf_Sym>(Sec->sh_link, symbol_index);
354   StringRef Target;
355   ErrorOr<const Elf_Shdr *> SymSec = EF.getSection(symb);
356   if (std::error_code EC = SymSec.getError())
357     return EC;
358   if (symb->getType() == ELF::STT_SECTION) {
359     ErrorOr<StringRef> SecName = EF.getSectionName(*SymSec);
360     if (std::error_code EC = SecName.getError())
361       return EC;
362     Target = *SecName;
363   } else {
364     ErrorOr<StringRef> SymName = symb->getName(StrTab);
365     if (!SymName)
366       return SymName.getError();
367     Target = *SymName;
368   }
369   switch (EF.getHeader()->e_machine) {
370   case ELF::EM_X86_64:
371     switch (type) {
372     case ELF::R_X86_64_PC8:
373     case ELF::R_X86_64_PC16:
374     case ELF::R_X86_64_PC32: {
375       std::string fmtbuf;
376       raw_string_ostream fmt(fmtbuf);
377       fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
378       fmt.flush();
379       Result.append(fmtbuf.begin(), fmtbuf.end());
380     } break;
381     case ELF::R_X86_64_8:
382     case ELF::R_X86_64_16:
383     case ELF::R_X86_64_32:
384     case ELF::R_X86_64_32S:
385     case ELF::R_X86_64_64: {
386       std::string fmtbuf;
387       raw_string_ostream fmt(fmtbuf);
388       fmt << Target << (addend < 0 ? "" : "+") << addend;
389       fmt.flush();
390       Result.append(fmtbuf.begin(), fmtbuf.end());
391     } break;
392     default:
393       res = "Unknown";
394     }
395     break;
396   case ELF::EM_AARCH64: {
397     std::string fmtbuf;
398     raw_string_ostream fmt(fmtbuf);
399     fmt << Target;
400     if (addend != 0)
401       fmt << (addend < 0 ? "" : "+") << addend;
402     fmt.flush();
403     Result.append(fmtbuf.begin(), fmtbuf.end());
404     break;
405   }
406   case ELF::EM_386:
407   case ELF::EM_ARM:
408   case ELF::EM_HEXAGON:
409   case ELF::EM_MIPS:
410     res = Target;
411     break;
412   default:
413     res = "Unknown";
414   }
415   if (Result.empty())
416     Result.append(res.begin(), res.end());
417   return std::error_code();
418 }
419
420 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
421                                                 const RelocationRef &RelRef,
422                                                 SmallVectorImpl<char> &Result) {
423   DataRefImpl Rel = RelRef.getRawDataRefImpl();
424   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
425     return getRelocationValueString(ELF32LE, Rel, Result);
426   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
427     return getRelocationValueString(ELF64LE, Rel, Result);
428   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
429     return getRelocationValueString(ELF32BE, Rel, Result);
430   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
431   return getRelocationValueString(ELF64BE, Rel, Result);
432 }
433
434 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
435                                                 const RelocationRef &Rel,
436                                                 SmallVectorImpl<char> &Result) {
437   symbol_iterator SymI = Rel.getSymbol();
438   ErrorOr<StringRef> SymNameOrErr = SymI->getName();
439   if (std::error_code EC = SymNameOrErr.getError())
440     return EC;
441   StringRef SymName = *SymNameOrErr;
442   Result.append(SymName.begin(), SymName.end());
443   return std::error_code();
444 }
445
446 static void printRelocationTargetName(const MachOObjectFile *O,
447                                       const MachO::any_relocation_info &RE,
448                                       raw_string_ostream &fmt) {
449   bool IsScattered = O->isRelocationScattered(RE);
450
451   // Target of a scattered relocation is an address.  In the interest of
452   // generating pretty output, scan through the symbol table looking for a
453   // symbol that aligns with that address.  If we find one, print it.
454   // Otherwise, we just print the hex address of the target.
455   if (IsScattered) {
456     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
457
458     for (const SymbolRef &Symbol : O->symbols()) {
459       std::error_code ec;
460       ErrorOr<uint64_t> Addr = Symbol.getAddress();
461       if ((ec = Addr.getError()))
462         report_fatal_error(ec.message());
463       if (*Addr != Val)
464         continue;
465       ErrorOr<StringRef> Name = Symbol.getName();
466       if (std::error_code EC = Name.getError())
467         report_fatal_error(EC.message());
468       fmt << *Name;
469       return;
470     }
471
472     // If we couldn't find a symbol that this relocation refers to, try
473     // to find a section beginning instead.
474     for (const SectionRef &Section : O->sections()) {
475       std::error_code ec;
476
477       StringRef Name;
478       uint64_t Addr = Section.getAddress();
479       if (Addr != Val)
480         continue;
481       if ((ec = Section.getName(Name)))
482         report_fatal_error(ec.message());
483       fmt << Name;
484       return;
485     }
486
487     fmt << format("0x%x", Val);
488     return;
489   }
490
491   StringRef S;
492   bool isExtern = O->getPlainRelocationExternal(RE);
493   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
494
495   if (isExtern) {
496     symbol_iterator SI = O->symbol_begin();
497     advance(SI, Val);
498     ErrorOr<StringRef> SOrErr = SI->getName();
499     if (!error(SOrErr.getError()))
500       S = *SOrErr;
501   } else {
502     section_iterator SI = O->section_begin();
503     // Adjust for the fact that sections are 1-indexed.
504     advance(SI, Val - 1);
505     SI->getName(S);
506   }
507
508   fmt << S;
509 }
510
511 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
512                                                 const RelocationRef &RelRef,
513                                                 SmallVectorImpl<char> &Result) {
514   DataRefImpl Rel = RelRef.getRawDataRefImpl();
515   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
516
517   unsigned Arch = Obj->getArch();
518
519   std::string fmtbuf;
520   raw_string_ostream fmt(fmtbuf);
521   unsigned Type = Obj->getAnyRelocationType(RE);
522   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
523
524   // Determine any addends that should be displayed with the relocation.
525   // These require decoding the relocation type, which is triple-specific.
526
527   // X86_64 has entirely custom relocation types.
528   if (Arch == Triple::x86_64) {
529     bool isPCRel = Obj->getAnyRelocationPCRel(RE);
530
531     switch (Type) {
532     case MachO::X86_64_RELOC_GOT_LOAD:
533     case MachO::X86_64_RELOC_GOT: {
534       printRelocationTargetName(Obj, RE, fmt);
535       fmt << "@GOT";
536       if (isPCRel)
537         fmt << "PCREL";
538       break;
539     }
540     case MachO::X86_64_RELOC_SUBTRACTOR: {
541       DataRefImpl RelNext = Rel;
542       Obj->moveRelocationNext(RelNext);
543       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
544
545       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
546       // X86_64_RELOC_UNSIGNED.
547       // NOTE: Scattered relocations don't exist on x86_64.
548       unsigned RType = Obj->getAnyRelocationType(RENext);
549       if (RType != MachO::X86_64_RELOC_UNSIGNED)
550         report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
551                            "X86_64_RELOC_SUBTRACTOR.");
552
553       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
554       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
555       printRelocationTargetName(Obj, RENext, fmt);
556       fmt << "-";
557       printRelocationTargetName(Obj, RE, fmt);
558       break;
559     }
560     case MachO::X86_64_RELOC_TLV:
561       printRelocationTargetName(Obj, RE, fmt);
562       fmt << "@TLV";
563       if (isPCRel)
564         fmt << "P";
565       break;
566     case MachO::X86_64_RELOC_SIGNED_1:
567       printRelocationTargetName(Obj, RE, fmt);
568       fmt << "-1";
569       break;
570     case MachO::X86_64_RELOC_SIGNED_2:
571       printRelocationTargetName(Obj, RE, fmt);
572       fmt << "-2";
573       break;
574     case MachO::X86_64_RELOC_SIGNED_4:
575       printRelocationTargetName(Obj, RE, fmt);
576       fmt << "-4";
577       break;
578     default:
579       printRelocationTargetName(Obj, RE, fmt);
580       break;
581     }
582     // X86 and ARM share some relocation types in common.
583   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
584              Arch == Triple::ppc) {
585     // Generic relocation types...
586     switch (Type) {
587     case MachO::GENERIC_RELOC_PAIR: // prints no info
588       return std::error_code();
589     case MachO::GENERIC_RELOC_SECTDIFF: {
590       DataRefImpl RelNext = Rel;
591       Obj->moveRelocationNext(RelNext);
592       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
593
594       // X86 sect diff's must be followed by a relocation of type
595       // GENERIC_RELOC_PAIR.
596       unsigned RType = Obj->getAnyRelocationType(RENext);
597
598       if (RType != MachO::GENERIC_RELOC_PAIR)
599         report_fatal_error("Expected GENERIC_RELOC_PAIR after "
600                            "GENERIC_RELOC_SECTDIFF.");
601
602       printRelocationTargetName(Obj, RE, fmt);
603       fmt << "-";
604       printRelocationTargetName(Obj, RENext, fmt);
605       break;
606     }
607     }
608
609     if (Arch == Triple::x86 || Arch == Triple::ppc) {
610       switch (Type) {
611       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
612         DataRefImpl RelNext = Rel;
613         Obj->moveRelocationNext(RelNext);
614         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
615
616         // X86 sect diff's must be followed by a relocation of type
617         // GENERIC_RELOC_PAIR.
618         unsigned RType = Obj->getAnyRelocationType(RENext);
619         if (RType != MachO::GENERIC_RELOC_PAIR)
620           report_fatal_error("Expected GENERIC_RELOC_PAIR after "
621                              "GENERIC_RELOC_LOCAL_SECTDIFF.");
622
623         printRelocationTargetName(Obj, RE, fmt);
624         fmt << "-";
625         printRelocationTargetName(Obj, RENext, fmt);
626         break;
627       }
628       case MachO::GENERIC_RELOC_TLV: {
629         printRelocationTargetName(Obj, RE, fmt);
630         fmt << "@TLV";
631         if (IsPCRel)
632           fmt << "P";
633         break;
634       }
635       default:
636         printRelocationTargetName(Obj, RE, fmt);
637       }
638     } else { // ARM-specific relocations
639       switch (Type) {
640       case MachO::ARM_RELOC_HALF:
641       case MachO::ARM_RELOC_HALF_SECTDIFF: {
642         // Half relocations steal a bit from the length field to encode
643         // whether this is an upper16 or a lower16 relocation.
644         bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
645
646         if (isUpper)
647           fmt << ":upper16:(";
648         else
649           fmt << ":lower16:(";
650         printRelocationTargetName(Obj, RE, fmt);
651
652         DataRefImpl RelNext = Rel;
653         Obj->moveRelocationNext(RelNext);
654         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
655
656         // ARM half relocs must be followed by a relocation of type
657         // ARM_RELOC_PAIR.
658         unsigned RType = Obj->getAnyRelocationType(RENext);
659         if (RType != MachO::ARM_RELOC_PAIR)
660           report_fatal_error("Expected ARM_RELOC_PAIR after "
661                              "ARM_RELOC_HALF");
662
663         // NOTE: The half of the target virtual address is stashed in the
664         // address field of the secondary relocation, but we can't reverse
665         // engineer the constant offset from it without decoding the movw/movt
666         // instruction to find the other half in its immediate field.
667
668         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
669         // symbol/section pointer of the follow-on relocation.
670         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
671           fmt << "-";
672           printRelocationTargetName(Obj, RENext, fmt);
673         }
674
675         fmt << ")";
676         break;
677       }
678       default: { printRelocationTargetName(Obj, RE, fmt); }
679       }
680     }
681   } else
682     printRelocationTargetName(Obj, RE, fmt);
683
684   fmt.flush();
685   Result.append(fmtbuf.begin(), fmtbuf.end());
686   return std::error_code();
687 }
688
689 static std::error_code getRelocationValueString(const RelocationRef &Rel,
690                                                 SmallVectorImpl<char> &Result) {
691   const ObjectFile *Obj = Rel.getObject();
692   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
693     return getRelocationValueString(ELF, Rel, Result);
694   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
695     return getRelocationValueString(COFF, Rel, Result);
696   auto *MachO = cast<MachOObjectFile>(Obj);
697   return getRelocationValueString(MachO, Rel, Result);
698 }
699
700 /// @brief Indicates whether this relocation should hidden when listing
701 /// relocations, usually because it is the trailing part of a multipart
702 /// relocation that will be printed as part of the leading relocation.
703 static bool getHidden(RelocationRef RelRef) {
704   const ObjectFile *Obj = RelRef.getObject();
705   auto *MachO = dyn_cast<MachOObjectFile>(Obj);
706   if (!MachO)
707     return false;
708
709   unsigned Arch = MachO->getArch();
710   DataRefImpl Rel = RelRef.getRawDataRefImpl();
711   uint64_t Type = MachO->getRelocationType(Rel);
712
713   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
714   // is always hidden.
715   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
716     if (Type == MachO::GENERIC_RELOC_PAIR)
717       return true;
718   } else if (Arch == Triple::x86_64) {
719     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
720     // an X86_64_RELOC_SUBTRACTOR.
721     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
722       DataRefImpl RelPrev = Rel;
723       RelPrev.d.a--;
724       uint64_t PrevType = MachO->getRelocationType(RelPrev);
725       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
726         return true;
727     }
728   }
729
730   return false;
731 }
732
733 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
734   const Target *TheTarget = getTarget(Obj);
735   // getTarget() will have already issued a diagnostic if necessary, so
736   // just bail here if it failed.
737   if (!TheTarget)
738     return;
739
740   // Package up features to be passed to target/subtarget
741   std::string FeaturesStr;
742   if (MAttrs.size()) {
743     SubtargetFeatures Features;
744     for (unsigned i = 0; i != MAttrs.size(); ++i)
745       Features.AddFeature(MAttrs[i]);
746     FeaturesStr = Features.getString();
747   }
748
749   std::unique_ptr<const MCRegisterInfo> MRI(
750       TheTarget->createMCRegInfo(TripleName));
751   if (!MRI) {
752     errs() << "error: no register info for target " << TripleName << "\n";
753     return;
754   }
755
756   // Set up disassembler.
757   std::unique_ptr<const MCAsmInfo> AsmInfo(
758       TheTarget->createMCAsmInfo(*MRI, TripleName));
759   if (!AsmInfo) {
760     errs() << "error: no assembly info for target " << TripleName << "\n";
761     return;
762   }
763
764   std::unique_ptr<const MCSubtargetInfo> STI(
765       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
766   if (!STI) {
767     errs() << "error: no subtarget info for target " << TripleName << "\n";
768     return;
769   }
770
771   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
772   if (!MII) {
773     errs() << "error: no instruction info for target " << TripleName << "\n";
774     return;
775   }
776
777   std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
778   MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
779
780   std::unique_ptr<MCDisassembler> DisAsm(
781     TheTarget->createMCDisassembler(*STI, Ctx));
782
783   if (!DisAsm) {
784     errs() << "error: no disassembler for target " << TripleName << "\n";
785     return;
786   }
787
788   std::unique_ptr<const MCInstrAnalysis> MIA(
789       TheTarget->createMCInstrAnalysis(MII.get()));
790
791   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
792   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
793       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
794   if (!IP) {
795     errs() << "error: no instruction printer for target " << TripleName
796       << '\n';
797     return;
798   }
799   IP->setPrintImmHex(PrintImmHex);
800   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
801
802   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
803                                                  "\t\t\t%08" PRIx64 ":  ";
804
805   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
806   // in RelocSecs contain the relocations for section S.
807   std::error_code EC;
808   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
809   for (const SectionRef &Section : Obj->sections()) {
810     section_iterator Sec2 = Section.getRelocatedSection();
811     if (Sec2 != Obj->section_end())
812       SectionRelocMap[*Sec2].push_back(Section);
813   }
814
815   // Create a mapping from virtual address to symbol name.  This is used to
816   // pretty print the target of a call.
817   std::vector<std::pair<uint64_t, StringRef>> AllSymbols;
818   if (MIA) {
819     for (const SymbolRef &Symbol : Obj->symbols()) {
820       ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
821       if (error(AddressOrErr.getError()))
822         break;
823       uint64_t Address = *AddressOrErr;
824
825       ErrorOr<StringRef> Name = Symbol.getName();
826       if (error(Name.getError()))
827         break;
828       if (Name->empty())
829         continue;
830       AllSymbols.push_back(std::make_pair(Address, *Name));
831     }
832
833     array_pod_sort(AllSymbols.begin(), AllSymbols.end());
834   }
835
836   for (const SectionRef &Section : Obj->sections()) {
837     if (!Section.isText() || Section.isVirtual())
838       continue;
839
840     uint64_t SectionAddr = Section.getAddress();
841     uint64_t SectSize = Section.getSize();
842     if (!SectSize)
843       continue;
844
845     // Make a list of all the symbols in this section.
846     std::vector<std::pair<uint64_t, StringRef>> Symbols;
847     for (const SymbolRef &Symbol : Obj->symbols()) {
848       if (Section.containsSymbol(Symbol)) {
849         ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
850         if (error(AddressOrErr.getError()))
851           break;
852         uint64_t Address = *AddressOrErr;
853         Address -= SectionAddr;
854         if (Address >= SectSize)
855           continue;
856
857         ErrorOr<StringRef> Name = Symbol.getName();
858         if (error(Name.getError()))
859           break;
860         Symbols.push_back(std::make_pair(Address, *Name));
861       }
862     }
863
864     // Sort the symbols by address, just in case they didn't come in that way.
865     array_pod_sort(Symbols.begin(), Symbols.end());
866
867     // Make a list of all the relocations for this section.
868     std::vector<RelocationRef> Rels;
869     if (InlineRelocs) {
870       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
871         for (const RelocationRef &Reloc : RelocSec.relocations()) {
872           Rels.push_back(Reloc);
873         }
874       }
875     }
876
877     // Sort relocations by address.
878     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
879
880     StringRef SegmentName = "";
881     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
882       DataRefImpl DR = Section.getRawDataRefImpl();
883       SegmentName = MachO->getSectionFinalSegmentName(DR);
884     }
885     StringRef name;
886     if (error(Section.getName(name)))
887       break;
888     outs() << "Disassembly of section ";
889     if (!SegmentName.empty())
890       outs() << SegmentName << ",";
891     outs() << name << ':';
892
893     // If the section has no symbol at the start, just insert a dummy one.
894     if (Symbols.empty() || Symbols[0].first != 0)
895       Symbols.insert(Symbols.begin(), std::make_pair(0, name));
896
897     SmallString<40> Comments;
898     raw_svector_ostream CommentStream(Comments);
899
900     StringRef BytesStr;
901     if (error(Section.getContents(BytesStr)))
902       break;
903     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
904                             BytesStr.size());
905
906     uint64_t Size;
907     uint64_t Index;
908
909     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
910     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
911     // Disassemble symbol by symbol.
912     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
913
914       uint64_t Start = Symbols[si].first;
915       // The end is either the section end or the beginning of the next symbol.
916       uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
917       // If this symbol has the same address as the next symbol, then skip it.
918       if (Start == End)
919         continue;
920
921       outs() << '\n' << Symbols[si].second << ":\n";
922
923 #ifndef NDEBUG
924       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
925 #else
926       raw_ostream &DebugOut = nulls();
927 #endif
928
929       for (Index = Start; Index < End; Index += Size) {
930         MCInst Inst;
931
932         if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
933                                    SectionAddr + Index, DebugOut,
934                                    CommentStream)) {
935           PIP.printInst(*IP, &Inst,
936                         Bytes.slice(Index, Size),
937                         SectionAddr + Index, outs(), "", *STI);
938           outs() << CommentStream.str();
939           Comments.clear();
940           if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst))) {
941             uint64_t Target;
942             if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
943               const auto &TargetSym =
944                   std::lower_bound(AllSymbols.begin(), AllSymbols.end(),
945                                    std::make_pair(Target, StringRef()));
946               if (TargetSym != AllSymbols.end()) {
947                 outs() << " <" << TargetSym->second;
948                 uint64_t Disp = TargetSym->first - Target;
949                 if (Disp)
950                   outs() << '-' << Disp;
951                 outs() << '>';
952               }
953             }
954           }
955           outs() << "\n";
956         } else {
957           errs() << ToolName << ": warning: invalid instruction encoding\n";
958           if (Size == 0)
959             Size = 1; // skip illegible bytes
960         }
961
962         // Print relocation for instruction.
963         while (rel_cur != rel_end) {
964           bool hidden = getHidden(*rel_cur);
965           uint64_t addr = rel_cur->getOffset();
966           SmallString<16> name;
967           SmallString<32> val;
968
969           // If this relocation is hidden, skip it.
970           if (hidden) goto skip_print_rel;
971
972           // Stop when rel_cur's address is past the current instruction.
973           if (addr >= Index + Size) break;
974           rel_cur->getTypeName(name);
975           if (error(getRelocationValueString(*rel_cur, val)))
976             goto skip_print_rel;
977           outs() << format(Fmt.data(), SectionAddr + addr) << name
978                  << "\t" << val << "\n";
979
980         skip_print_rel:
981           ++rel_cur;
982         }
983       }
984     }
985   }
986 }
987
988 void llvm::PrintRelocations(const ObjectFile *Obj) {
989   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
990                                                  "%08" PRIx64;
991   // Regular objdump doesn't print relocations in non-relocatable object
992   // files.
993   if (!Obj->isRelocatableObject())
994     return;
995
996   for (const SectionRef &Section : Obj->sections()) {
997     if (Section.relocation_begin() == Section.relocation_end())
998       continue;
999     StringRef secname;
1000     if (error(Section.getName(secname)))
1001       continue;
1002     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1003     for (const RelocationRef &Reloc : Section.relocations()) {
1004       bool hidden = getHidden(Reloc);
1005       uint64_t address = Reloc.getOffset();
1006       SmallString<32> relocname;
1007       SmallString<32> valuestr;
1008       if (hidden)
1009         continue;
1010       Reloc.getTypeName(relocname);
1011       if (error(getRelocationValueString(Reloc, valuestr)))
1012         continue;
1013       outs() << format(Fmt.data(), address) << " " << relocname << " "
1014              << valuestr << "\n";
1015     }
1016     outs() << "\n";
1017   }
1018 }
1019
1020 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1021   outs() << "Sections:\n"
1022             "Idx Name          Size      Address          Type\n";
1023   unsigned i = 0;
1024   for (const SectionRef &Section : Obj->sections()) {
1025     StringRef Name;
1026     if (error(Section.getName(Name)))
1027       return;
1028     uint64_t Address = Section.getAddress();
1029     uint64_t Size = Section.getSize();
1030     bool Text = Section.isText();
1031     bool Data = Section.isData();
1032     bool BSS = Section.isBSS();
1033     std::string Type = (std::string(Text ? "TEXT " : "") +
1034                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1035     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1036                      Name.str().c_str(), Size, Address, Type.c_str());
1037     ++i;
1038   }
1039 }
1040
1041 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1042   std::error_code EC;
1043   for (const SectionRef &Section : Obj->sections()) {
1044     StringRef Name;
1045     StringRef Contents;
1046     if (error(Section.getName(Name)))
1047       continue;
1048     uint64_t BaseAddr = Section.getAddress();
1049     uint64_t Size = Section.getSize();
1050     if (!Size)
1051       continue;
1052
1053     outs() << "Contents of section " << Name << ":\n";
1054     if (Section.isBSS()) {
1055       outs() << format("<skipping contents of bss section at [%04" PRIx64
1056                        ", %04" PRIx64 ")>\n",
1057                        BaseAddr, BaseAddr + Size);
1058       continue;
1059     }
1060
1061     if (error(Section.getContents(Contents)))
1062       continue;
1063
1064     // Dump out the content as hex and printable ascii characters.
1065     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1066       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1067       // Dump line of hex.
1068       for (std::size_t i = 0; i < 16; ++i) {
1069         if (i != 0 && i % 4 == 0)
1070           outs() << ' ';
1071         if (addr + i < end)
1072           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1073                  << hexdigit(Contents[addr + i] & 0xF, true);
1074         else
1075           outs() << "  ";
1076       }
1077       // Print ascii.
1078       outs() << "  ";
1079       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1080         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1081           outs() << Contents[addr + i];
1082         else
1083           outs() << ".";
1084       }
1085       outs() << "\n";
1086     }
1087   }
1088 }
1089
1090 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
1091   for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1092     ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
1093     StringRef Name;
1094     if (error(Symbol.getError()))
1095       return;
1096
1097     if (error(coff->getSymbolName(*Symbol, Name)))
1098       return;
1099
1100     outs() << "[" << format("%2d", SI) << "]"
1101            << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
1102            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
1103            << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1104            << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1105            << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1106            << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
1107            << Name << "\n";
1108
1109     for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
1110       if (Symbol->isSectionDefinition()) {
1111         const coff_aux_section_definition *asd;
1112         if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
1113           return;
1114
1115         int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1116
1117         outs() << "AUX "
1118                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1119                          , unsigned(asd->Length)
1120                          , unsigned(asd->NumberOfRelocations)
1121                          , unsigned(asd->NumberOfLinenumbers)
1122                          , unsigned(asd->CheckSum))
1123                << format("assoc %d comdat %d\n"
1124                          , unsigned(AuxNumber)
1125                          , unsigned(asd->Selection));
1126       } else if (Symbol->isFileRecord()) {
1127         const char *FileName;
1128         if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
1129           return;
1130
1131         StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1132                                      coff->getSymbolTableEntrySize());
1133         outs() << "AUX " << Name.rtrim(StringRef("\0", 1))  << '\n';
1134
1135         SI = SI + Symbol->getNumberOfAuxSymbols();
1136         break;
1137       } else {
1138         outs() << "AUX Unknown\n";
1139       }
1140     }
1141   }
1142 }
1143
1144 void llvm::PrintSymbolTable(const ObjectFile *o) {
1145   outs() << "SYMBOL TABLE:\n";
1146
1147   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1148     PrintCOFFSymbolTable(coff);
1149     return;
1150   }
1151   for (const SymbolRef &Symbol : o->symbols()) {
1152     ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1153     if (error(AddressOrError.getError()))
1154       continue;
1155     uint64_t Address = *AddressOrError;
1156     SymbolRef::Type Type = Symbol.getType();
1157     uint32_t Flags = Symbol.getFlags();
1158     section_iterator Section = o->section_end();
1159     if (error(Symbol.getSection(Section)))
1160       continue;
1161     StringRef Name;
1162     if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1163       Section->getName(Name);
1164     } else {
1165       ErrorOr<StringRef> NameOrErr = Symbol.getName();
1166       if (error(NameOrErr.getError()))
1167         continue;
1168       Name = *NameOrErr;
1169     }
1170
1171     bool Global = Flags & SymbolRef::SF_Global;
1172     bool Weak = Flags & SymbolRef::SF_Weak;
1173     bool Absolute = Flags & SymbolRef::SF_Absolute;
1174     bool Common = Flags & SymbolRef::SF_Common;
1175     bool Hidden = Flags & SymbolRef::SF_Hidden;
1176
1177     char GlobLoc = ' ';
1178     if (Type != SymbolRef::ST_Unknown)
1179       GlobLoc = Global ? 'g' : 'l';
1180     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1181                  ? 'd' : ' ';
1182     char FileFunc = ' ';
1183     if (Type == SymbolRef::ST_File)
1184       FileFunc = 'f';
1185     else if (Type == SymbolRef::ST_Function)
1186       FileFunc = 'F';
1187
1188     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1189                                                    "%08" PRIx64;
1190
1191     outs() << format(Fmt, Address) << " "
1192            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1193            << (Weak ? 'w' : ' ') // Weak?
1194            << ' ' // Constructor. Not supported yet.
1195            << ' ' // Warning. Not supported yet.
1196            << ' ' // Indirect reference to another symbol.
1197            << Debug // Debugging (d) or dynamic (D) symbol.
1198            << FileFunc // Name of function (F), file (f) or object (O).
1199            << ' ';
1200     if (Absolute) {
1201       outs() << "*ABS*";
1202     } else if (Common) {
1203       outs() << "*COM*";
1204     } else if (Section == o->section_end()) {
1205       outs() << "*UND*";
1206     } else {
1207       if (const MachOObjectFile *MachO =
1208           dyn_cast<const MachOObjectFile>(o)) {
1209         DataRefImpl DR = Section->getRawDataRefImpl();
1210         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1211         outs() << SegmentName << ",";
1212       }
1213       StringRef SectionName;
1214       if (error(Section->getName(SectionName)))
1215         SectionName = "";
1216       outs() << SectionName;
1217     }
1218
1219     outs() << '\t';
1220     if (Common || isa<ELFObjectFileBase>(o)) {
1221       uint64_t Val =
1222           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1223       outs() << format("\t %08" PRIx64 " ", Val);
1224     }
1225
1226     if (Hidden) {
1227       outs() << ".hidden ";
1228     }
1229     outs() << Name
1230            << '\n';
1231   }
1232 }
1233
1234 static void PrintUnwindInfo(const ObjectFile *o) {
1235   outs() << "Unwind info:\n\n";
1236
1237   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1238     printCOFFUnwindInfo(coff);
1239   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1240     printMachOUnwindInfo(MachO);
1241   else {
1242     // TODO: Extract DWARF dump tool to objdump.
1243     errs() << "This operation is only currently supported "
1244               "for COFF and MachO object files.\n";
1245     return;
1246   }
1247 }
1248
1249 void llvm::printExportsTrie(const ObjectFile *o) {
1250   outs() << "Exports trie:\n";
1251   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1252     printMachOExportsTrie(MachO);
1253   else {
1254     errs() << "This operation is only currently supported "
1255               "for Mach-O executable files.\n";
1256     return;
1257   }
1258 }
1259
1260 void llvm::printRebaseTable(const ObjectFile *o) {
1261   outs() << "Rebase table:\n";
1262   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1263     printMachORebaseTable(MachO);
1264   else {
1265     errs() << "This operation is only currently supported "
1266               "for Mach-O executable files.\n";
1267     return;
1268   }
1269 }
1270
1271 void llvm::printBindTable(const ObjectFile *o) {
1272   outs() << "Bind table:\n";
1273   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1274     printMachOBindTable(MachO);
1275   else {
1276     errs() << "This operation is only currently supported "
1277               "for Mach-O executable files.\n";
1278     return;
1279   }
1280 }
1281
1282 void llvm::printLazyBindTable(const ObjectFile *o) {
1283   outs() << "Lazy bind table:\n";
1284   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1285     printMachOLazyBindTable(MachO);
1286   else {
1287     errs() << "This operation is only currently supported "
1288               "for Mach-O executable files.\n";
1289     return;
1290   }
1291 }
1292
1293 void llvm::printWeakBindTable(const ObjectFile *o) {
1294   outs() << "Weak bind table:\n";
1295   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1296     printMachOWeakBindTable(MachO);
1297   else {
1298     errs() << "This operation is only currently supported "
1299               "for Mach-O executable files.\n";
1300     return;
1301   }
1302 }
1303
1304 /// Dump the raw contents of the __clangast section so the output can be piped
1305 /// into llvm-bcanalyzer.
1306 void llvm::printRawClangAST(const ObjectFile *Obj) {
1307   if (outs().is_displayed()) {
1308     errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1309               "the clang ast section.\n"
1310               "Please redirect the output to a file or another program such as "
1311               "llvm-bcanalyzer.\n";
1312     return;
1313   }
1314
1315   StringRef ClangASTSectionName("__clangast");
1316   if (isa<COFFObjectFile>(Obj)) {
1317     ClangASTSectionName = "clangast";
1318   }
1319
1320   Optional<object::SectionRef> ClangASTSection;
1321   for (auto Sec : Obj->sections()) {
1322     StringRef Name;
1323     Sec.getName(Name);
1324     if (Name == ClangASTSectionName) {
1325       ClangASTSection = Sec;
1326       break;
1327     }
1328   }
1329   if (!ClangASTSection)
1330     return;
1331
1332   StringRef ClangASTContents;
1333   if (error(ClangASTSection.getValue().getContents(ClangASTContents))) {
1334     errs() << "Could not read the " << ClangASTSectionName << " section!\n";
1335     return;
1336   }
1337
1338   outs().write(ClangASTContents.data(), ClangASTContents.size());
1339 }
1340
1341 static void printFaultMaps(const ObjectFile *Obj) {
1342   const char *FaultMapSectionName = nullptr;
1343
1344   if (isa<ELFObjectFileBase>(Obj)) {
1345     FaultMapSectionName = ".llvm_faultmaps";
1346   } else if (isa<MachOObjectFile>(Obj)) {
1347     FaultMapSectionName = "__llvm_faultmaps";
1348   } else {
1349     errs() << "This operation is only currently supported "
1350               "for ELF and Mach-O executable files.\n";
1351     return;
1352   }
1353
1354   Optional<object::SectionRef> FaultMapSection;
1355
1356   for (auto Sec : Obj->sections()) {
1357     StringRef Name;
1358     Sec.getName(Name);
1359     if (Name == FaultMapSectionName) {
1360       FaultMapSection = Sec;
1361       break;
1362     }
1363   }
1364
1365   outs() << "FaultMap table:\n";
1366
1367   if (!FaultMapSection.hasValue()) {
1368     outs() << "<not found>\n";
1369     return;
1370   }
1371
1372   StringRef FaultMapContents;
1373   if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1374     errs() << "Could not read the " << FaultMapContents << " section!\n";
1375     return;
1376   }
1377
1378   FaultMapParser FMP(FaultMapContents.bytes_begin(),
1379                      FaultMapContents.bytes_end());
1380
1381   outs() << FMP;
1382 }
1383
1384 static void printPrivateFileHeader(const ObjectFile *o) {
1385   if (o->isELF()) {
1386     printELFFileHeader(o);
1387   } else if (o->isCOFF()) {
1388     printCOFFFileHeader(o);
1389   } else if (o->isMachO()) {
1390     printMachOFileHeader(o);
1391   }
1392 }
1393
1394 static void DumpObject(const ObjectFile *o) {
1395   // Avoid other output when using a raw option.
1396   if (!RawClangAST) {
1397     outs() << '\n';
1398     outs() << o->getFileName()
1399            << ":\tfile format " << o->getFileFormatName() << "\n\n";
1400   }
1401
1402   if (Disassemble)
1403     DisassembleObject(o, Relocations);
1404   if (Relocations && !Disassemble)
1405     PrintRelocations(o);
1406   if (SectionHeaders)
1407     PrintSectionHeaders(o);
1408   if (SectionContents)
1409     PrintSectionContents(o);
1410   if (SymbolTable)
1411     PrintSymbolTable(o);
1412   if (UnwindInfo)
1413     PrintUnwindInfo(o);
1414   if (PrivateHeaders)
1415     printPrivateFileHeader(o);
1416   if (ExportsTrie)
1417     printExportsTrie(o);
1418   if (Rebase)
1419     printRebaseTable(o);
1420   if (Bind)
1421     printBindTable(o);
1422   if (LazyBind)
1423     printLazyBindTable(o);
1424   if (WeakBind)
1425     printWeakBindTable(o);
1426   if (RawClangAST)
1427     printRawClangAST(o);
1428   if (PrintFaultMaps)
1429     printFaultMaps(o);
1430 }
1431
1432 /// @brief Dump each object file in \a a;
1433 static void DumpArchive(const Archive *a) {
1434   for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1435        ++i) {
1436     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1437     if (std::error_code EC = ChildOrErr.getError()) {
1438       // Ignore non-object files.
1439       if (EC != object_error::invalid_file_type)
1440         report_error(a->getFileName(), EC);
1441       continue;
1442     }
1443     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1444       DumpObject(o);
1445     else
1446       report_error(a->getFileName(), object_error::invalid_file_type);
1447   }
1448 }
1449
1450 /// @brief Open file and figure out how to dump it.
1451 static void DumpInput(StringRef file) {
1452   // If file isn't stdin, check that it exists.
1453   if (file != "-" && !sys::fs::exists(file)) {
1454     report_error(file, errc::no_such_file_or_directory);
1455     return;
1456   }
1457
1458   // If we are using the Mach-O specific object file parser, then let it parse
1459   // the file and process the command line options.  So the -arch flags can
1460   // be used to select specific slices, etc.
1461   if (MachOOpt) {
1462     ParseInputMachO(file);
1463     return;
1464   }
1465
1466   // Attempt to open the binary.
1467   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1468   if (std::error_code EC = BinaryOrErr.getError()) {
1469     report_error(file, EC);
1470     return;
1471   }
1472   Binary &Binary = *BinaryOrErr.get().getBinary();
1473
1474   if (Archive *a = dyn_cast<Archive>(&Binary))
1475     DumpArchive(a);
1476   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1477     DumpObject(o);
1478   else
1479     report_error(file, object_error::invalid_file_type);
1480 }
1481
1482 int main(int argc, char **argv) {
1483   // Print a stack trace if we signal out.
1484   sys::PrintStackTraceOnErrorSignal();
1485   PrettyStackTraceProgram X(argc, argv);
1486   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
1487
1488   // Initialize targets and assembly printers/parsers.
1489   llvm::InitializeAllTargetInfos();
1490   llvm::InitializeAllTargetMCs();
1491   llvm::InitializeAllAsmParsers();
1492   llvm::InitializeAllDisassemblers();
1493
1494   // Register the target printer for --version.
1495   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1496
1497   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1498   TripleName = Triple::normalize(TripleName);
1499
1500   ToolName = argv[0];
1501
1502   // Defaults to a.out if no filenames specified.
1503   if (InputFilenames.size() == 0)
1504     InputFilenames.push_back("a.out");
1505
1506   if (!Disassemble
1507       && !Relocations
1508       && !SectionHeaders
1509       && !SectionContents
1510       && !SymbolTable
1511       && !UnwindInfo
1512       && !PrivateHeaders
1513       && !ExportsTrie
1514       && !Rebase
1515       && !Bind
1516       && !LazyBind
1517       && !WeakBind
1518       && !RawClangAST
1519       && !(UniversalHeaders && MachOOpt)
1520       && !(ArchiveHeaders && MachOOpt)
1521       && !(IndirectSymbols && MachOOpt)
1522       && !(DataInCode && MachOOpt)
1523       && !(LinkOptHints && MachOOpt)
1524       && !(InfoPlist && MachOOpt)
1525       && !(DylibsUsed && MachOOpt)
1526       && !(DylibId && MachOOpt)
1527       && !(ObjcMetaData && MachOOpt)
1528       && !(DumpSections.size() != 0 && MachOOpt)
1529       && !PrintFaultMaps) {
1530     cl::PrintHelpMessage();
1531     return 2;
1532   }
1533
1534   std::for_each(InputFilenames.begin(), InputFilenames.end(),
1535                 DumpInput);
1536
1537   return ReturnValue;
1538 }