Be a bit more consistent about using ErrorOr when constructing Binary objects.
[oota-llvm.git] / lib / Object / MachOObjectFile.cpp
1 //===- MachOObjectFile.cpp - Mach-O object file binding ---------*- C++ -*-===//
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 defines the MachOObjectFile class, which binds the MachOObject
11 // class to the generic ObjectFile wrapper.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Object/MachO.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Support/DataExtractor.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/Support/Host.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <cctype>
23 #include <cstring>
24 #include <limits>
25
26 using namespace llvm;
27 using namespace object;
28
29 namespace llvm {
30 namespace object {
31
32 struct nlist_base {
33   uint32_t n_strx;
34   uint8_t n_type;
35   uint8_t n_sect;
36   uint16_t n_desc;
37 };
38
39 struct section_base {
40   char sectname[16];
41   char segname[16];
42 };
43
44 template<typename T>
45 static void SwapValue(T &Value) {
46   Value = sys::SwapByteOrder(Value);
47 }
48
49 template<typename T>
50 static void SwapStruct(T &Value);
51
52 template<>
53 void SwapStruct(MachO::any_relocation_info &H) {
54   SwapValue(H.r_word0);
55   SwapValue(H.r_word1);
56 }
57
58 template<>
59 void SwapStruct(MachO::load_command &L) {
60   SwapValue(L.cmd);
61   SwapValue(L.cmdsize);
62 }
63
64 template<>
65 void SwapStruct(nlist_base &S) {
66   SwapValue(S.n_strx);
67   SwapValue(S.n_desc);
68 }
69
70 template<>
71 void SwapStruct(MachO::section &S) {
72   SwapValue(S.addr);
73   SwapValue(S.size);
74   SwapValue(S.offset);
75   SwapValue(S.align);
76   SwapValue(S.reloff);
77   SwapValue(S.nreloc);
78   SwapValue(S.flags);
79   SwapValue(S.reserved1);
80   SwapValue(S.reserved2);
81 }
82
83 template<>
84 void SwapStruct(MachO::section_64 &S) {
85   SwapValue(S.addr);
86   SwapValue(S.size);
87   SwapValue(S.offset);
88   SwapValue(S.align);
89   SwapValue(S.reloff);
90   SwapValue(S.nreloc);
91   SwapValue(S.flags);
92   SwapValue(S.reserved1);
93   SwapValue(S.reserved2);
94   SwapValue(S.reserved3);
95 }
96
97 template<>
98 void SwapStruct(MachO::nlist &S) {
99   SwapValue(S.n_strx);
100   SwapValue(S.n_desc);
101   SwapValue(S.n_value);
102 }
103
104 template<>
105 void SwapStruct(MachO::nlist_64 &S) {
106   SwapValue(S.n_strx);
107   SwapValue(S.n_desc);
108   SwapValue(S.n_value);
109 }
110
111 template<>
112 void SwapStruct(MachO::mach_header &H) {
113   SwapValue(H.magic);
114   SwapValue(H.cputype);
115   SwapValue(H.cpusubtype);
116   SwapValue(H.filetype);
117   SwapValue(H.ncmds);
118   SwapValue(H.sizeofcmds);
119   SwapValue(H.flags);
120 }
121
122 template<>
123 void SwapStruct(MachO::mach_header_64 &H) {
124   SwapValue(H.magic);
125   SwapValue(H.cputype);
126   SwapValue(H.cpusubtype);
127   SwapValue(H.filetype);
128   SwapValue(H.ncmds);
129   SwapValue(H.sizeofcmds);
130   SwapValue(H.flags);
131   SwapValue(H.reserved);
132 }
133
134 template<>
135 void SwapStruct(MachO::symtab_command &C) {
136   SwapValue(C.cmd);
137   SwapValue(C.cmdsize);
138   SwapValue(C.symoff);
139   SwapValue(C.nsyms);
140   SwapValue(C.stroff);
141   SwapValue(C.strsize);
142 }
143
144 template<>
145 void SwapStruct(MachO::dysymtab_command &C) {
146   SwapValue(C.cmd);
147   SwapValue(C.cmdsize);
148   SwapValue(C.ilocalsym);
149   SwapValue(C.nlocalsym);
150   SwapValue(C.iextdefsym);
151   SwapValue(C.nextdefsym);
152   SwapValue(C.iundefsym);
153   SwapValue(C.nundefsym);
154   SwapValue(C.tocoff);
155   SwapValue(C.ntoc);
156   SwapValue(C.modtaboff);
157   SwapValue(C.nmodtab);
158   SwapValue(C.extrefsymoff);
159   SwapValue(C.nextrefsyms);
160   SwapValue(C.indirectsymoff);
161   SwapValue(C.nindirectsyms);
162   SwapValue(C.extreloff);
163   SwapValue(C.nextrel);
164   SwapValue(C.locreloff);
165   SwapValue(C.nlocrel);
166 }
167
168 template<>
169 void SwapStruct(MachO::linkedit_data_command &C) {
170   SwapValue(C.cmd);
171   SwapValue(C.cmdsize);
172   SwapValue(C.dataoff);
173   SwapValue(C.datasize);
174 }
175
176 template<>
177 void SwapStruct(MachO::segment_command &C) {
178   SwapValue(C.cmd);
179   SwapValue(C.cmdsize);
180   SwapValue(C.vmaddr);
181   SwapValue(C.vmsize);
182   SwapValue(C.fileoff);
183   SwapValue(C.filesize);
184   SwapValue(C.maxprot);
185   SwapValue(C.initprot);
186   SwapValue(C.nsects);
187   SwapValue(C.flags);
188 }
189
190 template<>
191 void SwapStruct(MachO::segment_command_64 &C) {
192   SwapValue(C.cmd);
193   SwapValue(C.cmdsize);
194   SwapValue(C.vmaddr);
195   SwapValue(C.vmsize);
196   SwapValue(C.fileoff);
197   SwapValue(C.filesize);
198   SwapValue(C.maxprot);
199   SwapValue(C.initprot);
200   SwapValue(C.nsects);
201   SwapValue(C.flags);
202 }
203
204 template<>
205 void SwapStruct(uint32_t &C) {
206   SwapValue(C);
207 }
208
209 template<>
210 void SwapStruct(MachO::linker_options_command &C) {
211   SwapValue(C.cmd);
212   SwapValue(C.cmdsize);
213   SwapValue(C.count);
214 }
215
216 template<>
217 void SwapStruct(MachO::data_in_code_entry &C) {
218   SwapValue(C.offset);
219   SwapValue(C.length);
220   SwapValue(C.kind);
221 }
222
223 template<typename T>
224 T getStruct(const MachOObjectFile *O, const char *P) {
225   T Cmd;
226   memcpy(&Cmd, P, sizeof(T));
227   if (O->isLittleEndian() != sys::IsLittleEndianHost)
228     SwapStruct(Cmd);
229   return Cmd;
230 }
231
232 static uint32_t
233 getSegmentLoadCommandNumSections(const MachOObjectFile *O,
234                                  const MachOObjectFile::LoadCommandInfo &L) {
235   if (O->is64Bit()) {
236     MachO::segment_command_64 S = O->getSegment64LoadCommand(L);
237     return S.nsects;
238   }
239   MachO::segment_command S = O->getSegmentLoadCommand(L);
240   return S.nsects;
241 }
242
243 static const char *
244 getSectionPtr(const MachOObjectFile *O, MachOObjectFile::LoadCommandInfo L,
245               unsigned Sec) {
246   uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
247
248   bool Is64 = O->is64Bit();
249   unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
250                                     sizeof(MachO::segment_command);
251   unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
252                                 sizeof(MachO::section);
253
254   uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
255   return reinterpret_cast<const char*>(SectionAddr);
256 }
257
258 static const char *getPtr(const MachOObjectFile *O, size_t Offset) {
259   return O->getData().substr(Offset, 1).data();
260 }
261
262 static nlist_base
263 getSymbolTableEntryBase(const MachOObjectFile *O, DataRefImpl DRI) {
264   const char *P = reinterpret_cast<const char *>(DRI.p);
265   return getStruct<nlist_base>(O, P);
266 }
267
268 static StringRef parseSegmentOrSectionName(const char *P) {
269   if (P[15] == 0)
270     // Null terminated.
271     return P;
272   // Not null terminated, so this is a 16 char string.
273   return StringRef(P, 16);
274 }
275
276 // Helper to advance a section or symbol iterator multiple increments at a time.
277 template<class T>
278 static error_code advance(T &it, size_t Val) {
279   error_code ec;
280   while (Val--) {
281     it.increment(ec);
282   }
283   return ec;
284 }
285
286 template<class T>
287 static void advanceTo(T &it, size_t Val) {
288   if (error_code ec = advance(it, Val))
289     report_fatal_error(ec.message());
290 }
291
292 static unsigned getCPUType(const MachOObjectFile *O) {
293   return O->getHeader().cputype;
294 }
295
296 static void printRelocationTargetName(const MachOObjectFile *O,
297                                       const MachO::any_relocation_info &RE,
298                                       raw_string_ostream &fmt) {
299   bool IsScattered = O->isRelocationScattered(RE);
300
301   // Target of a scattered relocation is an address.  In the interest of
302   // generating pretty output, scan through the symbol table looking for a
303   // symbol that aligns with that address.  If we find one, print it.
304   // Otherwise, we just print the hex address of the target.
305   if (IsScattered) {
306     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
307
308     error_code ec;
309     for (symbol_iterator SI = O->begin_symbols(), SE = O->end_symbols();
310          SI != SE; SI.increment(ec)) {
311       if (ec) report_fatal_error(ec.message());
312
313       uint64_t Addr;
314       StringRef Name;
315
316       if ((ec = SI->getAddress(Addr)))
317         report_fatal_error(ec.message());
318       if (Addr != Val) continue;
319       if ((ec = SI->getName(Name)))
320         report_fatal_error(ec.message());
321       fmt << Name;
322       return;
323     }
324
325     // If we couldn't find a symbol that this relocation refers to, try
326     // to find a section beginning instead.
327     for (section_iterator SI = O->begin_sections(), SE = O->end_sections();
328          SI != SE; SI.increment(ec)) {
329       if (ec) report_fatal_error(ec.message());
330
331       uint64_t Addr;
332       StringRef Name;
333
334       if ((ec = SI->getAddress(Addr)))
335         report_fatal_error(ec.message());
336       if (Addr != Val) continue;
337       if ((ec = SI->getName(Name)))
338         report_fatal_error(ec.message());
339       fmt << Name;
340       return;
341     }
342
343     fmt << format("0x%x", Val);
344     return;
345   }
346
347   StringRef S;
348   bool isExtern = O->getPlainRelocationExternal(RE);
349   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
350
351   if (isExtern) {
352     symbol_iterator SI = O->begin_symbols();
353     advanceTo(SI, Val);
354     SI->getName(S);
355   } else {
356     section_iterator SI = O->begin_sections();
357     // Adjust for the fact that sections are 1-indexed.
358     advanceTo(SI, Val - 1);
359     SI->getName(S);
360   }
361
362   fmt << S;
363 }
364
365 static uint32_t
366 getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
367   return RE.r_word0;
368 }
369
370 static unsigned
371 getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
372   return RE.r_word0 & 0xffffff;
373 }
374
375 static bool getPlainRelocationPCRel(const MachOObjectFile *O,
376                                     const MachO::any_relocation_info &RE) {
377   if (O->isLittleEndian())
378     return (RE.r_word1 >> 24) & 1;
379   return (RE.r_word1 >> 7) & 1;
380 }
381
382 static bool
383 getScatteredRelocationPCRel(const MachOObjectFile *O,
384                             const MachO::any_relocation_info &RE) {
385   return (RE.r_word0 >> 30) & 1;
386 }
387
388 static unsigned getPlainRelocationLength(const MachOObjectFile *O,
389                                          const MachO::any_relocation_info &RE) {
390   if (O->isLittleEndian())
391     return (RE.r_word1 >> 25) & 3;
392   return (RE.r_word1 >> 5) & 3;
393 }
394
395 static unsigned
396 getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
397   return (RE.r_word0 >> 28) & 3;
398 }
399
400 static unsigned getPlainRelocationType(const MachOObjectFile *O,
401                                        const MachO::any_relocation_info &RE) {
402   if (O->isLittleEndian())
403     return RE.r_word1 >> 28;
404   return RE.r_word1 & 0xf;
405 }
406
407 static unsigned
408 getScatteredRelocationType(const MachO::any_relocation_info &RE) {
409   return (RE.r_word0 >> 24) & 0xf;
410 }
411
412 static uint32_t getSectionFlags(const MachOObjectFile *O,
413                                 DataRefImpl Sec) {
414   if (O->is64Bit()) {
415     MachO::section_64 Sect = O->getSection64(Sec);
416     return Sect.flags;
417   }
418   MachO::section Sect = O->getSection(Sec);
419   return Sect.flags;
420 }
421
422 MachOObjectFile::MachOObjectFile(MemoryBuffer *Object,
423                                  bool IsLittleEndian, bool Is64bits,
424                                  error_code &ec)
425     : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
426       SymtabLoadCmd(NULL), DysymtabLoadCmd(NULL), DataInCodeLoadCmd(NULL) {
427   uint32_t LoadCommandCount = this->getHeader().ncmds;
428   MachO::LoadCommandType SegmentLoadType = is64Bit() ?
429     MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT;
430
431   MachOObjectFile::LoadCommandInfo Load = getFirstLoadCommandInfo();
432   for (unsigned I = 0; ; ++I) {
433     if (Load.C.cmd == MachO::LC_SYMTAB) {
434       assert(!SymtabLoadCmd && "Multiple symbol tables");
435       SymtabLoadCmd = Load.Ptr;
436     } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
437       assert(!DysymtabLoadCmd && "Multiple dynamic symbol tables");
438       DysymtabLoadCmd = Load.Ptr;
439     } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
440       assert(!DataInCodeLoadCmd && "Multiple data in code tables");
441       DataInCodeLoadCmd = Load.Ptr;
442     } else if (Load.C.cmd == SegmentLoadType) {
443       uint32_t NumSections = getSegmentLoadCommandNumSections(this, Load);
444       for (unsigned J = 0; J < NumSections; ++J) {
445         const char *Sec = getSectionPtr(this, Load, J);
446         Sections.push_back(Sec);
447       }
448     }
449
450     if (I == LoadCommandCount - 1)
451       break;
452     else
453       Load = getNextLoadCommandInfo(Load);
454   }
455 }
456
457 error_code MachOObjectFile::getSymbolNext(DataRefImpl Symb,
458                                           SymbolRef &Res) const {
459   unsigned SymbolTableEntrySize = is64Bit() ?
460     sizeof(MachO::nlist_64) :
461     sizeof(MachO::nlist);
462   Symb.p += SymbolTableEntrySize;
463   Res = SymbolRef(Symb, this);
464   return object_error::success;
465 }
466
467 error_code MachOObjectFile::getSymbolName(DataRefImpl Symb,
468                                           StringRef &Res) const {
469   StringRef StringTable = getStringTableData();
470   nlist_base Entry = getSymbolTableEntryBase(this, Symb);
471   const char *Start = &StringTable.data()[Entry.n_strx];
472   Res = StringRef(Start);
473   return object_error::success;
474 }
475
476 error_code MachOObjectFile::getSymbolAddress(DataRefImpl Symb,
477                                              uint64_t &Res) const {
478   if (is64Bit()) {
479     MachO::nlist_64 Entry = getSymbol64TableEntry(Symb);
480     Res = Entry.n_value;
481   } else {
482     MachO::nlist Entry = getSymbolTableEntry(Symb);
483     Res = Entry.n_value;
484   }
485   return object_error::success;
486 }
487
488 error_code
489 MachOObjectFile::getSymbolFileOffset(DataRefImpl Symb,
490                                      uint64_t &Res) const {
491   nlist_base Entry = getSymbolTableEntryBase(this, Symb);
492   getSymbolAddress(Symb, Res);
493   if (Entry.n_sect) {
494     uint64_t Delta;
495     DataRefImpl SecRel;
496     SecRel.d.a = Entry.n_sect-1;
497     if (is64Bit()) {
498       MachO::section_64 Sec = getSection64(SecRel);
499       Delta = Sec.offset - Sec.addr;
500     } else {
501       MachO::section Sec = getSection(SecRel);
502       Delta = Sec.offset - Sec.addr;
503     }
504
505     Res += Delta;
506   }
507
508   return object_error::success;
509 }
510
511 error_code MachOObjectFile::getSymbolAlignment(DataRefImpl DRI,
512                                                uint32_t &Result) const {
513   uint32_t flags;
514   this->getSymbolFlags(DRI, flags);
515   if (flags & SymbolRef::SF_Common) {
516     nlist_base Entry = getSymbolTableEntryBase(this, DRI);
517     Result = 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
518   } else {
519     Result = 0;
520   }
521   return object_error::success;
522 }
523
524 error_code MachOObjectFile::getSymbolSize(DataRefImpl DRI,
525                                           uint64_t &Result) const {
526   uint64_t BeginOffset;
527   uint64_t EndOffset = 0;
528   uint8_t SectionIndex;
529
530   nlist_base Entry = getSymbolTableEntryBase(this, DRI);
531   uint64_t Value;
532   getSymbolAddress(DRI, Value);
533
534   BeginOffset = Value;
535
536   SectionIndex = Entry.n_sect;
537   if (!SectionIndex) {
538     uint32_t flags = SymbolRef::SF_None;
539     this->getSymbolFlags(DRI, flags);
540     if (flags & SymbolRef::SF_Common)
541       Result = Value;
542     else
543       Result = UnknownAddressOrSize;
544     return object_error::success;
545   }
546   // Unfortunately symbols are unsorted so we need to touch all
547   // symbols from load command
548   error_code ec;
549   for (symbol_iterator I = begin_symbols(), E = end_symbols(); I != E;
550        I.increment(ec)) {
551     DataRefImpl DRI = I->getRawDataRefImpl();
552     Entry = getSymbolTableEntryBase(this, DRI);
553     getSymbolAddress(DRI, Value);
554     if (Entry.n_sect == SectionIndex && Value > BeginOffset)
555       if (!EndOffset || Value < EndOffset)
556         EndOffset = Value;
557   }
558   if (!EndOffset) {
559     uint64_t Size;
560     DataRefImpl Sec;
561     Sec.d.a = SectionIndex-1;
562     getSectionSize(Sec, Size);
563     getSectionAddress(Sec, EndOffset);
564     EndOffset += Size;
565   }
566   Result = EndOffset - BeginOffset;
567   return object_error::success;
568 }
569
570 error_code MachOObjectFile::getSymbolType(DataRefImpl Symb,
571                                           SymbolRef::Type &Res) const {
572   nlist_base Entry = getSymbolTableEntryBase(this, Symb);
573   uint8_t n_type = Entry.n_type;
574
575   Res = SymbolRef::ST_Other;
576
577   // If this is a STAB debugging symbol, we can do nothing more.
578   if (n_type & MachO::N_STAB) {
579     Res = SymbolRef::ST_Debug;
580     return object_error::success;
581   }
582
583   switch (n_type & MachO::N_TYPE) {
584     case MachO::N_UNDF :
585       Res = SymbolRef::ST_Unknown;
586       break;
587     case MachO::N_SECT :
588       Res = SymbolRef::ST_Function;
589       break;
590   }
591   return object_error::success;
592 }
593
594 error_code MachOObjectFile::getSymbolFlags(DataRefImpl DRI,
595                                            uint32_t &Result) const {
596   nlist_base Entry = getSymbolTableEntryBase(this, DRI);
597
598   uint8_t MachOType = Entry.n_type;
599   uint16_t MachOFlags = Entry.n_desc;
600
601   // TODO: Correctly set SF_ThreadLocal
602   Result = SymbolRef::SF_None;
603
604   if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF)
605     Result |= SymbolRef::SF_Undefined;
606
607   if (MachOType & MachO::N_STAB)
608     Result |= SymbolRef::SF_FormatSpecific;
609
610   if (MachOType & MachO::N_EXT) {
611     Result |= SymbolRef::SF_Global;
612     if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
613       uint64_t Value;
614       getSymbolAddress(DRI, Value);
615       if (Value)
616         Result |= SymbolRef::SF_Common;
617     }
618   }
619
620   if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
621     Result |= SymbolRef::SF_Weak;
622
623   if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
624     Result |= SymbolRef::SF_Absolute;
625
626   return object_error::success;
627 }
628
629 error_code
630 MachOObjectFile::getSymbolSection(DataRefImpl Symb,
631                                   section_iterator &Res) const {
632   nlist_base Entry = getSymbolTableEntryBase(this, Symb);
633   uint8_t index = Entry.n_sect;
634
635   if (index == 0) {
636     Res = end_sections();
637   } else {
638     DataRefImpl DRI;
639     DRI.d.a = index - 1;
640     Res = section_iterator(SectionRef(DRI, this));
641   }
642
643   return object_error::success;
644 }
645
646 error_code MachOObjectFile::getSymbolValue(DataRefImpl Symb,
647                                            uint64_t &Val) const {
648   report_fatal_error("getSymbolValue unimplemented in MachOObjectFile");
649 }
650
651 error_code MachOObjectFile::getSectionNext(DataRefImpl Sec,
652                                            SectionRef &Res) const {
653   Sec.d.a++;
654   Res = SectionRef(Sec, this);
655   return object_error::success;
656 }
657
658 error_code
659 MachOObjectFile::getSectionName(DataRefImpl Sec, StringRef &Result) const {
660   ArrayRef<char> Raw = getSectionRawName(Sec);
661   Result = parseSegmentOrSectionName(Raw.data());
662   return object_error::success;
663 }
664
665 error_code
666 MachOObjectFile::getSectionAddress(DataRefImpl Sec, uint64_t &Res) const {
667   if (is64Bit()) {
668     MachO::section_64 Sect = getSection64(Sec);
669     Res = Sect.addr;
670   } else {
671     MachO::section Sect = getSection(Sec);
672     Res = Sect.addr;
673   }
674   return object_error::success;
675 }
676
677 error_code
678 MachOObjectFile::getSectionSize(DataRefImpl Sec, uint64_t &Res) const {
679   if (is64Bit()) {
680     MachO::section_64 Sect = getSection64(Sec);
681     Res = Sect.size;
682   } else {
683     MachO::section Sect = getSection(Sec);
684     Res = Sect.size;
685   }
686
687   return object_error::success;
688 }
689
690 error_code
691 MachOObjectFile::getSectionContents(DataRefImpl Sec, StringRef &Res) const {
692   uint32_t Offset;
693   uint64_t Size;
694
695   if (is64Bit()) {
696     MachO::section_64 Sect = getSection64(Sec);
697     Offset = Sect.offset;
698     Size = Sect.size;
699   } else {
700     MachO::section Sect = getSection(Sec);
701     Offset = Sect.offset;
702     Size = Sect.size;
703   }
704
705   Res = this->getData().substr(Offset, Size);
706   return object_error::success;
707 }
708
709 error_code
710 MachOObjectFile::getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const {
711   uint32_t Align;
712   if (is64Bit()) {
713     MachO::section_64 Sect = getSection64(Sec);
714     Align = Sect.align;
715   } else {
716     MachO::section Sect = getSection(Sec);
717     Align = Sect.align;
718   }
719
720   Res = uint64_t(1) << Align;
721   return object_error::success;
722 }
723
724 error_code
725 MachOObjectFile::isSectionText(DataRefImpl Sec, bool &Res) const {
726   uint32_t Flags = getSectionFlags(this, Sec);
727   Res = Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
728   return object_error::success;
729 }
730
731 error_code MachOObjectFile::isSectionData(DataRefImpl DRI, bool &Result) const {
732   // FIXME: Unimplemented.
733   Result = false;
734   return object_error::success;
735 }
736
737 error_code MachOObjectFile::isSectionBSS(DataRefImpl DRI, bool &Result) const {
738   // FIXME: Unimplemented.
739   Result = false;
740   return object_error::success;
741 }
742
743 error_code
744 MachOObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
745                                                bool &Result) const {
746   // FIXME: Unimplemented.
747   Result = true;
748   return object_error::success;
749 }
750
751 error_code MachOObjectFile::isSectionVirtual(DataRefImpl Sec,
752                                              bool &Result) const {
753   // FIXME: Unimplemented.
754   Result = false;
755   return object_error::success;
756 }
757
758 error_code
759 MachOObjectFile::isSectionZeroInit(DataRefImpl Sec, bool &Res) const {
760   uint32_t Flags = getSectionFlags(this, Sec);
761   unsigned SectionType = Flags & MachO::SECTION_TYPE;
762   Res = SectionType == MachO::S_ZEROFILL ||
763     SectionType == MachO::S_GB_ZEROFILL;
764   return object_error::success;
765 }
766
767 error_code MachOObjectFile::isSectionReadOnlyData(DataRefImpl Sec,
768                                                   bool &Result) const {
769   // Consider using the code from isSectionText to look for __const sections.
770   // Alternately, emit S_ATTR_PURE_INSTRUCTIONS and/or S_ATTR_SOME_INSTRUCTIONS
771   // to use section attributes to distinguish code from data.
772
773   // FIXME: Unimplemented.
774   Result = false;
775   return object_error::success;
776 }
777
778 error_code
779 MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
780                                        bool &Result) const {
781   SymbolRef::Type ST;
782   this->getSymbolType(Symb, ST);
783   if (ST == SymbolRef::ST_Unknown) {
784     Result = false;
785     return object_error::success;
786   }
787
788   uint64_t SectBegin, SectEnd;
789   getSectionAddress(Sec, SectBegin);
790   getSectionSize(Sec, SectEnd);
791   SectEnd += SectBegin;
792
793   uint64_t SymAddr;
794   getSymbolAddress(Symb, SymAddr);
795   Result = (SymAddr >= SectBegin) && (SymAddr < SectEnd);
796
797   return object_error::success;
798 }
799
800 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
801   uint32_t Offset;
802   if (is64Bit()) {
803     MachO::section_64 Sect = getSection64(Sec);
804     Offset = Sect.reloff;
805   } else {
806     MachO::section Sect = getSection(Sec);
807     Offset = Sect.reloff;
808   }
809
810   DataRefImpl Ret;
811   Ret.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
812   return relocation_iterator(RelocationRef(Ret, this));
813 }
814
815 relocation_iterator
816 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
817   uint32_t Offset;
818   uint32_t Num;
819   if (is64Bit()) {
820     MachO::section_64 Sect = getSection64(Sec);
821     Offset = Sect.reloff;
822     Num = Sect.nreloc;
823   } else {
824     MachO::section Sect = getSection(Sec);
825     Offset = Sect.reloff;
826     Num = Sect.nreloc;
827   }
828
829   const MachO::any_relocation_info *P =
830     reinterpret_cast<const MachO::any_relocation_info *>(getPtr(this, Offset));
831
832   DataRefImpl Ret;
833   Ret.p = reinterpret_cast<uintptr_t>(P + Num);
834   return relocation_iterator(RelocationRef(Ret, this));
835 }
836
837 error_code MachOObjectFile::getRelocationNext(DataRefImpl Rel,
838                                               RelocationRef &Res) const {
839   const MachO::any_relocation_info *P =
840     reinterpret_cast<const MachO::any_relocation_info *>(Rel.p);
841   Rel.p = reinterpret_cast<uintptr_t>(P + 1);
842   Res = RelocationRef(Rel, this);
843   return object_error::success;
844 }
845
846 error_code
847 MachOObjectFile::getRelocationAddress(DataRefImpl Rel, uint64_t &Res) const {
848   report_fatal_error("getRelocationAddress not implemented in MachOObjectFile");
849 }
850
851 error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
852                                                 uint64_t &Res) const {
853   MachO::any_relocation_info RE = getRelocation(Rel);
854   Res = getAnyRelocationAddress(RE);
855   return object_error::success;
856 }
857
858 symbol_iterator
859 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
860   MachO::any_relocation_info RE = getRelocation(Rel);
861   uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
862   bool isExtern = getPlainRelocationExternal(RE);
863   if (!isExtern)
864     return end_symbols();
865
866   MachO::symtab_command S = getSymtabLoadCommand();
867   unsigned SymbolTableEntrySize = is64Bit() ?
868     sizeof(MachO::nlist_64) :
869     sizeof(MachO::nlist);
870   uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
871   DataRefImpl Sym;
872   Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
873   return symbol_iterator(SymbolRef(Sym, this));
874 }
875
876 error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
877                                               uint64_t &Res) const {
878   MachO::any_relocation_info RE = getRelocation(Rel);
879   Res = getAnyRelocationType(RE);
880   return object_error::success;
881 }
882
883 error_code
884 MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
885                                        SmallVectorImpl<char> &Result) const {
886   StringRef res;
887   uint64_t RType;
888   getRelocationType(Rel, RType);
889
890   unsigned Arch = this->getArch();
891
892   switch (Arch) {
893     case Triple::x86: {
894       static const char *const Table[] =  {
895         "GENERIC_RELOC_VANILLA",
896         "GENERIC_RELOC_PAIR",
897         "GENERIC_RELOC_SECTDIFF",
898         "GENERIC_RELOC_PB_LA_PTR",
899         "GENERIC_RELOC_LOCAL_SECTDIFF",
900         "GENERIC_RELOC_TLV" };
901
902       if (RType > 5)
903         res = "Unknown";
904       else
905         res = Table[RType];
906       break;
907     }
908     case Triple::x86_64: {
909       static const char *const Table[] =  {
910         "X86_64_RELOC_UNSIGNED",
911         "X86_64_RELOC_SIGNED",
912         "X86_64_RELOC_BRANCH",
913         "X86_64_RELOC_GOT_LOAD",
914         "X86_64_RELOC_GOT",
915         "X86_64_RELOC_SUBTRACTOR",
916         "X86_64_RELOC_SIGNED_1",
917         "X86_64_RELOC_SIGNED_2",
918         "X86_64_RELOC_SIGNED_4",
919         "X86_64_RELOC_TLV" };
920
921       if (RType > 9)
922         res = "Unknown";
923       else
924         res = Table[RType];
925       break;
926     }
927     case Triple::arm: {
928       static const char *const Table[] =  {
929         "ARM_RELOC_VANILLA",
930         "ARM_RELOC_PAIR",
931         "ARM_RELOC_SECTDIFF",
932         "ARM_RELOC_LOCAL_SECTDIFF",
933         "ARM_RELOC_PB_LA_PTR",
934         "ARM_RELOC_BR24",
935         "ARM_THUMB_RELOC_BR22",
936         "ARM_THUMB_32BIT_BRANCH",
937         "ARM_RELOC_HALF",
938         "ARM_RELOC_HALF_SECTDIFF" };
939
940       if (RType > 9)
941         res = "Unknown";
942       else
943         res = Table[RType];
944       break;
945     }
946     case Triple::ppc: {
947       static const char *const Table[] =  {
948         "PPC_RELOC_VANILLA",
949         "PPC_RELOC_PAIR",
950         "PPC_RELOC_BR14",
951         "PPC_RELOC_BR24",
952         "PPC_RELOC_HI16",
953         "PPC_RELOC_LO16",
954         "PPC_RELOC_HA16",
955         "PPC_RELOC_LO14",
956         "PPC_RELOC_SECTDIFF",
957         "PPC_RELOC_PB_LA_PTR",
958         "PPC_RELOC_HI16_SECTDIFF",
959         "PPC_RELOC_LO16_SECTDIFF",
960         "PPC_RELOC_HA16_SECTDIFF",
961         "PPC_RELOC_JBSR",
962         "PPC_RELOC_LO14_SECTDIFF",
963         "PPC_RELOC_LOCAL_SECTDIFF" };
964
965       if (RType > 15)
966         res = "Unknown";
967       else
968         res = Table[RType];
969       break;
970     }
971     case Triple::UnknownArch:
972       res = "Unknown";
973       break;
974   }
975   Result.append(res.begin(), res.end());
976   return object_error::success;
977 }
978
979 error_code
980 MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
981                                           SmallVectorImpl<char> &Result) const {
982   MachO::any_relocation_info RE = getRelocation(Rel);
983
984   unsigned Arch = this->getArch();
985
986   std::string fmtbuf;
987   raw_string_ostream fmt(fmtbuf);
988   unsigned Type = this->getAnyRelocationType(RE);
989   bool IsPCRel = this->getAnyRelocationPCRel(RE);
990
991   // Determine any addends that should be displayed with the relocation.
992   // These require decoding the relocation type, which is triple-specific.
993
994   // X86_64 has entirely custom relocation types.
995   if (Arch == Triple::x86_64) {
996     bool isPCRel = getAnyRelocationPCRel(RE);
997
998     switch (Type) {
999       case MachO::X86_64_RELOC_GOT_LOAD:
1000       case MachO::X86_64_RELOC_GOT: {
1001         printRelocationTargetName(this, RE, fmt);
1002         fmt << "@GOT";
1003         if (isPCRel) fmt << "PCREL";
1004         break;
1005       }
1006       case MachO::X86_64_RELOC_SUBTRACTOR: {
1007         DataRefImpl RelNext = Rel;
1008         RelNext.d.a++;
1009         MachO::any_relocation_info RENext = getRelocation(RelNext);
1010
1011         // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
1012         // X86_64_RELOC_UNSIGNED.
1013         // NOTE: Scattered relocations don't exist on x86_64.
1014         unsigned RType = getAnyRelocationType(RENext);
1015         if (RType != MachO::X86_64_RELOC_UNSIGNED)
1016           report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
1017                              "X86_64_RELOC_SUBTRACTOR.");
1018
1019         // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
1020         // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
1021         printRelocationTargetName(this, RENext, fmt);
1022         fmt << "-";
1023         printRelocationTargetName(this, RE, fmt);
1024         break;
1025       }
1026       case MachO::X86_64_RELOC_TLV:
1027         printRelocationTargetName(this, RE, fmt);
1028         fmt << "@TLV";
1029         if (isPCRel) fmt << "P";
1030         break;
1031       case MachO::X86_64_RELOC_SIGNED_1:
1032         printRelocationTargetName(this, RE, fmt);
1033         fmt << "-1";
1034         break;
1035       case MachO::X86_64_RELOC_SIGNED_2:
1036         printRelocationTargetName(this, RE, fmt);
1037         fmt << "-2";
1038         break;
1039       case MachO::X86_64_RELOC_SIGNED_4:
1040         printRelocationTargetName(this, RE, fmt);
1041         fmt << "-4";
1042         break;
1043       default:
1044         printRelocationTargetName(this, RE, fmt);
1045         break;
1046     }
1047   // X86 and ARM share some relocation types in common.
1048   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
1049              Arch == Triple::ppc) {
1050     // Generic relocation types...
1051     switch (Type) {
1052       case MachO::GENERIC_RELOC_PAIR: // prints no info
1053         return object_error::success;
1054       case MachO::GENERIC_RELOC_SECTDIFF: {
1055         DataRefImpl RelNext = Rel;
1056         RelNext.d.a++;
1057         MachO::any_relocation_info RENext = getRelocation(RelNext);
1058
1059         // X86 sect diff's must be followed by a relocation of type
1060         // GENERIC_RELOC_PAIR.
1061         unsigned RType = getAnyRelocationType(RENext);
1062
1063         if (RType != MachO::GENERIC_RELOC_PAIR)
1064           report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1065                              "GENERIC_RELOC_SECTDIFF.");
1066
1067         printRelocationTargetName(this, RE, fmt);
1068         fmt << "-";
1069         printRelocationTargetName(this, RENext, fmt);
1070         break;
1071       }
1072     }
1073
1074     if (Arch == Triple::x86 || Arch == Triple::ppc) {
1075       switch (Type) {
1076         case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1077           DataRefImpl RelNext = Rel;
1078           RelNext.d.a++;
1079           MachO::any_relocation_info RENext = getRelocation(RelNext);
1080
1081           // X86 sect diff's must be followed by a relocation of type
1082           // GENERIC_RELOC_PAIR.
1083           unsigned RType = getAnyRelocationType(RENext);
1084           if (RType != MachO::GENERIC_RELOC_PAIR)
1085             report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1086                                "GENERIC_RELOC_LOCAL_SECTDIFF.");
1087
1088           printRelocationTargetName(this, RE, fmt);
1089           fmt << "-";
1090           printRelocationTargetName(this, RENext, fmt);
1091           break;
1092         }
1093         case MachO::GENERIC_RELOC_TLV: {
1094           printRelocationTargetName(this, RE, fmt);
1095           fmt << "@TLV";
1096           if (IsPCRel) fmt << "P";
1097           break;
1098         }
1099         default:
1100           printRelocationTargetName(this, RE, fmt);
1101       }
1102     } else { // ARM-specific relocations
1103       switch (Type) {
1104         case MachO::ARM_RELOC_HALF:
1105         case MachO::ARM_RELOC_HALF_SECTDIFF: {
1106           // Half relocations steal a bit from the length field to encode
1107           // whether this is an upper16 or a lower16 relocation.
1108           bool isUpper = getAnyRelocationLength(RE) >> 1;
1109
1110           if (isUpper)
1111             fmt << ":upper16:(";
1112           else
1113             fmt << ":lower16:(";
1114           printRelocationTargetName(this, RE, fmt);
1115
1116           DataRefImpl RelNext = Rel;
1117           RelNext.d.a++;
1118           MachO::any_relocation_info RENext = getRelocation(RelNext);
1119
1120           // ARM half relocs must be followed by a relocation of type
1121           // ARM_RELOC_PAIR.
1122           unsigned RType = getAnyRelocationType(RENext);
1123           if (RType != MachO::ARM_RELOC_PAIR)
1124             report_fatal_error("Expected ARM_RELOC_PAIR after "
1125                                "ARM_RELOC_HALF");
1126
1127           // NOTE: The half of the target virtual address is stashed in the
1128           // address field of the secondary relocation, but we can't reverse
1129           // engineer the constant offset from it without decoding the movw/movt
1130           // instruction to find the other half in its immediate field.
1131
1132           // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1133           // symbol/section pointer of the follow-on relocation.
1134           if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1135             fmt << "-";
1136             printRelocationTargetName(this, RENext, fmt);
1137           }
1138
1139           fmt << ")";
1140           break;
1141         }
1142         default: {
1143           printRelocationTargetName(this, RE, fmt);
1144         }
1145       }
1146     }
1147   } else
1148     printRelocationTargetName(this, RE, fmt);
1149
1150   fmt.flush();
1151   Result.append(fmtbuf.begin(), fmtbuf.end());
1152   return object_error::success;
1153 }
1154
1155 error_code
1156 MachOObjectFile::getRelocationHidden(DataRefImpl Rel, bool &Result) const {
1157   unsigned Arch = getArch();
1158   uint64_t Type;
1159   getRelocationType(Rel, Type);
1160
1161   Result = false;
1162
1163   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1164   // is always hidden.
1165   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1166     if (Type == MachO::GENERIC_RELOC_PAIR) Result = true;
1167   } else if (Arch == Triple::x86_64) {
1168     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1169     // an X86_64_RELOC_SUBTRACTOR.
1170     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1171       DataRefImpl RelPrev = Rel;
1172       RelPrev.d.a--;
1173       uint64_t PrevType;
1174       getRelocationType(RelPrev, PrevType);
1175       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1176         Result = true;
1177     }
1178   }
1179
1180   return object_error::success;
1181 }
1182
1183 error_code MachOObjectFile::getLibraryNext(DataRefImpl LibData,
1184                                            LibraryRef &Res) const {
1185   report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1186 }
1187
1188 error_code MachOObjectFile::getLibraryPath(DataRefImpl LibData,
1189                                            StringRef &Res) const {
1190   report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1191 }
1192
1193 symbol_iterator MachOObjectFile::begin_symbols() const {
1194   DataRefImpl DRI;
1195   if (!SymtabLoadCmd)
1196     return symbol_iterator(SymbolRef(DRI, this));
1197
1198   MachO::symtab_command Symtab = getSymtabLoadCommand();
1199   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1200   return symbol_iterator(SymbolRef(DRI, this));
1201 }
1202
1203 symbol_iterator MachOObjectFile::end_symbols() const {
1204   DataRefImpl DRI;
1205   if (!SymtabLoadCmd)
1206     return symbol_iterator(SymbolRef(DRI, this));
1207
1208   MachO::symtab_command Symtab = getSymtabLoadCommand();
1209   unsigned SymbolTableEntrySize = is64Bit() ?
1210     sizeof(MachO::nlist_64) :
1211     sizeof(MachO::nlist);
1212   unsigned Offset = Symtab.symoff +
1213     Symtab.nsyms * SymbolTableEntrySize;
1214   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1215   return symbol_iterator(SymbolRef(DRI, this));
1216 }
1217
1218 symbol_iterator MachOObjectFile::begin_dynamic_symbols() const {
1219   // TODO: implement
1220   report_fatal_error("Dynamic symbols unimplemented in MachOObjectFile");
1221 }
1222
1223 symbol_iterator MachOObjectFile::end_dynamic_symbols() const {
1224   // TODO: implement
1225   report_fatal_error("Dynamic symbols unimplemented in MachOObjectFile");
1226 }
1227
1228 section_iterator MachOObjectFile::begin_sections() const {
1229   DataRefImpl DRI;
1230   return section_iterator(SectionRef(DRI, this));
1231 }
1232
1233 section_iterator MachOObjectFile::end_sections() const {
1234   DataRefImpl DRI;
1235   DRI.d.a = Sections.size();
1236   return section_iterator(SectionRef(DRI, this));
1237 }
1238
1239 library_iterator MachOObjectFile::begin_libraries_needed() const {
1240   // TODO: implement
1241   report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1242 }
1243
1244 library_iterator MachOObjectFile::end_libraries_needed() const {
1245   // TODO: implement
1246   report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1247 }
1248
1249 uint8_t MachOObjectFile::getBytesInAddress() const {
1250   return is64Bit() ? 8 : 4;
1251 }
1252
1253 StringRef MachOObjectFile::getFileFormatName() const {
1254   unsigned CPUType = getCPUType(this);
1255   if (!is64Bit()) {
1256     switch (CPUType) {
1257     case llvm::MachO::CPU_TYPE_I386:
1258       return "Mach-O 32-bit i386";
1259     case llvm::MachO::CPU_TYPE_ARM:
1260       return "Mach-O arm";
1261     case llvm::MachO::CPU_TYPE_POWERPC:
1262       return "Mach-O 32-bit ppc";
1263     default:
1264       assert((CPUType & llvm::MachO::CPU_ARCH_ABI64) == 0 &&
1265              "64-bit object file when we're not 64-bit?");
1266       return "Mach-O 32-bit unknown";
1267     }
1268   }
1269
1270   // Make sure the cpu type has the correct mask.
1271   assert((CPUType & llvm::MachO::CPU_ARCH_ABI64)
1272          == llvm::MachO::CPU_ARCH_ABI64 &&
1273          "32-bit object file when we're 64-bit?");
1274
1275   switch (CPUType) {
1276   case llvm::MachO::CPU_TYPE_X86_64:
1277     return "Mach-O 64-bit x86-64";
1278   case llvm::MachO::CPU_TYPE_POWERPC64:
1279     return "Mach-O 64-bit ppc64";
1280   default:
1281     return "Mach-O 64-bit unknown";
1282   }
1283 }
1284
1285 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1286   switch (CPUType) {
1287   case llvm::MachO::CPU_TYPE_I386:
1288     return Triple::x86;
1289   case llvm::MachO::CPU_TYPE_X86_64:
1290     return Triple::x86_64;
1291   case llvm::MachO::CPU_TYPE_ARM:
1292     return Triple::arm;
1293   case llvm::MachO::CPU_TYPE_POWERPC:
1294     return Triple::ppc;
1295   case llvm::MachO::CPU_TYPE_POWERPC64:
1296     return Triple::ppc64;
1297   default:
1298     return Triple::UnknownArch;
1299   }
1300 }
1301
1302 unsigned MachOObjectFile::getArch() const {
1303   return getArch(getCPUType(this));
1304 }
1305
1306 StringRef MachOObjectFile::getLoadName() const {
1307   // TODO: Implement
1308   report_fatal_error("get_load_name() unimplemented in MachOObjectFile");
1309 }
1310
1311 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
1312   DataRefImpl DRI;
1313   DRI.d.a = Index;
1314   return section_rel_begin(DRI);
1315 }
1316
1317 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
1318   DataRefImpl DRI;
1319   DRI.d.a = Index;
1320   return section_rel_end(DRI);
1321 }
1322
1323 dice_iterator MachOObjectFile::begin_dices() const {
1324   DataRefImpl DRI;
1325   if (!DataInCodeLoadCmd)
1326     return dice_iterator(DiceRef(DRI, this));
1327
1328   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1329   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
1330   return dice_iterator(DiceRef(DRI, this));
1331 }
1332
1333 dice_iterator MachOObjectFile::end_dices() const {
1334   DataRefImpl DRI;
1335   if (!DataInCodeLoadCmd)
1336     return dice_iterator(DiceRef(DRI, this));
1337
1338   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1339   unsigned Offset = DicLC.dataoff + DicLC.datasize;
1340   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1341   return dice_iterator(DiceRef(DRI, this));
1342 }
1343
1344 StringRef
1345 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1346   ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1347   return parseSegmentOrSectionName(Raw.data());
1348 }
1349
1350 ArrayRef<char>
1351 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
1352   const section_base *Base =
1353     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1354   return ArrayRef<char>(Base->sectname);
1355 }
1356
1357 ArrayRef<char>
1358 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
1359   const section_base *Base =
1360     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1361   return ArrayRef<char>(Base->segname);
1362 }
1363
1364 bool
1365 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
1366   const {
1367   if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
1368     return false;
1369   return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
1370 }
1371
1372 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
1373     const MachO::any_relocation_info &RE) const {
1374   if (isLittleEndian())
1375     return RE.r_word1 & 0xffffff;
1376   return RE.r_word1 >> 8;
1377 }
1378
1379 bool MachOObjectFile::getPlainRelocationExternal(
1380     const MachO::any_relocation_info &RE) const {
1381   if (isLittleEndian())
1382     return (RE.r_word1 >> 27) & 1;
1383   return (RE.r_word1 >> 4) & 1;
1384 }
1385
1386 bool MachOObjectFile::getScatteredRelocationScattered(
1387     const MachO::any_relocation_info &RE) const {
1388   return RE.r_word0 >> 31;
1389 }
1390
1391 uint32_t MachOObjectFile::getScatteredRelocationValue(
1392     const MachO::any_relocation_info &RE) const {
1393   return RE.r_word1;
1394 }
1395
1396 unsigned MachOObjectFile::getAnyRelocationAddress(
1397     const MachO::any_relocation_info &RE) const {
1398   if (isRelocationScattered(RE))
1399     return getScatteredRelocationAddress(RE);
1400   return getPlainRelocationAddress(RE);
1401 }
1402
1403 unsigned MachOObjectFile::getAnyRelocationPCRel(
1404     const MachO::any_relocation_info &RE) const {
1405   if (isRelocationScattered(RE))
1406     return getScatteredRelocationPCRel(this, RE);
1407   return getPlainRelocationPCRel(this, RE);
1408 }
1409
1410 unsigned MachOObjectFile::getAnyRelocationLength(
1411     const MachO::any_relocation_info &RE) const {
1412   if (isRelocationScattered(RE))
1413     return getScatteredRelocationLength(RE);
1414   return getPlainRelocationLength(this, RE);
1415 }
1416
1417 unsigned
1418 MachOObjectFile::getAnyRelocationType(
1419                                    const MachO::any_relocation_info &RE) const {
1420   if (isRelocationScattered(RE))
1421     return getScatteredRelocationType(RE);
1422   return getPlainRelocationType(this, RE);
1423 }
1424
1425 SectionRef
1426 MachOObjectFile::getRelocationSection(
1427                                    const MachO::any_relocation_info &RE) const {
1428   if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
1429     return *end_sections();
1430   unsigned SecNum = getPlainRelocationSymbolNum(RE) - 1;
1431   DataRefImpl DRI;
1432   DRI.d.a = SecNum;
1433   return SectionRef(DRI, this);
1434 }
1435
1436 MachOObjectFile::LoadCommandInfo
1437 MachOObjectFile::getFirstLoadCommandInfo() const {
1438   MachOObjectFile::LoadCommandInfo Load;
1439
1440   unsigned HeaderSize = is64Bit() ? sizeof(MachO::mach_header_64) :
1441                                     sizeof(MachO::mach_header);
1442   Load.Ptr = getPtr(this, HeaderSize);
1443   Load.C = getStruct<MachO::load_command>(this, Load.Ptr);
1444   return Load;
1445 }
1446
1447 MachOObjectFile::LoadCommandInfo
1448 MachOObjectFile::getNextLoadCommandInfo(const LoadCommandInfo &L) const {
1449   MachOObjectFile::LoadCommandInfo Next;
1450   Next.Ptr = L.Ptr + L.C.cmdsize;
1451   Next.C = getStruct<MachO::load_command>(this, Next.Ptr);
1452   return Next;
1453 }
1454
1455 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
1456   return getStruct<MachO::section>(this, Sections[DRI.d.a]);
1457 }
1458
1459 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
1460   return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
1461 }
1462
1463 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
1464                                            unsigned Index) const {
1465   const char *Sec = getSectionPtr(this, L, Index);
1466   return getStruct<MachO::section>(this, Sec);
1467 }
1468
1469 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
1470                                                 unsigned Index) const {
1471   const char *Sec = getSectionPtr(this, L, Index);
1472   return getStruct<MachO::section_64>(this, Sec);
1473 }
1474
1475 MachO::nlist
1476 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
1477   const char *P = reinterpret_cast<const char *>(DRI.p);
1478   return getStruct<MachO::nlist>(this, P);
1479 }
1480
1481 MachO::nlist_64
1482 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
1483   const char *P = reinterpret_cast<const char *>(DRI.p);
1484   return getStruct<MachO::nlist_64>(this, P);
1485 }
1486
1487 MachO::linkedit_data_command
1488 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
1489   return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
1490 }
1491
1492 MachO::segment_command
1493 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
1494   return getStruct<MachO::segment_command>(this, L.Ptr);
1495 }
1496
1497 MachO::segment_command_64
1498 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
1499   return getStruct<MachO::segment_command_64>(this, L.Ptr);
1500 }
1501
1502 MachO::linker_options_command
1503 MachOObjectFile::getLinkerOptionsLoadCommand(const LoadCommandInfo &L) const {
1504   return getStruct<MachO::linker_options_command>(this, L.Ptr);
1505 }
1506
1507 MachO::any_relocation_info
1508 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
1509   const char *P = reinterpret_cast<const char *>(Rel.p);
1510   return getStruct<MachO::any_relocation_info>(this, P);
1511 }
1512
1513 MachO::data_in_code_entry
1514 MachOObjectFile::getDice(DataRefImpl Rel) const {
1515   const char *P = reinterpret_cast<const char *>(Rel.p);
1516   return getStruct<MachO::data_in_code_entry>(this, P);
1517 }
1518
1519 MachO::mach_header MachOObjectFile::getHeader() const {
1520   return getStruct<MachO::mach_header>(this, getPtr(this, 0));
1521 }
1522
1523 MachO::mach_header_64 MachOObjectFile::getHeader64() const {
1524   return getStruct<MachO::mach_header_64>(this, getPtr(this, 0));
1525 }
1526
1527 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
1528                                              const MachO::dysymtab_command &DLC,
1529                                              unsigned Index) const {
1530   uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
1531   return getStruct<uint32_t>(this, getPtr(this, Offset));
1532 }
1533
1534 MachO::data_in_code_entry
1535 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
1536                                          unsigned Index) const {
1537   uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
1538   return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
1539 }
1540
1541 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
1542   return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
1543 }
1544
1545 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
1546   return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
1547 }
1548
1549 MachO::linkedit_data_command
1550 MachOObjectFile::getDataInCodeLoadCommand() const {
1551   if (DataInCodeLoadCmd)
1552     return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
1553
1554   // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
1555   MachO::linkedit_data_command Cmd;
1556   Cmd.cmd = MachO::LC_DATA_IN_CODE;
1557   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
1558   Cmd.dataoff = 0;
1559   Cmd.datasize = 0;
1560   return Cmd;
1561 }
1562
1563 StringRef MachOObjectFile::getStringTableData() const {
1564   MachO::symtab_command S = getSymtabLoadCommand();
1565   return getData().substr(S.stroff, S.strsize);
1566 }
1567
1568 bool MachOObjectFile::is64Bit() const {
1569   return getType() == getMachOType(false, true) ||
1570     getType() == getMachOType(true, true);
1571 }
1572
1573 void MachOObjectFile::ReadULEB128s(uint64_t Index,
1574                                    SmallVectorImpl<uint64_t> &Out) const {
1575   DataExtractor extractor(ObjectFile::getData(), true, 0);
1576
1577   uint32_t offset = Index;
1578   uint64_t data = 0;
1579   while (uint64_t delta = extractor.getULEB128(&offset)) {
1580     data += delta;
1581     Out.push_back(data);
1582   }
1583 }
1584
1585 ErrorOr<ObjectFile *> ObjectFile::createMachOObjectFile(MemoryBuffer *Buffer) {
1586   StringRef Magic = Buffer->getBuffer().slice(0, 4);
1587   error_code EC;
1588   OwningPtr<MachOObjectFile> Ret;
1589   if (Magic == "\xFE\xED\xFA\xCE")
1590     Ret.reset(new MachOObjectFile(Buffer, false, false, EC));
1591   else if (Magic == "\xCE\xFA\xED\xFE")
1592     Ret.reset(new MachOObjectFile(Buffer, true, false, EC));
1593   else if (Magic == "\xFE\xED\xFA\xCF")
1594     Ret.reset(new MachOObjectFile(Buffer, false, true, EC));
1595   else if (Magic == "\xCF\xFA\xED\xFE")
1596     Ret.reset(new MachOObjectFile(Buffer, true, true, EC));
1597   else {
1598     delete Buffer;
1599     return object_error::parse_failed;
1600   }
1601
1602   if (EC)
1603     return EC;
1604   return Ret.take();
1605 }
1606
1607 } // end namespace object
1608 } // end namespace llvm