d207eabb52401190a30f11283e33e96d21d49e31
[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
19 #include "llvm/ADT/SmallString.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 MachOObjectFileBase *Obj, StreamWriter& Writer)
31     : ObjDumper(Writer)
32     , Obj(Obj) { }
33
34   virtual void printFileHeaders() LLVM_OVERRIDE;
35   virtual void printSections() LLVM_OVERRIDE;
36   virtual void printRelocations() LLVM_OVERRIDE;
37   virtual void printSymbols() LLVM_OVERRIDE;
38   virtual void printDynamicSymbols() LLVM_OVERRIDE;
39   virtual void printUnwindInfo() LLVM_OVERRIDE;
40
41 private:
42   void printSymbol(symbol_iterator SymI);
43
44   void printRelocation(section_iterator SecI, relocation_iterator RelI);
45
46   template<support::endianness E>
47   void printRelocation(const MachOObjectFileMiddle<E> *Obj,
48                        section_iterator SecI, relocation_iterator RelI);
49
50   template<support::endianness E>
51   void printSections(const MachOObjectFileMiddle<E> *Obj);
52
53   const MachOObjectFileBase *Obj;
54 };
55
56 } // namespace
57
58
59 namespace llvm {
60
61 error_code createMachODumper(const object::ObjectFile *Obj,
62                              StreamWriter& Writer,
63                              OwningPtr<ObjDumper> &Result) {
64   const MachOObjectFileBase *MachOObj = dyn_cast<MachOObjectFileBase>(Obj);
65   if (!MachOObj)
66     return readobj_error::unsupported_obj_file_format;
67
68   Result.reset(new MachODumper(MachOObj, Writer));
69   return readobj_error::success;
70 }
71
72 } // namespace llvm
73
74
75 static const EnumEntry<unsigned> MachOSectionTypes[] = {
76   { "Regular"                        , 0x00 },
77   { "ZeroFill"                       , 0x01 },
78   { "CStringLiterals"                , 0x02 },
79   { "4ByteLiterals"                  , 0x03 },
80   { "8ByteLiterals"                  , 0x04 },
81   { "LiteralPointers"                , 0x05 },
82   { "NonLazySymbolPointers"          , 0x06 },
83   { "LazySymbolPointers"             , 0x07 },
84   { "SymbolStubs"                    , 0x08 },
85   { "ModInitFuncs"                   , 0x09 },
86   { "ModTermFuncs"                   , 0x0A },
87   { "Coalesced"                      , 0x0B },
88   { "GBZeroFill"                     , 0x0C },
89   { "Interposing"                    , 0x0D },
90   { "16ByteLiterals"                 , 0x0E },
91   { "DTraceDOF"                      , 0x0F },
92   { "LazyDylibSymbolPoints"          , 0x10 },
93   { "ThreadLocalRegular"             , 0x11 },
94   { "ThreadLocalZerofill"            , 0x12 },
95   { "ThreadLocalVariables"           , 0x13 },
96   { "ThreadLocalVariablePointers"    , 0x14 },
97   { "ThreadLocalInitFunctionPointers", 0x15 }
98 };
99
100 static const EnumEntry<unsigned> MachOSectionAttributes[] = {
101   { "LocReloc"         , 1 <<  0 /*S_ATTR_LOC_RELOC          */ },
102   { "ExtReloc"         , 1 <<  1 /*S_ATTR_EXT_RELOC          */ },
103   { "SomeInstructions" , 1 <<  2 /*S_ATTR_SOME_INSTRUCTIONS  */ },
104   { "Debug"            , 1 << 17 /*S_ATTR_DEBUG              */ },
105   { "SelfModifyingCode", 1 << 18 /*S_ATTR_SELF_MODIFYING_CODE*/ },
106   { "LiveSupport"      , 1 << 19 /*S_ATTR_LIVE_SUPPORT       */ },
107   { "NoDeadStrip"      , 1 << 20 /*S_ATTR_NO_DEAD_STRIP      */ },
108   { "StripStaticSyms"  , 1 << 21 /*S_ATTR_STRIP_STATIC_SYMS  */ },
109   { "NoTOC"            , 1 << 22 /*S_ATTR_NO_TOC             */ },
110   { "PureInstructions" , 1 << 23 /*S_ATTR_PURE_INSTRUCTIONS  */ },
111 };
112
113 static const EnumEntry<unsigned> MachOSymbolRefTypes[] = {
114   { "UndefinedNonLazy",                     0 },
115   { "ReferenceFlagUndefinedLazy",           1 },
116   { "ReferenceFlagDefined",                 2 },
117   { "ReferenceFlagPrivateDefined",          3 },
118   { "ReferenceFlagPrivateUndefinedNonLazy", 4 },
119   { "ReferenceFlagPrivateUndefinedLazy",    5 }
120 };
121
122 static const EnumEntry<unsigned> MachOSymbolFlags[] = {
123   { "ReferencedDynamically", 0x10 },
124   { "NoDeadStrip",           0x20 },
125   { "WeakRef",               0x40 },
126   { "WeakDef",               0x80 }
127 };
128
129 static const EnumEntry<unsigned> MachOSymbolTypes[] = {
130   { "Undef",           0x0 },
131   { "External",        0x1 },
132   { "Abs",             0x2 },
133   { "Indirect",        0xA },
134   { "PreboundUndef",   0xC },
135   { "Section",         0xE },
136   { "PrivateExternal", 0x10 }
137 };
138
139 namespace {
140   enum {
141     N_STAB = 0xE0
142   };
143
144   struct MachOSection {
145     ArrayRef<char> Name;
146     ArrayRef<char> SegmentName;
147     uint64_t Address;
148     uint64_t Size;
149     uint32_t Offset;
150     uint32_t Alignment;
151     uint32_t RelocationTableOffset;
152     uint32_t NumRelocationTableEntries;
153     uint32_t Flags;
154     uint32_t Reserved1;
155     uint32_t Reserved2;
156   };
157
158   struct MachOSymbol {
159     uint32_t StringIndex;
160     uint8_t Type;
161     uint8_t SectionIndex;
162     uint16_t Flags;
163     uint64_t Value;
164   };
165 }
166
167 template<class MachOT>
168 static void getSection(const MachOObjectFile<MachOT> *Obj,
169                        DataRefImpl DRI,
170                        MachOSection &Section) {
171   const typename MachOObjectFile<MachOT>::Section *Sect = Obj->getSection(DRI);
172   Section.Address     = Sect->Address;
173   Section.Size        = Sect->Size;
174   Section.Offset      = Sect->Offset;
175   Section.Alignment   = Sect->Align;
176   Section.RelocationTableOffset = Sect->RelocationTableOffset;
177   Section.NumRelocationTableEntries = Sect->NumRelocationTableEntries;
178   Section.Flags       = Sect->Flags;
179   Section.Reserved1   = Sect->Reserved1;
180   Section.Reserved2   = Sect->Reserved2;
181 }
182
183 static void getSection(const MachOObjectFileBase *Obj,
184                        DataRefImpl DRI,
185                        MachOSection &Section) {
186   if (const MachOObjectFileLE32 *O = dyn_cast<MachOObjectFileLE32>(Obj))
187     return getSection(O, DRI, Section);
188   if (const MachOObjectFileLE64 *O = dyn_cast<MachOObjectFileLE64>(Obj))
189     return getSection(O, DRI, Section);
190   if (const MachOObjectFileBE32 *O = dyn_cast<MachOObjectFileBE32>(Obj))
191     return getSection(O, DRI, Section);
192   const MachOObjectFileBE64 *O = cast<MachOObjectFileBE64>(Obj);
193   getSection(O, DRI, Section);
194 }
195
196 template<class MachOT>
197 static void getSymbol(const MachOObjectFile<MachOT> *Obj,
198                       DataRefImpl DRI,
199                       MachOSymbol &Symbol) {
200   const typename MachOObjectFile<MachOT>::SymbolTableEntry *Entry =
201     Obj->getSymbolTableEntry(DRI);
202   Symbol.StringIndex  = Entry->StringIndex;
203   Symbol.Type         = Entry->Type;
204   Symbol.SectionIndex = Entry->SectionIndex;
205   Symbol.Flags        = Entry->Flags;
206   Symbol.Value        = Entry->Value;
207 }
208
209 static void getSymbol(const MachOObjectFileBase *Obj,
210                       DataRefImpl DRI,
211                       MachOSymbol &Symbol) {
212   if (const MachOObjectFileLE32 *O = dyn_cast<MachOObjectFileLE32>(Obj))
213     return getSymbol(O, DRI, Symbol);
214   if (const MachOObjectFileLE64 *O = dyn_cast<MachOObjectFileLE64>(Obj))
215     return getSymbol(O, DRI, Symbol);
216   if (const MachOObjectFileBE32 *O = dyn_cast<MachOObjectFileBE32>(Obj))
217     return getSymbol(O, DRI, Symbol);
218   const MachOObjectFileBE64 *O = cast<MachOObjectFileBE64>(Obj);
219   getSymbol(O, DRI, Symbol);
220 }
221
222 void MachODumper::printFileHeaders() {
223   W.startLine() << "FileHeaders not implemented.\n";
224 }
225
226 void MachODumper::printSections() {
227   if (const MachOObjectFileLE *O = dyn_cast<MachOObjectFileLE>(Obj))
228     return printSections(O);
229   const MachOObjectFileBE *O = cast<MachOObjectFileBE>(Obj);
230   return printSections(O);
231 }
232
233 template<support::endianness E>
234 void MachODumper::printSections(const MachOObjectFileMiddle<E> *Obj) {
235   ListScope Group(W, "Sections");
236
237   int SectionIndex = -1;
238   error_code EC;
239   for (section_iterator SecI = Obj->begin_sections(),
240                         SecE = Obj->end_sections();
241                         SecI != SecE; SecI.increment(EC)) {
242     if (error(EC)) break;
243
244     ++SectionIndex;
245
246     MachOSection Section;
247     getSection(Obj, SecI->getRawDataRefImpl(), Section);
248     DataRefImpl DR = SecI->getRawDataRefImpl();
249
250     StringRef Name;
251     if (error(SecI->getName(Name)))
252         Name = "";
253
254     ArrayRef<char> RawName = Obj->getSectionRawName(DR);
255     StringRef SegmentName = Obj->getSectionFinalSegmentName(DR);
256     ArrayRef<char> RawSegmentName = Obj->getSectionRawFinalSegmentName(DR);
257
258     DictScope SectionD(W, "Section");
259     W.printNumber("Index", SectionIndex);
260     W.printBinary("Name", Name, RawName);
261     W.printBinary("Segment", SegmentName, RawSegmentName);
262     W.printHex   ("Address", Section.Address);
263     W.printHex   ("Size", Section.Size);
264     W.printNumber("Offset", Section.Offset);
265     W.printNumber("Alignment", Section.Alignment);
266     W.printHex   ("RelocationOffset", Section.RelocationTableOffset);
267     W.printNumber("RelocationCount", Section.NumRelocationTableEntries);
268     W.printEnum  ("Type", Section.Flags & 0xFF,
269                   makeArrayRef(MachOSectionAttributes));
270     W.printFlags ("Attributes", Section.Flags >> 8,
271                   makeArrayRef(MachOSectionAttributes));
272     W.printHex   ("Reserved1", Section.Reserved1);
273     W.printHex   ("Reserved2", Section.Reserved2);
274
275     if (opts::SectionRelocations) {
276       ListScope D(W, "Relocations");
277       for (relocation_iterator RelI = SecI->begin_relocations(),
278                                RelE = SecI->end_relocations();
279                                RelI != RelE; RelI.increment(EC)) {
280         if (error(EC)) break;
281
282         printRelocation(SecI, RelI);
283       }
284     }
285
286     if (opts::SectionSymbols) {
287       ListScope D(W, "Symbols");
288       for (symbol_iterator SymI = Obj->begin_symbols(),
289                            SymE = Obj->end_symbols();
290                            SymI != SymE; SymI.increment(EC)) {
291         if (error(EC)) break;
292
293         bool Contained = false;
294         if (SecI->containsSymbol(*SymI, Contained) || !Contained)
295           continue;
296
297         printSymbol(SymI);
298       }
299     }
300
301     if (opts::SectionData) {
302       StringRef Data;
303       if (error(SecI->getContents(Data))) break;
304
305       W.printBinaryBlock("SectionData", Data);
306     }
307   }
308 }
309
310 void MachODumper::printRelocations() {
311   ListScope D(W, "Relocations");
312
313   error_code EC;
314   for (section_iterator SecI = Obj->begin_sections(),
315                         SecE = Obj->end_sections();
316                         SecI != SecE; SecI.increment(EC)) {
317     if (error(EC)) break;
318
319     StringRef Name;
320     if (error(SecI->getName(Name)))
321       continue;
322
323     bool PrintedGroup = false;
324     for (relocation_iterator RelI = SecI->begin_relocations(),
325                              RelE = SecI->end_relocations();
326                              RelI != RelE; RelI.increment(EC)) {
327       if (error(EC)) break;
328
329       if (!PrintedGroup) {
330         W.startLine() << "Section " << Name << " {\n";
331         W.indent();
332         PrintedGroup = true;
333       }
334
335       printRelocation(SecI, RelI);
336     }
337
338     if (PrintedGroup) {
339       W.unindent();
340       W.startLine() << "}\n";
341     }
342   }
343 }
344
345 void MachODumper::printRelocation(section_iterator SecI,
346                                   relocation_iterator RelI) {
347   if (const MachOObjectFileLE *O = dyn_cast<MachOObjectFileLE>(Obj))
348     return printRelocation(O, SecI, RelI);
349   const MachOObjectFileBE *O = cast<MachOObjectFileBE>(Obj);
350   return printRelocation(O, SecI, RelI);
351 }
352
353 template<support::endianness E>
354 void MachODumper::printRelocation(const MachOObjectFileMiddle<E> *Obj,
355                                   section_iterator SecI,
356                                   relocation_iterator RelI) {
357   uint64_t Offset;
358   SmallString<32> RelocName;
359   StringRef SymbolName;
360   SymbolRef Symbol;
361   if (error(RelI->getOffset(Offset))) return;
362   if (error(RelI->getTypeName(RelocName))) return;
363   if (error(RelI->getSymbol(Symbol))) return;
364   if (error(Symbol.getName(SymbolName))) return;
365
366   DataRefImpl DR = RelI->getRawDataRefImpl();
367   const typename MachOObjectFileMiddle<E>::RelocationEntry *RE =
368     Obj->getRelocation(DR);
369   bool IsScattered = Obj->isRelocationScattered(RE);
370
371   if (opts::ExpandRelocs) {
372     DictScope Group(W, "Relocation");
373     W.printHex("Offset", Offset);
374     W.printNumber("PCRel", Obj->isRelocationPCRel(RE));
375     W.printNumber("Length", Obj->getRelocationLength(RE));
376     if (IsScattered)
377       W.printString("Extern", StringRef("N/A"));
378     else
379       W.printNumber("Extern", RE->getExternal());
380     W.printNumber("Type", RelocName, RE->getType());
381     W.printString("Symbol", SymbolName.size() > 0 ? SymbolName : "-");
382     W.printNumber("Scattered", IsScattered);
383   } else {
384     raw_ostream& OS = W.startLine();
385     OS << W.hex(Offset)
386        << " " << Obj->isRelocationPCRel(RE)
387        << " " << Obj->getRelocationLength(RE);
388     if (IsScattered)
389       OS << " n/a";
390     else
391       OS << " " << RE->getExternal();
392     OS << " " << RelocName
393        << " " << IsScattered
394        << " " << (SymbolName.size() > 0 ? SymbolName : "-")
395        << "\n";
396   }
397 }
398
399 void MachODumper::printSymbols() {
400   ListScope Group(W, "Symbols");
401
402   error_code EC;
403   for (symbol_iterator SymI = Obj->begin_symbols(),
404                        SymE = Obj->end_symbols();
405                        SymI != SymE; SymI.increment(EC)) {
406     if (error(EC)) break;
407
408     printSymbol(SymI);
409   }
410 }
411
412 void MachODumper::printDynamicSymbols() {
413   ListScope Group(W, "DynamicSymbols");
414 }
415
416 void MachODumper::printSymbol(symbol_iterator SymI) {
417   error_code EC;
418
419   StringRef SymbolName;
420   if (SymI->getName(SymbolName))
421     SymbolName = "";
422
423   MachOSymbol Symbol;
424   getSymbol(Obj, SymI->getRawDataRefImpl(), Symbol);
425
426   StringRef SectionName;
427   section_iterator SecI(Obj->end_sections());
428   if (error(SymI->getSection(SecI)) ||
429       SecI == Obj->end_sections() ||
430       error(SecI->getName(SectionName)))
431     SectionName = "";
432
433   DictScope D(W, "Symbol");
434   W.printNumber("Name", SymbolName, Symbol.StringIndex);
435   if (Symbol.Type & N_STAB) {
436     W.printHex ("Type", "SymDebugTable", Symbol.Type);
437   } else {
438     W.printEnum("Type", Symbol.Type, makeArrayRef(MachOSymbolTypes));
439   }
440   W.printHex   ("Section", SectionName, Symbol.SectionIndex);
441   W.printEnum  ("RefType", static_cast<uint16_t>(Symbol.Flags & 0xF),
442                   makeArrayRef(MachOSymbolRefTypes));
443   W.printFlags ("Flags", static_cast<uint16_t>(Symbol.Flags & ~0xF),
444                   makeArrayRef(MachOSymbolFlags));
445   W.printHex   ("Value", Symbol.Value);
446 }
447
448 void MachODumper::printUnwindInfo() {
449   W.startLine() << "UnwindInfo not implemented.\n";
450 }