Add some tests for RelocVisitor.
[oota-llvm.git] / tools / llvm-readobj / MachODumper.cpp
1 //===-- MachODump.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 file implements the MachO-specific dumper for llvm-readobj.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm-readobj.h"
15 #include "Error.h"
16 #include "ObjDumper.h"
17 #include "StreamWriter.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Object/MachO.h"
21 #include "llvm/Support/Casting.h"
22
23 using namespace llvm;
24 using namespace object;
25
26 namespace {
27
28 class MachODumper : public ObjDumper {
29 public:
30   MachODumper(const MachOObjectFile *Obj, StreamWriter& Writer)
31     : ObjDumper(Writer)
32     , Obj(Obj) { }
33
34   void printFileHeaders() override;
35   void printSections() override;
36   void printRelocations() override;
37   void printSymbols() override;
38   void printDynamicSymbols() override;
39   void printUnwindInfo() override;
40
41 private:
42   void printSymbol(const SymbolRef &Symbol);
43
44   void printRelocation(const RelocationRef &Reloc);
45
46   void printRelocation(const MachOObjectFile *Obj, const RelocationRef &Reloc);
47
48   void printSections(const MachOObjectFile *Obj);
49
50   const MachOObjectFile *Obj;
51 };
52
53 } // namespace
54
55
56 namespace llvm {
57
58 std::error_code createMachODumper(const object::ObjectFile *Obj,
59                                   StreamWriter &Writer,
60                                   std::unique_ptr<ObjDumper> &Result) {
61   const MachOObjectFile *MachOObj = dyn_cast<MachOObjectFile>(Obj);
62   if (!MachOObj)
63     return readobj_error::unsupported_obj_file_format;
64
65   Result.reset(new MachODumper(MachOObj, Writer));
66   return readobj_error::success;
67 }
68
69 } // namespace llvm
70
71
72 static const EnumEntry<unsigned> MachOSectionTypes[] = {
73   { "Regular"                        , 0x00 },
74   { "ZeroFill"                       , 0x01 },
75   { "CStringLiterals"                , 0x02 },
76   { "4ByteLiterals"                  , 0x03 },
77   { "8ByteLiterals"                  , 0x04 },
78   { "LiteralPointers"                , 0x05 },
79   { "NonLazySymbolPointers"          , 0x06 },
80   { "LazySymbolPointers"             , 0x07 },
81   { "SymbolStubs"                    , 0x08 },
82   { "ModInitFuncs"                   , 0x09 },
83   { "ModTermFuncs"                   , 0x0A },
84   { "Coalesced"                      , 0x0B },
85   { "GBZeroFill"                     , 0x0C },
86   { "Interposing"                    , 0x0D },
87   { "16ByteLiterals"                 , 0x0E },
88   { "DTraceDOF"                      , 0x0F },
89   { "LazyDylibSymbolPoints"          , 0x10 },
90   { "ThreadLocalRegular"             , 0x11 },
91   { "ThreadLocalZerofill"            , 0x12 },
92   { "ThreadLocalVariables"           , 0x13 },
93   { "ThreadLocalVariablePointers"    , 0x14 },
94   { "ThreadLocalInitFunctionPointers", 0x15 }
95 };
96
97 static const EnumEntry<unsigned> MachOSectionAttributes[] = {
98   { "LocReloc"         , 1 <<  0 /*S_ATTR_LOC_RELOC          */ },
99   { "ExtReloc"         , 1 <<  1 /*S_ATTR_EXT_RELOC          */ },
100   { "SomeInstructions" , 1 <<  2 /*S_ATTR_SOME_INSTRUCTIONS  */ },
101   { "Debug"            , 1 << 17 /*S_ATTR_DEBUG              */ },
102   { "SelfModifyingCode", 1 << 18 /*S_ATTR_SELF_MODIFYING_CODE*/ },
103   { "LiveSupport"      , 1 << 19 /*S_ATTR_LIVE_SUPPORT       */ },
104   { "NoDeadStrip"      , 1 << 20 /*S_ATTR_NO_DEAD_STRIP      */ },
105   { "StripStaticSyms"  , 1 << 21 /*S_ATTR_STRIP_STATIC_SYMS  */ },
106   { "NoTOC"            , 1 << 22 /*S_ATTR_NO_TOC             */ },
107   { "PureInstructions" , 1 << 23 /*S_ATTR_PURE_INSTRUCTIONS  */ },
108 };
109
110 static const EnumEntry<unsigned> MachOSymbolRefTypes[] = {
111   { "UndefinedNonLazy",                     0 },
112   { "ReferenceFlagUndefinedLazy",           1 },
113   { "ReferenceFlagDefined",                 2 },
114   { "ReferenceFlagPrivateDefined",          3 },
115   { "ReferenceFlagPrivateUndefinedNonLazy", 4 },
116   { "ReferenceFlagPrivateUndefinedLazy",    5 }
117 };
118
119 static const EnumEntry<unsigned> MachOSymbolFlags[] = {
120   { "ReferencedDynamically", 0x10 },
121   { "NoDeadStrip",           0x20 },
122   { "WeakRef",               0x40 },
123   { "WeakDef",               0x80 }
124 };
125
126 static const EnumEntry<unsigned> MachOSymbolTypes[] = {
127   { "Undef",           0x0 },
128   { "Abs",             0x2 },
129   { "Indirect",        0xA },
130   { "PreboundUndef",   0xC },
131   { "Section",         0xE }
132 };
133
134 namespace {
135   struct MachOSection {
136     ArrayRef<char> Name;
137     ArrayRef<char> SegmentName;
138     uint64_t Address;
139     uint64_t Size;
140     uint32_t Offset;
141     uint32_t Alignment;
142     uint32_t RelocationTableOffset;
143     uint32_t NumRelocationTableEntries;
144     uint32_t Flags;
145     uint32_t Reserved1;
146     uint32_t Reserved2;
147   };
148
149   struct MachOSymbol {
150     uint32_t StringIndex;
151     uint8_t Type;
152     uint8_t SectionIndex;
153     uint16_t Flags;
154     uint64_t Value;
155   };
156 }
157
158 static void getSection(const MachOObjectFile *Obj,
159                        DataRefImpl Sec,
160                        MachOSection &Section) {
161   if (!Obj->is64Bit()) {
162     MachO::section Sect = Obj->getSection(Sec);
163     Section.Address     = Sect.addr;
164     Section.Size        = Sect.size;
165     Section.Offset      = Sect.offset;
166     Section.Alignment   = Sect.align;
167     Section.RelocationTableOffset = Sect.reloff;
168     Section.NumRelocationTableEntries = Sect.nreloc;
169     Section.Flags       = Sect.flags;
170     Section.Reserved1   = Sect.reserved1;
171     Section.Reserved2   = Sect.reserved2;
172     return;
173   }
174   MachO::section_64 Sect = Obj->getSection64(Sec);
175   Section.Address     = Sect.addr;
176   Section.Size        = Sect.size;
177   Section.Offset      = Sect.offset;
178   Section.Alignment   = Sect.align;
179   Section.RelocationTableOffset = Sect.reloff;
180   Section.NumRelocationTableEntries = Sect.nreloc;
181   Section.Flags       = Sect.flags;
182   Section.Reserved1   = Sect.reserved1;
183   Section.Reserved2   = Sect.reserved2;
184 }
185
186
187 static void getSymbol(const MachOObjectFile *Obj,
188                       DataRefImpl DRI,
189                       MachOSymbol &Symbol) {
190   if (!Obj->is64Bit()) {
191     MachO::nlist Entry = Obj->getSymbolTableEntry(DRI);
192     Symbol.StringIndex  = Entry.n_strx;
193     Symbol.Type         = Entry.n_type;
194     Symbol.SectionIndex = Entry.n_sect;
195     Symbol.Flags        = Entry.n_desc;
196     Symbol.Value        = Entry.n_value;
197     return;
198   }
199   MachO::nlist_64 Entry = Obj->getSymbol64TableEntry(DRI);
200   Symbol.StringIndex  = Entry.n_strx;
201   Symbol.Type         = Entry.n_type;
202   Symbol.SectionIndex = Entry.n_sect;
203   Symbol.Flags        = Entry.n_desc;
204   Symbol.Value        = Entry.n_value;
205 }
206
207 void MachODumper::printFileHeaders() {
208   W.startLine() << "FileHeaders not implemented.\n";
209 }
210
211 void MachODumper::printSections() {
212   return printSections(Obj);
213 }
214
215 void MachODumper::printSections(const MachOObjectFile *Obj) {
216   ListScope Group(W, "Sections");
217
218   int SectionIndex = -1;
219   for (const SectionRef &Section : Obj->sections()) {
220     ++SectionIndex;
221
222     MachOSection MOSection;
223     getSection(Obj, Section.getRawDataRefImpl(), MOSection);
224     DataRefImpl DR = Section.getRawDataRefImpl();
225
226     StringRef Name;
227     if (error(Section.getName(Name)))
228       Name = "";
229
230     ArrayRef<char> RawName = Obj->getSectionRawName(DR);
231     StringRef SegmentName = Obj->getSectionFinalSegmentName(DR);
232     ArrayRef<char> RawSegmentName = Obj->getSectionRawFinalSegmentName(DR);
233
234     DictScope SectionD(W, "Section");
235     W.printNumber("Index", SectionIndex);
236     W.printBinary("Name", Name, RawName);
237     W.printBinary("Segment", SegmentName, RawSegmentName);
238     W.printHex("Address", MOSection.Address);
239     W.printHex("Size", MOSection.Size);
240     W.printNumber("Offset", MOSection.Offset);
241     W.printNumber("Alignment", MOSection.Alignment);
242     W.printHex("RelocationOffset", MOSection.RelocationTableOffset);
243     W.printNumber("RelocationCount", MOSection.NumRelocationTableEntries);
244     W.printEnum("Type", MOSection.Flags & 0xFF,
245                 makeArrayRef(MachOSectionAttributes));
246     W.printFlags("Attributes", MOSection.Flags >> 8,
247                  makeArrayRef(MachOSectionAttributes));
248     W.printHex("Reserved1", MOSection.Reserved1);
249     W.printHex("Reserved2", MOSection.Reserved2);
250
251     if (opts::SectionRelocations) {
252       ListScope D(W, "Relocations");
253       for (const RelocationRef &Reloc : Section.relocations())
254         printRelocation(Reloc);
255     }
256
257     if (opts::SectionSymbols) {
258       ListScope D(W, "Symbols");
259       for (const SymbolRef &Symbol : Obj->symbols()) {
260         bool Contained = false;
261         if (Section.containsSymbol(Symbol, Contained) || !Contained)
262           continue;
263
264         printSymbol(Symbol);
265       }
266     }
267
268     if (opts::SectionData) {
269       bool IsBSS;
270       if (error(Section.isBSS(IsBSS)))
271         break;
272       if (!IsBSS) {
273         StringRef Data;
274         if (error(Section.getContents(Data)))
275           break;
276
277         W.printBinaryBlock("SectionData", Data);
278       }
279     }
280   }
281 }
282
283 void MachODumper::printRelocations() {
284   ListScope D(W, "Relocations");
285
286   std::error_code EC;
287   for (const SectionRef &Section : Obj->sections()) {
288     StringRef Name;
289     if (error(Section.getName(Name)))
290       continue;
291
292     bool PrintedGroup = false;
293     for (const RelocationRef &Reloc : Section.relocations()) {
294       if (!PrintedGroup) {
295         W.startLine() << "Section " << Name << " {\n";
296         W.indent();
297         PrintedGroup = true;
298       }
299
300       printRelocation(Reloc);
301     }
302
303     if (PrintedGroup) {
304       W.unindent();
305       W.startLine() << "}\n";
306     }
307   }
308 }
309
310 void MachODumper::printRelocation(const RelocationRef &Reloc) {
311   return printRelocation(Obj, Reloc);
312 }
313
314 void MachODumper::printRelocation(const MachOObjectFile *Obj,
315                                   const RelocationRef &Reloc) {
316   uint64_t Offset;
317   SmallString<32> RelocName;
318   if (error(Reloc.getOffset(Offset)))
319     return;
320   if (error(Reloc.getTypeName(RelocName)))
321     return;
322
323   DataRefImpl DR = Reloc.getRawDataRefImpl();
324   MachO::any_relocation_info RE = Obj->getRelocation(DR);
325   bool IsScattered = Obj->isRelocationScattered(RE);
326   SmallString<32> SymbolNameOrOffset("0x");
327   if (IsScattered) {
328     // Scattered relocations don't really have an associated symbol
329     // for some reason, even if one exists in the symtab at the correct address.
330     SymbolNameOrOffset += utohexstr(Obj->getScatteredRelocationValue(RE));
331   } else {
332     symbol_iterator Symbol = Reloc.getSymbol();
333     if (Symbol != Obj->symbol_end()) {
334       StringRef SymbolName;
335       if (error(Symbol->getName(SymbolName)))
336         return;
337       SymbolNameOrOffset = SymbolName;
338     } else
339       SymbolNameOrOffset += utohexstr(Obj->getPlainRelocationSymbolNum(RE));
340   }
341
342   if (opts::ExpandRelocs) {
343     DictScope Group(W, "Relocation");
344     W.printHex("Offset", Offset);
345     W.printNumber("PCRel", Obj->getAnyRelocationPCRel(RE));
346     W.printNumber("Length", Obj->getAnyRelocationLength(RE));
347     if (IsScattered)
348       W.printString("Extern", StringRef("N/A"));
349     else
350       W.printNumber("Extern", Obj->getPlainRelocationExternal(RE));
351     W.printNumber("Type", RelocName, Obj->getAnyRelocationType(RE));
352     W.printString("Symbol", SymbolNameOrOffset);
353     W.printNumber("Scattered", IsScattered);
354   } else {
355     raw_ostream& OS = W.startLine();
356     OS << W.hex(Offset)
357        << " " << Obj->getAnyRelocationPCRel(RE)
358        << " " << Obj->getAnyRelocationLength(RE);
359     if (IsScattered)
360       OS << " n/a";
361     else
362       OS << " " << Obj->getPlainRelocationExternal(RE);
363     OS << " " << RelocName
364        << " " << IsScattered
365        << " " << SymbolNameOrOffset
366        << "\n";
367   }
368 }
369
370 void MachODumper::printSymbols() {
371   ListScope Group(W, "Symbols");
372
373   for (const SymbolRef &Symbol : Obj->symbols()) {
374     printSymbol(Symbol);
375   }
376 }
377
378 void MachODumper::printDynamicSymbols() {
379   ListScope Group(W, "DynamicSymbols");
380 }
381
382 void MachODumper::printSymbol(const SymbolRef &Symbol) {
383   StringRef SymbolName;
384   if (Symbol.getName(SymbolName))
385     SymbolName = "";
386
387   MachOSymbol MOSymbol;
388   getSymbol(Obj, Symbol.getRawDataRefImpl(), MOSymbol);
389
390   StringRef SectionName = "";
391   section_iterator SecI(Obj->section_begin());
392   if (!error(Symbol.getSection(SecI)) && SecI != Obj->section_end())
393     error(SecI->getName(SectionName));
394
395   DictScope D(W, "Symbol");
396   W.printNumber("Name", SymbolName, MOSymbol.StringIndex);
397   if (MOSymbol.Type & MachO::N_STAB) {
398     W.printHex("Type", "SymDebugTable", MOSymbol.Type);
399   } else {
400     if (MOSymbol.Type & MachO::N_PEXT)
401       W.startLine() << "PrivateExtern\n";
402     if (MOSymbol.Type & MachO::N_EXT)
403       W.startLine() << "Extern\n";
404     W.printEnum("Type", uint8_t(MOSymbol.Type & MachO::N_TYPE),
405                 makeArrayRef(MachOSymbolTypes));
406   }
407   W.printHex("Section", SectionName, MOSymbol.SectionIndex);
408   W.printEnum("RefType", static_cast<uint16_t>(MOSymbol.Flags & 0xF),
409               makeArrayRef(MachOSymbolRefTypes));
410   W.printFlags("Flags", static_cast<uint16_t>(MOSymbol.Flags & ~0xF),
411                makeArrayRef(MachOSymbolFlags));
412   W.printHex("Value", MOSymbol.Value);
413 }
414
415 void MachODumper::printUnwindInfo() {
416   W.startLine() << "UnwindInfo not implemented.\n";
417 }