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