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