Re-sort #include lines again, prior to moving headers around.
[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/Object/MachO.h"
20 #include "llvm/Support/Casting.h"
21
22 using namespace llvm;
23 using namespace object;
24
25 namespace {
26
27 class MachODumper : public ObjDumper {
28 public:
29   MachODumper(const MachOObjectFile *Obj, StreamWriter& Writer)
30     : ObjDumper(Writer)
31     , Obj(Obj) { }
32
33   virtual void printFileHeaders() LLVM_OVERRIDE;
34   virtual void printSections() LLVM_OVERRIDE;
35   virtual void printRelocations() LLVM_OVERRIDE;
36   virtual void printSymbols() LLVM_OVERRIDE;
37   virtual void printDynamicSymbols() LLVM_OVERRIDE;
38   virtual void printUnwindInfo() LLVM_OVERRIDE;
39
40 private:
41   void printSymbol(symbol_iterator SymI);
42
43   void printRelocation(section_iterator SecI, relocation_iterator RelI);
44
45   void printRelocation(const MachOObjectFile *Obj,
46                        section_iterator SecI, relocation_iterator RelI);
47
48   void printSections(const MachOObjectFile *Obj);
49
50   const MachOObjectFile *Obj;
51 };
52
53 } // namespace
54
55
56 namespace llvm {
57
58 error_code createMachODumper(const object::ObjectFile *Obj,
59                              StreamWriter& Writer,
60                              OwningPtr<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   { "External",        0x1 },
129   { "Abs",             0x2 },
130   { "Indirect",        0xA },
131   { "PreboundUndef",   0xC },
132   { "Section",         0xE },
133   { "PrivateExternal", 0x10 }
134 };
135
136 namespace {
137   enum {
138     N_STAB = 0xE0
139   };
140
141   struct MachOSection {
142     ArrayRef<char> Name;
143     ArrayRef<char> SegmentName;
144     uint64_t Address;
145     uint64_t Size;
146     uint32_t Offset;
147     uint32_t Alignment;
148     uint32_t RelocationTableOffset;
149     uint32_t NumRelocationTableEntries;
150     uint32_t Flags;
151     uint32_t Reserved1;
152     uint32_t Reserved2;
153   };
154
155   struct MachOSymbol {
156     uint32_t StringIndex;
157     uint8_t Type;
158     uint8_t SectionIndex;
159     uint16_t Flags;
160     uint64_t Value;
161   };
162 }
163
164 static void getSection(const MachOObjectFile *Obj,
165                        DataRefImpl Sec,
166                        MachOSection &Section) {
167   if (!Obj->is64Bit()) {
168     MachO::section Sect = Obj->getSection(Sec);
169     Section.Address     = Sect.addr;
170     Section.Size        = Sect.size;
171     Section.Offset      = Sect.offset;
172     Section.Alignment   = Sect.align;
173     Section.RelocationTableOffset = Sect.reloff;
174     Section.NumRelocationTableEntries = Sect.nreloc;
175     Section.Flags       = Sect.flags;
176     Section.Reserved1   = Sect.reserved1;
177     Section.Reserved2   = Sect.reserved2;
178     return;
179   }
180   MachO::section_64 Sect = Obj->getSection64(Sec);
181   Section.Address     = Sect.addr;
182   Section.Size        = Sect.size;
183   Section.Offset      = Sect.offset;
184   Section.Alignment   = Sect.align;
185   Section.RelocationTableOffset = Sect.reloff;
186   Section.NumRelocationTableEntries = Sect.nreloc;
187   Section.Flags       = Sect.flags;
188   Section.Reserved1   = Sect.reserved1;
189   Section.Reserved2   = Sect.reserved2;
190 }
191
192
193 static void getSymbol(const MachOObjectFile *Obj,
194                       DataRefImpl DRI,
195                       MachOSymbol &Symbol) {
196   if (!Obj->is64Bit()) {
197     MachO::nlist Entry = Obj->getSymbolTableEntry(DRI);
198     Symbol.StringIndex  = Entry.n_strx;
199     Symbol.Type         = Entry.n_type;
200     Symbol.SectionIndex = Entry.n_sect;
201     Symbol.Flags        = Entry.n_desc;
202     Symbol.Value        = Entry.n_value;
203     return;
204   }
205   MachO::nlist_64 Entry = Obj->getSymbol64TableEntry(DRI);
206   Symbol.StringIndex  = Entry.n_strx;
207   Symbol.Type         = Entry.n_type;
208   Symbol.SectionIndex = Entry.n_sect;
209   Symbol.Flags        = Entry.n_desc;
210   Symbol.Value        = Entry.n_value;
211 }
212
213 void MachODumper::printFileHeaders() {
214   W.startLine() << "FileHeaders not implemented.\n";
215 }
216
217 void MachODumper::printSections() {
218   return printSections(Obj);
219 }
220
221 void MachODumper::printSections(const MachOObjectFile *Obj) {
222   ListScope Group(W, "Sections");
223
224   int SectionIndex = -1;
225   error_code EC;
226   for (section_iterator SecI = Obj->begin_sections(),
227                         SecE = Obj->end_sections();
228                         SecI != SecE; SecI.increment(EC)) {
229     if (error(EC)) break;
230
231     ++SectionIndex;
232
233     MachOSection Section;
234     getSection(Obj, SecI->getRawDataRefImpl(), Section);
235     DataRefImpl DR = SecI->getRawDataRefImpl();
236
237     StringRef Name;
238     if (error(SecI->getName(Name)))
239         Name = "";
240
241     ArrayRef<char> RawName = Obj->getSectionRawName(DR);
242     StringRef SegmentName = Obj->getSectionFinalSegmentName(DR);
243     ArrayRef<char> RawSegmentName = Obj->getSectionRawFinalSegmentName(DR);
244
245     DictScope SectionD(W, "Section");
246     W.printNumber("Index", SectionIndex);
247     W.printBinary("Name", Name, RawName);
248     W.printBinary("Segment", SegmentName, RawSegmentName);
249     W.printHex   ("Address", Section.Address);
250     W.printHex   ("Size", Section.Size);
251     W.printNumber("Offset", Section.Offset);
252     W.printNumber("Alignment", Section.Alignment);
253     W.printHex   ("RelocationOffset", Section.RelocationTableOffset);
254     W.printNumber("RelocationCount", Section.NumRelocationTableEntries);
255     W.printEnum  ("Type", Section.Flags & 0xFF,
256                   makeArrayRef(MachOSectionAttributes));
257     W.printFlags ("Attributes", Section.Flags >> 8,
258                   makeArrayRef(MachOSectionAttributes));
259     W.printHex   ("Reserved1", Section.Reserved1);
260     W.printHex   ("Reserved2", Section.Reserved2);
261
262     if (opts::SectionRelocations) {
263       ListScope D(W, "Relocations");
264       for (relocation_iterator RelI = SecI->begin_relocations(),
265                                RelE = SecI->end_relocations();
266                                RelI != RelE; RelI.increment(EC)) {
267         if (error(EC)) break;
268
269         printRelocation(SecI, RelI);
270       }
271     }
272
273     if (opts::SectionSymbols) {
274       ListScope D(W, "Symbols");
275       for (symbol_iterator SymI = Obj->begin_symbols(),
276                            SymE = Obj->end_symbols();
277                            SymI != SymE; SymI.increment(EC)) {
278         if (error(EC)) break;
279
280         bool Contained = false;
281         if (SecI->containsSymbol(*SymI, Contained) || !Contained)
282           continue;
283
284         printSymbol(SymI);
285       }
286     }
287
288     if (opts::SectionData) {
289       StringRef Data;
290       if (error(SecI->getContents(Data))) break;
291
292       W.printBinaryBlock("SectionData", Data);
293     }
294   }
295 }
296
297 void MachODumper::printRelocations() {
298   ListScope D(W, "Relocations");
299
300   error_code EC;
301   for (section_iterator SecI = Obj->begin_sections(),
302                         SecE = Obj->end_sections();
303                         SecI != SecE; SecI.increment(EC)) {
304     if (error(EC)) break;
305
306     StringRef Name;
307     if (error(SecI->getName(Name)))
308       continue;
309
310     bool PrintedGroup = false;
311     for (relocation_iterator RelI = SecI->begin_relocations(),
312                              RelE = SecI->end_relocations();
313                              RelI != RelE; RelI.increment(EC)) {
314       if (error(EC)) break;
315
316       if (!PrintedGroup) {
317         W.startLine() << "Section " << Name << " {\n";
318         W.indent();
319         PrintedGroup = true;
320       }
321
322       printRelocation(SecI, RelI);
323     }
324
325     if (PrintedGroup) {
326       W.unindent();
327       W.startLine() << "}\n";
328     }
329   }
330 }
331
332 void MachODumper::printRelocation(section_iterator SecI,
333                                   relocation_iterator RelI) {
334   return printRelocation(Obj, SecI, RelI);
335 }
336
337 void MachODumper::printRelocation(const MachOObjectFile *Obj,
338                                   section_iterator SecI,
339                                   relocation_iterator RelI) {
340   uint64_t Offset;
341   SmallString<32> RelocName;
342   StringRef SymbolName;
343   if (error(RelI->getOffset(Offset))) return;
344   if (error(RelI->getTypeName(RelocName))) return;
345   symbol_iterator Symbol = RelI->getSymbol();
346   if (Symbol != Obj->end_symbols() &&
347       error(Symbol->getName(SymbolName)))
348     return;
349
350   DataRefImpl DR = RelI->getRawDataRefImpl();
351   MachO::any_relocation_info RE = Obj->getRelocation(DR);
352   bool IsScattered = Obj->isRelocationScattered(RE);
353
354   if (opts::ExpandRelocs) {
355     DictScope Group(W, "Relocation");
356     W.printHex("Offset", Offset);
357     W.printNumber("PCRel", Obj->getAnyRelocationPCRel(RE));
358     W.printNumber("Length", Obj->getAnyRelocationLength(RE));
359     if (IsScattered)
360       W.printString("Extern", StringRef("N/A"));
361     else
362       W.printNumber("Extern", Obj->getPlainRelocationExternal(RE));
363     W.printNumber("Type", RelocName, Obj->getAnyRelocationType(RE));
364     W.printString("Symbol", SymbolName.size() > 0 ? SymbolName : "-");
365     W.printNumber("Scattered", IsScattered);
366   } else {
367     raw_ostream& OS = W.startLine();
368     OS << W.hex(Offset)
369        << " " << Obj->getAnyRelocationPCRel(RE)
370        << " " << Obj->getAnyRelocationLength(RE);
371     if (IsScattered)
372       OS << " n/a";
373     else
374       OS << " " << Obj->getPlainRelocationExternal(RE);
375     OS << " " << RelocName
376        << " " << IsScattered
377        << " " << (SymbolName.size() > 0 ? SymbolName : "-")
378        << "\n";
379   }
380 }
381
382 void MachODumper::printSymbols() {
383   ListScope Group(W, "Symbols");
384
385   error_code EC;
386   for (symbol_iterator SymI = Obj->begin_symbols(),
387                        SymE = Obj->end_symbols();
388                        SymI != SymE; SymI.increment(EC)) {
389     if (error(EC)) break;
390
391     printSymbol(SymI);
392   }
393 }
394
395 void MachODumper::printDynamicSymbols() {
396   ListScope Group(W, "DynamicSymbols");
397 }
398
399 void MachODumper::printSymbol(symbol_iterator SymI) {
400   StringRef SymbolName;
401   if (SymI->getName(SymbolName))
402     SymbolName = "";
403
404   MachOSymbol Symbol;
405   getSymbol(Obj, SymI->getRawDataRefImpl(), Symbol);
406
407   StringRef SectionName = "";
408   section_iterator SecI(Obj->end_sections());
409   if (!error(SymI->getSection(SecI)) &&
410       SecI != Obj->end_sections())
411       error(SecI->getName(SectionName));
412
413   DictScope D(W, "Symbol");
414   W.printNumber("Name", SymbolName, Symbol.StringIndex);
415   if (Symbol.Type & N_STAB) {
416     W.printHex ("Type", "SymDebugTable", Symbol.Type);
417   } else {
418     W.printEnum("Type", Symbol.Type, makeArrayRef(MachOSymbolTypes));
419   }
420   W.printHex   ("Section", SectionName, Symbol.SectionIndex);
421   W.printEnum  ("RefType", static_cast<uint16_t>(Symbol.Flags & 0xF),
422                   makeArrayRef(MachOSymbolRefTypes));
423   W.printFlags ("Flags", static_cast<uint16_t>(Symbol.Flags & ~0xF),
424                   makeArrayRef(MachOSymbolFlags));
425   W.printHex   ("Value", Symbol.Value);
426 }
427
428 void MachODumper::printUnwindInfo() {
429   W.startLine() << "UnwindInfo not implemented.\n";
430 }