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