9763fabca82390f053b67cd4130ddaed4feea37d
[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/STLExtras.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Support/DataExtractor.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/Host.h"
23 #include "llvm/Support/LEB128.h"
24 #include "llvm/Support/MachO.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <cctype>
28 #include <cstring>
29 #include <limits>
30
31 using namespace llvm;
32 using namespace object;
33
34 namespace {
35   struct section_base {
36     char sectname[16];
37     char segname[16];
38   };
39 }
40
41 // FIXME: Replace all uses of this function with getStructOrErr.
42 template <typename T>
43 static T getStruct(const MachOObjectFile *O, const char *P) {
44   // Don't read before the beginning or past the end of the file
45   if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
46     report_fatal_error("Malformed MachO file.");
47
48   T Cmd;
49   memcpy(&Cmd, P, sizeof(T));
50   if (O->isLittleEndian() != sys::IsLittleEndianHost)
51     MachO::swapStruct(Cmd);
52   return Cmd;
53 }
54
55 template <typename T>
56 static ErrorOr<T> getStructOrErr(const MachOObjectFile *O, const char *P) {
57   // Don't read before the beginning or past the end of the file
58   if (P < O->getData().begin() || P + sizeof(T) > O->getData().end())
59     return object_error::parse_failed;
60
61   T Cmd;
62   memcpy(&Cmd, P, sizeof(T));
63   if (O->isLittleEndian() != sys::IsLittleEndianHost)
64     MachO::swapStruct(Cmd);
65   return Cmd;
66 }
67
68 static const char *
69 getSectionPtr(const MachOObjectFile *O, MachOObjectFile::LoadCommandInfo L,
70               unsigned Sec) {
71   uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
72
73   bool Is64 = O->is64Bit();
74   unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
75                                     sizeof(MachO::segment_command);
76   unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
77                                 sizeof(MachO::section);
78
79   uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
80   return reinterpret_cast<const char*>(SectionAddr);
81 }
82
83 static const char *getPtr(const MachOObjectFile *O, size_t Offset) {
84   return O->getData().substr(Offset, 1).data();
85 }
86
87 static MachO::nlist_base
88 getSymbolTableEntryBase(const MachOObjectFile *O, DataRefImpl DRI) {
89   const char *P = reinterpret_cast<const char *>(DRI.p);
90   return getStruct<MachO::nlist_base>(O, P);
91 }
92
93 static StringRef parseSegmentOrSectionName(const char *P) {
94   if (P[15] == 0)
95     // Null terminated.
96     return P;
97   // Not null terminated, so this is a 16 char string.
98   return StringRef(P, 16);
99 }
100
101 // Helper to advance a section or symbol iterator multiple increments at a time.
102 template<class T>
103 static void advance(T &it, size_t Val) {
104   while (Val--)
105     ++it;
106 }
107
108 static unsigned getCPUType(const MachOObjectFile *O) {
109   return O->getHeader().cputype;
110 }
111
112 static uint32_t
113 getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
114   return RE.r_word0;
115 }
116
117 static unsigned
118 getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
119   return RE.r_word0 & 0xffffff;
120 }
121
122 static bool getPlainRelocationPCRel(const MachOObjectFile *O,
123                                     const MachO::any_relocation_info &RE) {
124   if (O->isLittleEndian())
125     return (RE.r_word1 >> 24) & 1;
126   return (RE.r_word1 >> 7) & 1;
127 }
128
129 static bool
130 getScatteredRelocationPCRel(const MachOObjectFile *O,
131                             const MachO::any_relocation_info &RE) {
132   return (RE.r_word0 >> 30) & 1;
133 }
134
135 static unsigned getPlainRelocationLength(const MachOObjectFile *O,
136                                          const MachO::any_relocation_info &RE) {
137   if (O->isLittleEndian())
138     return (RE.r_word1 >> 25) & 3;
139   return (RE.r_word1 >> 5) & 3;
140 }
141
142 static unsigned
143 getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
144   return (RE.r_word0 >> 28) & 3;
145 }
146
147 static unsigned getPlainRelocationType(const MachOObjectFile *O,
148                                        const MachO::any_relocation_info &RE) {
149   if (O->isLittleEndian())
150     return RE.r_word1 >> 28;
151   return RE.r_word1 & 0xf;
152 }
153
154 static uint32_t getSectionFlags(const MachOObjectFile *O,
155                                 DataRefImpl Sec) {
156   if (O->is64Bit()) {
157     MachO::section_64 Sect = O->getSection64(Sec);
158     return Sect.flags;
159   }
160   MachO::section Sect = O->getSection(Sec);
161   return Sect.flags;
162 }
163
164 static ErrorOr<MachOObjectFile::LoadCommandInfo>
165 getLoadCommandInfo(const MachOObjectFile *Obj, const char *Ptr) {
166   auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr);
167   if (!CmdOrErr)
168     return CmdOrErr.getError();
169   if (CmdOrErr->cmdsize < 8)
170     return object_error::macho_small_load_command;
171   MachOObjectFile::LoadCommandInfo Load;
172   Load.Ptr = Ptr;
173   Load.C = CmdOrErr.get();
174   return Load;
175 }
176
177 static ErrorOr<MachOObjectFile::LoadCommandInfo>
178 getFirstLoadCommandInfo(const MachOObjectFile *Obj) {
179   unsigned HeaderSize = Obj->is64Bit() ? sizeof(MachO::mach_header_64)
180                                        : sizeof(MachO::mach_header);
181   return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize));
182 }
183
184 static ErrorOr<MachOObjectFile::LoadCommandInfo>
185 getNextLoadCommandInfo(const MachOObjectFile *Obj,
186                        const MachOObjectFile::LoadCommandInfo &L) {
187   return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize);
188 }
189
190 template <typename T>
191 static void parseHeader(const MachOObjectFile *Obj, T &Header,
192                         std::error_code &EC) {
193   auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0));
194   if (HeaderOrErr)
195     Header = HeaderOrErr.get();
196   else
197     EC = HeaderOrErr.getError();
198 }
199
200 // Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
201 // sections to \param Sections, and optionally sets
202 // \param IsPageZeroSegment to true.
203 template <typename SegmentCmd>
204 static std::error_code parseSegmentLoadCommand(
205     const MachOObjectFile *Obj, const MachOObjectFile::LoadCommandInfo &Load,
206     SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment) {
207   const unsigned SegmentLoadSize = sizeof(SegmentCmd);
208   if (Load.C.cmdsize < SegmentLoadSize)
209     return object_error::macho_load_segment_too_small;
210   auto SegOrErr = getStructOrErr<SegmentCmd>(Obj, Load.Ptr);
211   if (!SegOrErr)
212     return SegOrErr.getError();
213   SegmentCmd S = SegOrErr.get();
214   const unsigned SectionSize =
215       Obj->is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section);
216   if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
217       S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
218     return object_error::macho_load_segment_too_many_sections;
219   for (unsigned J = 0; J < S.nsects; ++J) {
220     const char *Sec = getSectionPtr(Obj, Load, J);
221     Sections.push_back(Sec);
222   }
223   IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
224   return std::error_code();
225 }
226
227 MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
228                                  bool Is64bits, std::error_code &EC)
229     : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
230       SymtabLoadCmd(nullptr), DysymtabLoadCmd(nullptr),
231       DataInCodeLoadCmd(nullptr), LinkOptHintsLoadCmd(nullptr),
232       DyldInfoLoadCmd(nullptr), UuidLoadCmd(nullptr),
233       HasPageZeroSegment(false) {
234   if (is64Bit())
235     parseHeader(this, Header64, EC);
236   else
237     parseHeader(this, Header, EC);
238   if (EC)
239     return;
240
241   uint32_t LoadCommandCount = getHeader().ncmds;
242   if (LoadCommandCount == 0)
243     return;
244
245   auto LoadOrErr = getFirstLoadCommandInfo(this);
246   if (!LoadOrErr) {
247     EC = LoadOrErr.getError();
248     return;
249   }
250   LoadCommandInfo Load = LoadOrErr.get();
251   for (unsigned I = 0; I < LoadCommandCount; ++I) {
252     LoadCommands.push_back(Load);
253     if (Load.C.cmd == MachO::LC_SYMTAB) {
254       // Multiple symbol tables
255       if (SymtabLoadCmd) {
256         EC = object_error::parse_failed;
257         return;
258       }
259       SymtabLoadCmd = Load.Ptr;
260     } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
261       // Multiple dynamic symbol tables
262       if (DysymtabLoadCmd) {
263         EC = object_error::parse_failed;
264         return;
265       }
266       DysymtabLoadCmd = Load.Ptr;
267     } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
268       // Multiple data in code tables
269       if (DataInCodeLoadCmd) {
270         EC = object_error::parse_failed;
271         return;
272       }
273       DataInCodeLoadCmd = Load.Ptr;
274     } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
275       // Multiple linker optimization hint tables
276       if (LinkOptHintsLoadCmd) {
277         EC = object_error::parse_failed;
278         return;
279       }
280       LinkOptHintsLoadCmd = Load.Ptr;
281     } else if (Load.C.cmd == MachO::LC_DYLD_INFO || 
282                Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
283       // Multiple dyldinfo load commands
284       if (DyldInfoLoadCmd) {
285         EC = object_error::parse_failed;
286         return;
287       }
288       DyldInfoLoadCmd = Load.Ptr;
289     } else if (Load.C.cmd == MachO::LC_UUID) {
290       // Multiple UUID load commands
291       if (UuidLoadCmd) {
292         EC = object_error::parse_failed;
293         return;
294       }
295       UuidLoadCmd = Load.Ptr;
296     } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
297       if ((EC = parseSegmentLoadCommand<MachO::segment_command_64>(
298                this, Load, Sections, HasPageZeroSegment)))
299         return;
300     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
301       if ((EC = parseSegmentLoadCommand<MachO::segment_command>(
302                this, Load, Sections, HasPageZeroSegment)))
303         return;
304     } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB ||
305                Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
306                Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
307                Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
308                Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
309       Libraries.push_back(Load.Ptr);
310     }
311     if (I < LoadCommandCount - 1) {
312       auto LoadOrErr = getNextLoadCommandInfo(this, Load);
313       if (!LoadOrErr) {
314         EC = LoadOrErr.getError();
315         return;
316       }
317       Load = LoadOrErr.get();
318     }
319   }
320   assert(LoadCommands.size() == LoadCommandCount);
321 }
322
323 void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
324   unsigned SymbolTableEntrySize = is64Bit() ?
325     sizeof(MachO::nlist_64) :
326     sizeof(MachO::nlist);
327   Symb.p += SymbolTableEntrySize;
328 }
329
330 std::error_code MachOObjectFile::getSymbolName(DataRefImpl Symb,
331                                                StringRef &Res) const {
332   StringRef StringTable = getStringTableData();
333   MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
334   const char *Start = &StringTable.data()[Entry.n_strx];
335   if (Start < getData().begin() || Start >= getData().end())
336     report_fatal_error(
337         "Symbol name entry points before beginning or past end of file.");
338   Res = StringRef(Start);
339   return std::error_code();
340 }
341
342 unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
343   DataRefImpl DRI = Sec.getRawDataRefImpl();
344   uint32_t Flags = getSectionFlags(this, DRI);
345   return Flags & MachO::SECTION_TYPE;
346 }
347
348 uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
349   if (is64Bit()) {
350     MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
351     return Entry.n_value;
352   }
353   MachO::nlist Entry = getSymbolTableEntry(Sym);
354   return Entry.n_value;
355 }
356
357 // getIndirectName() returns the name of the alias'ed symbol who's string table
358 // index is in the n_value field.
359 std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
360                                                  StringRef &Res) const {
361   StringRef StringTable = getStringTableData();
362   MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
363   if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
364     return object_error::parse_failed;
365   uint64_t NValue = getNValue(Symb);
366   if (NValue >= StringTable.size())
367     return object_error::parse_failed;
368   const char *Start = &StringTable.data()[NValue];
369   Res = StringRef(Start);
370   return std::error_code();
371 }
372
373 uint64_t MachOObjectFile::getSymbolValue(DataRefImpl Sym) const {
374   uint64_t NValue = getNValue(Sym);
375   MachO::nlist_base Entry = getSymbolTableEntryBase(this, Sym);
376   if ((Entry.n_type & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0)
377     return UnknownAddress;
378   return NValue;
379 }
380
381 std::error_code MachOObjectFile::getSymbolAddress(DataRefImpl Sym,
382                                                   uint64_t &Res) const {
383   Res = getSymbolValue(Sym);
384   return std::error_code();
385 }
386
387 uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
388   uint32_t flags = getSymbolFlags(DRI);
389   if (flags & SymbolRef::SF_Common) {
390     MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
391     return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
392   }
393   return 0;
394 }
395
396 uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
397   uint64_t Value;
398   getSymbolAddress(DRI, Value);
399   return Value;
400 }
401
402 SymbolRef::Type MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
403   MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
404   uint8_t n_type = Entry.n_type;
405
406   // If this is a STAB debugging symbol, we can do nothing more.
407   if (n_type & MachO::N_STAB)
408     return SymbolRef::ST_Debug;
409
410   switch (n_type & MachO::N_TYPE) {
411     case MachO::N_UNDF :
412       return SymbolRef::ST_Unknown;
413     case MachO::N_SECT :
414       return SymbolRef::ST_Function;
415   }
416   return SymbolRef::ST_Other;
417 }
418
419 uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
420   MachO::nlist_base Entry = getSymbolTableEntryBase(this, DRI);
421
422   uint8_t MachOType = Entry.n_type;
423   uint16_t MachOFlags = Entry.n_desc;
424
425   uint32_t Result = SymbolRef::SF_None;
426
427   if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF)
428     Result |= SymbolRef::SF_Undefined;
429
430   if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
431     Result |= SymbolRef::SF_Indirect;
432
433   if (MachOType & MachO::N_STAB)
434     Result |= SymbolRef::SF_FormatSpecific;
435
436   if (MachOType & MachO::N_EXT) {
437     Result |= SymbolRef::SF_Global;
438     if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
439       uint64_t Value;
440       getSymbolAddress(DRI, Value);
441       if (Value && Value != UnknownAddress)
442         Result |= SymbolRef::SF_Common;
443     }
444
445     if (!(MachOType & MachO::N_PEXT))
446       Result |= SymbolRef::SF_Exported;
447   }
448
449   if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
450     Result |= SymbolRef::SF_Weak;
451
452   if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
453     Result |= SymbolRef::SF_Thumb;
454
455   if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
456     Result |= SymbolRef::SF_Absolute;
457
458   return Result;
459 }
460
461 std::error_code MachOObjectFile::getSymbolSection(DataRefImpl Symb,
462                                                   section_iterator &Res) const {
463   MachO::nlist_base Entry = getSymbolTableEntryBase(this, Symb);
464   uint8_t index = Entry.n_sect;
465
466   if (index == 0) {
467     Res = section_end();
468   } else {
469     DataRefImpl DRI;
470     DRI.d.a = index - 1;
471     if (DRI.d.a >= Sections.size())
472       report_fatal_error("getSymbolSection: Invalid section index.");
473     Res = section_iterator(SectionRef(DRI, this));
474   }
475
476   return std::error_code();
477 }
478
479 unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
480   MachO::nlist_base Entry =
481       getSymbolTableEntryBase(this, Sym.getRawDataRefImpl());
482   return Entry.n_sect - 1;
483 }
484
485 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
486   Sec.d.a++;
487 }
488
489 std::error_code MachOObjectFile::getSectionName(DataRefImpl Sec,
490                                                 StringRef &Result) const {
491   ArrayRef<char> Raw = getSectionRawName(Sec);
492   Result = parseSegmentOrSectionName(Raw.data());
493   return std::error_code();
494 }
495
496 uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
497   if (is64Bit())
498     return getSection64(Sec).addr;
499   return getSection(Sec).addr;
500 }
501
502 uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
503   if (is64Bit())
504     return getSection64(Sec).size;
505   return getSection(Sec).size;
506 }
507
508 std::error_code MachOObjectFile::getSectionContents(DataRefImpl Sec,
509                                                     StringRef &Res) const {
510   uint32_t Offset;
511   uint64_t Size;
512
513   if (is64Bit()) {
514     MachO::section_64 Sect = getSection64(Sec);
515     Offset = Sect.offset;
516     Size = Sect.size;
517   } else {
518     MachO::section Sect = getSection(Sec);
519     Offset = Sect.offset;
520     Size = Sect.size;
521   }
522
523   Res = this->getData().substr(Offset, Size);
524   return std::error_code();
525 }
526
527 uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
528   uint32_t Align;
529   if (is64Bit()) {
530     MachO::section_64 Sect = getSection64(Sec);
531     Align = Sect.align;
532   } else {
533     MachO::section Sect = getSection(Sec);
534     Align = Sect.align;
535   }
536
537   return uint64_t(1) << Align;
538 }
539
540 bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
541   uint32_t Flags = getSectionFlags(this, Sec);
542   return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
543 }
544
545 bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
546   uint32_t Flags = getSectionFlags(this, Sec);
547   unsigned SectionType = Flags & MachO::SECTION_TYPE;
548   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
549          !(SectionType == MachO::S_ZEROFILL ||
550            SectionType == MachO::S_GB_ZEROFILL);
551 }
552
553 bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
554   uint32_t Flags = getSectionFlags(this, Sec);
555   unsigned SectionType = Flags & MachO::SECTION_TYPE;
556   return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
557          (SectionType == MachO::S_ZEROFILL ||
558           SectionType == MachO::S_GB_ZEROFILL);
559 }
560
561 unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
562   return Sec.getRawDataRefImpl().d.a;
563 }
564
565 bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
566   // FIXME: Unimplemented.
567   return false;
568 }
569
570 bool MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec,
571                                             DataRefImpl Symb) const {
572   SymbolRef::Type ST = getSymbolType(Symb);
573   if (ST == SymbolRef::ST_Unknown)
574     return false;
575
576   uint64_t SectBegin = getSectionAddress(Sec);
577   uint64_t SectEnd = getSectionSize(Sec);
578   SectEnd += SectBegin;
579
580   uint64_t SymAddr;
581   getSymbolAddress(Symb, SymAddr);
582   return (SymAddr >= SectBegin) && (SymAddr < SectEnd);
583 }
584
585 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
586   DataRefImpl Ret;
587   Ret.d.a = Sec.d.a;
588   Ret.d.b = 0;
589   return relocation_iterator(RelocationRef(Ret, this));
590 }
591
592 relocation_iterator
593 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
594   uint32_t Num;
595   if (is64Bit()) {
596     MachO::section_64 Sect = getSection64(Sec);
597     Num = Sect.nreloc;
598   } else {
599     MachO::section Sect = getSection(Sec);
600     Num = Sect.nreloc;
601   }
602
603   DataRefImpl Ret;
604   Ret.d.a = Sec.d.a;
605   Ret.d.b = Num;
606   return relocation_iterator(RelocationRef(Ret, this));
607 }
608
609 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
610   ++Rel.d.b;
611 }
612
613 std::error_code MachOObjectFile::getRelocationAddress(DataRefImpl Rel,
614                                                       uint64_t &Res) const {
615   uint64_t Offset = getRelocationOffset(Rel);
616
617   DataRefImpl Sec;
618   Sec.d.a = Rel.d.a;
619   uint64_t SecAddress = getSectionAddress(Sec);
620   Res = SecAddress + Offset;
621   return std::error_code();
622 }
623
624 uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
625   assert(getHeader().filetype == MachO::MH_OBJECT &&
626          "Only implemented for MH_OBJECT");
627   MachO::any_relocation_info RE = getRelocation(Rel);
628   return getAnyRelocationAddress(RE);
629 }
630
631 symbol_iterator
632 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
633   MachO::any_relocation_info RE = getRelocation(Rel);
634   if (isRelocationScattered(RE))
635     return symbol_end();
636
637   uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
638   bool isExtern = getPlainRelocationExternal(RE);
639   if (!isExtern)
640     return symbol_end();
641
642   MachO::symtab_command S = getSymtabLoadCommand();
643   unsigned SymbolTableEntrySize = is64Bit() ?
644     sizeof(MachO::nlist_64) :
645     sizeof(MachO::nlist);
646   uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
647   DataRefImpl Sym;
648   Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
649   return symbol_iterator(SymbolRef(Sym, this));
650 }
651
652 section_iterator
653 MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
654   return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
655 }
656
657 uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
658   MachO::any_relocation_info RE = getRelocation(Rel);
659   return getAnyRelocationType(RE);
660 }
661
662 std::error_code
663 MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
664                                        SmallVectorImpl<char> &Result) const {
665   StringRef res;
666   uint64_t RType = getRelocationType(Rel);
667
668   unsigned Arch = this->getArch();
669
670   switch (Arch) {
671     case Triple::x86: {
672       static const char *const Table[] =  {
673         "GENERIC_RELOC_VANILLA",
674         "GENERIC_RELOC_PAIR",
675         "GENERIC_RELOC_SECTDIFF",
676         "GENERIC_RELOC_PB_LA_PTR",
677         "GENERIC_RELOC_LOCAL_SECTDIFF",
678         "GENERIC_RELOC_TLV" };
679
680       if (RType > 5)
681         res = "Unknown";
682       else
683         res = Table[RType];
684       break;
685     }
686     case Triple::x86_64: {
687       static const char *const Table[] =  {
688         "X86_64_RELOC_UNSIGNED",
689         "X86_64_RELOC_SIGNED",
690         "X86_64_RELOC_BRANCH",
691         "X86_64_RELOC_GOT_LOAD",
692         "X86_64_RELOC_GOT",
693         "X86_64_RELOC_SUBTRACTOR",
694         "X86_64_RELOC_SIGNED_1",
695         "X86_64_RELOC_SIGNED_2",
696         "X86_64_RELOC_SIGNED_4",
697         "X86_64_RELOC_TLV" };
698
699       if (RType > 9)
700         res = "Unknown";
701       else
702         res = Table[RType];
703       break;
704     }
705     case Triple::arm: {
706       static const char *const Table[] =  {
707         "ARM_RELOC_VANILLA",
708         "ARM_RELOC_PAIR",
709         "ARM_RELOC_SECTDIFF",
710         "ARM_RELOC_LOCAL_SECTDIFF",
711         "ARM_RELOC_PB_LA_PTR",
712         "ARM_RELOC_BR24",
713         "ARM_THUMB_RELOC_BR22",
714         "ARM_THUMB_32BIT_BRANCH",
715         "ARM_RELOC_HALF",
716         "ARM_RELOC_HALF_SECTDIFF" };
717
718       if (RType > 9)
719         res = "Unknown";
720       else
721         res = Table[RType];
722       break;
723     }
724     case Triple::aarch64: {
725       static const char *const Table[] = {
726         "ARM64_RELOC_UNSIGNED",           "ARM64_RELOC_SUBTRACTOR",
727         "ARM64_RELOC_BRANCH26",           "ARM64_RELOC_PAGE21",
728         "ARM64_RELOC_PAGEOFF12",          "ARM64_RELOC_GOT_LOAD_PAGE21",
729         "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
730         "ARM64_RELOC_TLVP_LOAD_PAGE21",   "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
731         "ARM64_RELOC_ADDEND"
732       };
733
734       if (RType >= array_lengthof(Table))
735         res = "Unknown";
736       else
737         res = Table[RType];
738       break;
739     }
740     case Triple::ppc: {
741       static const char *const Table[] =  {
742         "PPC_RELOC_VANILLA",
743         "PPC_RELOC_PAIR",
744         "PPC_RELOC_BR14",
745         "PPC_RELOC_BR24",
746         "PPC_RELOC_HI16",
747         "PPC_RELOC_LO16",
748         "PPC_RELOC_HA16",
749         "PPC_RELOC_LO14",
750         "PPC_RELOC_SECTDIFF",
751         "PPC_RELOC_PB_LA_PTR",
752         "PPC_RELOC_HI16_SECTDIFF",
753         "PPC_RELOC_LO16_SECTDIFF",
754         "PPC_RELOC_HA16_SECTDIFF",
755         "PPC_RELOC_JBSR",
756         "PPC_RELOC_LO14_SECTDIFF",
757         "PPC_RELOC_LOCAL_SECTDIFF" };
758
759       if (RType > 15)
760         res = "Unknown";
761       else
762         res = Table[RType];
763       break;
764     }
765     case Triple::UnknownArch:
766       res = "Unknown";
767       break;
768   }
769   Result.append(res.begin(), res.end());
770   return std::error_code();
771 }
772
773 uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
774   MachO::any_relocation_info RE = getRelocation(Rel);
775   return getAnyRelocationLength(RE);
776 }
777
778 //
779 // guessLibraryShortName() is passed a name of a dynamic library and returns a
780 // guess on what the short name is.  Then name is returned as a substring of the
781 // StringRef Name passed in.  The name of the dynamic library is recognized as
782 // a framework if it has one of the two following forms:
783 //      Foo.framework/Versions/A/Foo
784 //      Foo.framework/Foo
785 // Where A and Foo can be any string.  And may contain a trailing suffix
786 // starting with an underbar.  If the Name is recognized as a framework then
787 // isFramework is set to true else it is set to false.  If the Name has a
788 // suffix then Suffix is set to the substring in Name that contains the suffix
789 // else it is set to a NULL StringRef.
790 //
791 // The Name of the dynamic library is recognized as a library name if it has
792 // one of the two following forms:
793 //      libFoo.A.dylib
794 //      libFoo.dylib
795 // The library may have a suffix trailing the name Foo of the form:
796 //      libFoo_profile.A.dylib
797 //      libFoo_profile.dylib
798 //
799 // The Name of the dynamic library is also recognized as a library name if it
800 // has the following form:
801 //      Foo.qtx
802 //
803 // If the Name of the dynamic library is none of the forms above then a NULL
804 // StringRef is returned.
805 //
806 StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
807                                                  bool &isFramework,
808                                                  StringRef &Suffix) {
809   StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
810   size_t a, b, c, d, Idx;
811
812   isFramework = false;
813   Suffix = StringRef();
814
815   // Pull off the last component and make Foo point to it
816   a = Name.rfind('/');
817   if (a == Name.npos || a == 0)
818     goto guess_library;
819   Foo = Name.slice(a+1, Name.npos);
820
821   // Look for a suffix starting with a '_'
822   Idx = Foo.rfind('_');
823   if (Idx != Foo.npos && Foo.size() >= 2) {
824     Suffix = Foo.slice(Idx, Foo.npos);
825     Foo = Foo.slice(0, Idx);
826   }
827
828   // First look for the form Foo.framework/Foo
829   b = Name.rfind('/', a);
830   if (b == Name.npos)
831     Idx = 0;
832   else
833     Idx = b+1;
834   F = Name.slice(Idx, Idx + Foo.size());
835   DotFramework = Name.slice(Idx + Foo.size(),
836                             Idx + Foo.size() + sizeof(".framework/")-1);
837   if (F == Foo && DotFramework == ".framework/") {
838     isFramework = true;
839     return Foo;
840   }
841
842   // Next look for the form Foo.framework/Versions/A/Foo
843   if (b == Name.npos)
844     goto guess_library;
845   c =  Name.rfind('/', b);
846   if (c == Name.npos || c == 0)
847     goto guess_library;
848   V = Name.slice(c+1, Name.npos);
849   if (!V.startswith("Versions/"))
850     goto guess_library;
851   d =  Name.rfind('/', c);
852   if (d == Name.npos)
853     Idx = 0;
854   else
855     Idx = d+1;
856   F = Name.slice(Idx, Idx + Foo.size());
857   DotFramework = Name.slice(Idx + Foo.size(),
858                             Idx + Foo.size() + sizeof(".framework/")-1);
859   if (F == Foo && DotFramework == ".framework/") {
860     isFramework = true;
861     return Foo;
862   }
863
864 guess_library:
865   // pull off the suffix after the "." and make a point to it
866   a = Name.rfind('.');
867   if (a == Name.npos || a == 0)
868     return StringRef();
869   Dylib = Name.slice(a, Name.npos);
870   if (Dylib != ".dylib")
871     goto guess_qtx;
872
873   // First pull off the version letter for the form Foo.A.dylib if any.
874   if (a >= 3) {
875     Dot = Name.slice(a-2, a-1);
876     if (Dot == ".")
877       a = a - 2;
878   }
879
880   b = Name.rfind('/', a);
881   if (b == Name.npos)
882     b = 0;
883   else
884     b = b+1;
885   // ignore any suffix after an underbar like Foo_profile.A.dylib
886   Idx = Name.find('_', b);
887   if (Idx != Name.npos && Idx != b) {
888     Lib = Name.slice(b, Idx);
889     Suffix = Name.slice(Idx, a);
890   }
891   else
892     Lib = Name.slice(b, a);
893   // There are incorrect library names of the form:
894   // libATS.A_profile.dylib so check for these.
895   if (Lib.size() >= 3) {
896     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
897     if (Dot == ".")
898       Lib = Lib.slice(0, Lib.size()-2);
899   }
900   return Lib;
901
902 guess_qtx:
903   Qtx = Name.slice(a, Name.npos);
904   if (Qtx != ".qtx")
905     return StringRef();
906   b = Name.rfind('/', a);
907   if (b == Name.npos)
908     Lib = Name.slice(0, a);
909   else
910     Lib = Name.slice(b+1, a);
911   // There are library names of the form: QT.A.qtx so check for these.
912   if (Lib.size() >= 3) {
913     Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
914     if (Dot == ".")
915       Lib = Lib.slice(0, Lib.size()-2);
916   }
917   return Lib;
918 }
919
920 // getLibraryShortNameByIndex() is used to get the short name of the library
921 // for an undefined symbol in a linked Mach-O binary that was linked with the
922 // normal two-level namespace default (that is MH_TWOLEVEL in the header).
923 // It is passed the index (0 - based) of the library as translated from
924 // GET_LIBRARY_ORDINAL (1 - based).
925 std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
926                                                          StringRef &Res) const {
927   if (Index >= Libraries.size())
928     return object_error::parse_failed;
929
930   // If the cache of LibrariesShortNames is not built up do that first for
931   // all the Libraries.
932   if (LibrariesShortNames.size() == 0) {
933     for (unsigned i = 0; i < Libraries.size(); i++) {
934       MachO::dylib_command D =
935         getStruct<MachO::dylib_command>(this, Libraries[i]);
936       if (D.dylib.name >= D.cmdsize)
937         return object_error::parse_failed;
938       const char *P = (const char *)(Libraries[i]) + D.dylib.name;
939       StringRef Name = StringRef(P);
940       if (D.dylib.name+Name.size() >= D.cmdsize)
941         return object_error::parse_failed;
942       StringRef Suffix;
943       bool isFramework;
944       StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
945       if (shortName.empty())
946         LibrariesShortNames.push_back(Name);
947       else
948         LibrariesShortNames.push_back(shortName);
949     }
950   }
951
952   Res = LibrariesShortNames[Index];
953   return std::error_code();
954 }
955
956 basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
957   return getSymbolByIndex(0);
958 }
959
960 basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
961   DataRefImpl DRI;
962   if (!SymtabLoadCmd)
963     return basic_symbol_iterator(SymbolRef(DRI, this));
964
965   MachO::symtab_command Symtab = getSymtabLoadCommand();
966   unsigned SymbolTableEntrySize = is64Bit() ?
967     sizeof(MachO::nlist_64) :
968     sizeof(MachO::nlist);
969   unsigned Offset = Symtab.symoff +
970     Symtab.nsyms * SymbolTableEntrySize;
971   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
972   return basic_symbol_iterator(SymbolRef(DRI, this));
973 }
974
975 basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
976   DataRefImpl DRI;
977   if (!SymtabLoadCmd)
978     return basic_symbol_iterator(SymbolRef(DRI, this));
979
980   MachO::symtab_command Symtab = getSymtabLoadCommand();
981   if (Index >= Symtab.nsyms)
982     report_fatal_error("Requested symbol index is out of range.");
983   unsigned SymbolTableEntrySize =
984     is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
985   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
986   DRI.p += Index * SymbolTableEntrySize;
987   return basic_symbol_iterator(SymbolRef(DRI, this));
988 }
989
990 section_iterator MachOObjectFile::section_begin() const {
991   DataRefImpl DRI;
992   return section_iterator(SectionRef(DRI, this));
993 }
994
995 section_iterator MachOObjectFile::section_end() const {
996   DataRefImpl DRI;
997   DRI.d.a = Sections.size();
998   return section_iterator(SectionRef(DRI, this));
999 }
1000
1001 uint8_t MachOObjectFile::getBytesInAddress() const {
1002   return is64Bit() ? 8 : 4;
1003 }
1004
1005 StringRef MachOObjectFile::getFileFormatName() const {
1006   unsigned CPUType = getCPUType(this);
1007   if (!is64Bit()) {
1008     switch (CPUType) {
1009     case llvm::MachO::CPU_TYPE_I386:
1010       return "Mach-O 32-bit i386";
1011     case llvm::MachO::CPU_TYPE_ARM:
1012       return "Mach-O arm";
1013     case llvm::MachO::CPU_TYPE_POWERPC:
1014       return "Mach-O 32-bit ppc";
1015     default:
1016       return "Mach-O 32-bit unknown";
1017     }
1018   }
1019
1020   switch (CPUType) {
1021   case llvm::MachO::CPU_TYPE_X86_64:
1022     return "Mach-O 64-bit x86-64";
1023   case llvm::MachO::CPU_TYPE_ARM64:
1024     return "Mach-O arm64";
1025   case llvm::MachO::CPU_TYPE_POWERPC64:
1026     return "Mach-O 64-bit ppc64";
1027   default:
1028     return "Mach-O 64-bit unknown";
1029   }
1030 }
1031
1032 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1033   switch (CPUType) {
1034   case llvm::MachO::CPU_TYPE_I386:
1035     return Triple::x86;
1036   case llvm::MachO::CPU_TYPE_X86_64:
1037     return Triple::x86_64;
1038   case llvm::MachO::CPU_TYPE_ARM:
1039     return Triple::arm;
1040   case llvm::MachO::CPU_TYPE_ARM64:
1041     return Triple::aarch64;
1042   case llvm::MachO::CPU_TYPE_POWERPC:
1043     return Triple::ppc;
1044   case llvm::MachO::CPU_TYPE_POWERPC64:
1045     return Triple::ppc64;
1046   default:
1047     return Triple::UnknownArch;
1048   }
1049 }
1050
1051 Triple MachOObjectFile::getArch(uint32_t CPUType, uint32_t CPUSubType,
1052                                 const char **McpuDefault) {
1053   if (McpuDefault)
1054     *McpuDefault = nullptr;
1055
1056   switch (CPUType) {
1057   case MachO::CPU_TYPE_I386:
1058     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1059     case MachO::CPU_SUBTYPE_I386_ALL:
1060       return Triple("i386-apple-darwin");
1061     default:
1062       return Triple();
1063     }
1064   case MachO::CPU_TYPE_X86_64:
1065     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1066     case MachO::CPU_SUBTYPE_X86_64_ALL:
1067       return Triple("x86_64-apple-darwin");
1068     case MachO::CPU_SUBTYPE_X86_64_H:
1069       return Triple("x86_64h-apple-darwin");
1070     default:
1071       return Triple();
1072     }
1073   case MachO::CPU_TYPE_ARM:
1074     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1075     case MachO::CPU_SUBTYPE_ARM_V4T:
1076       return Triple("armv4t-apple-darwin");
1077     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1078       return Triple("armv5e-apple-darwin");
1079     case MachO::CPU_SUBTYPE_ARM_XSCALE:
1080       return Triple("xscale-apple-darwin");
1081     case MachO::CPU_SUBTYPE_ARM_V6:
1082       return Triple("armv6-apple-darwin");
1083     case MachO::CPU_SUBTYPE_ARM_V6M:
1084       if (McpuDefault)
1085         *McpuDefault = "cortex-m0";
1086       return Triple("armv6m-apple-darwin");
1087     case MachO::CPU_SUBTYPE_ARM_V7:
1088       return Triple("armv7-apple-darwin");
1089     case MachO::CPU_SUBTYPE_ARM_V7EM:
1090       if (McpuDefault)
1091         *McpuDefault = "cortex-m4";
1092       return Triple("armv7em-apple-darwin");
1093     case MachO::CPU_SUBTYPE_ARM_V7K:
1094       return Triple("armv7k-apple-darwin");
1095     case MachO::CPU_SUBTYPE_ARM_V7M:
1096       if (McpuDefault)
1097         *McpuDefault = "cortex-m3";
1098       return Triple("armv7m-apple-darwin");
1099     case MachO::CPU_SUBTYPE_ARM_V7S:
1100       return Triple("armv7s-apple-darwin");
1101     default:
1102       return Triple();
1103     }
1104   case MachO::CPU_TYPE_ARM64:
1105     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1106     case MachO::CPU_SUBTYPE_ARM64_ALL:
1107       return Triple("arm64-apple-darwin");
1108     default:
1109       return Triple();
1110     }
1111   case MachO::CPU_TYPE_POWERPC:
1112     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1113     case MachO::CPU_SUBTYPE_POWERPC_ALL:
1114       return Triple("ppc-apple-darwin");
1115     default:
1116       return Triple();
1117     }
1118   case MachO::CPU_TYPE_POWERPC64:
1119     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1120     case MachO::CPU_SUBTYPE_POWERPC_ALL:
1121       return Triple("ppc64-apple-darwin");
1122     default:
1123       return Triple();
1124     }
1125   default:
1126     return Triple();
1127   }
1128 }
1129
1130 Triple MachOObjectFile::getThumbArch(uint32_t CPUType, uint32_t CPUSubType,
1131                                      const char **McpuDefault) {
1132   if (McpuDefault)
1133     *McpuDefault = nullptr;
1134
1135   switch (CPUType) {
1136   case MachO::CPU_TYPE_ARM:
1137     switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
1138     case MachO::CPU_SUBTYPE_ARM_V4T:
1139       return Triple("thumbv4t-apple-darwin");
1140     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1141       return Triple("thumbv5e-apple-darwin");
1142     case MachO::CPU_SUBTYPE_ARM_XSCALE:
1143       return Triple("xscale-apple-darwin");
1144     case MachO::CPU_SUBTYPE_ARM_V6:
1145       return Triple("thumbv6-apple-darwin");
1146     case MachO::CPU_SUBTYPE_ARM_V6M:
1147       if (McpuDefault)
1148         *McpuDefault = "cortex-m0";
1149       return Triple("thumbv6m-apple-darwin");
1150     case MachO::CPU_SUBTYPE_ARM_V7:
1151       return Triple("thumbv7-apple-darwin");
1152     case MachO::CPU_SUBTYPE_ARM_V7EM:
1153       if (McpuDefault)
1154         *McpuDefault = "cortex-m4";
1155       return Triple("thumbv7em-apple-darwin");
1156     case MachO::CPU_SUBTYPE_ARM_V7K:
1157       return Triple("thumbv7k-apple-darwin");
1158     case MachO::CPU_SUBTYPE_ARM_V7M:
1159       if (McpuDefault)
1160         *McpuDefault = "cortex-m3";
1161       return Triple("thumbv7m-apple-darwin");
1162     case MachO::CPU_SUBTYPE_ARM_V7S:
1163       return Triple("thumbv7s-apple-darwin");
1164     default:
1165       return Triple();
1166     }
1167   default:
1168     return Triple();
1169   }
1170 }
1171
1172 Triple MachOObjectFile::getArch(uint32_t CPUType, uint32_t CPUSubType,
1173                                 const char **McpuDefault,
1174                                 Triple *ThumbTriple) {
1175   Triple T = MachOObjectFile::getArch(CPUType, CPUSubType, McpuDefault);
1176   *ThumbTriple = MachOObjectFile::getThumbArch(CPUType, CPUSubType,
1177                                                McpuDefault);
1178   return T;
1179 }
1180
1181 Triple MachOObjectFile::getHostArch() {
1182   return Triple(sys::getDefaultTargetTriple());
1183 }
1184
1185 bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
1186   return StringSwitch<bool>(ArchFlag)
1187       .Case("i386", true)
1188       .Case("x86_64", true)
1189       .Case("x86_64h", true)
1190       .Case("armv4t", true)
1191       .Case("arm", true)
1192       .Case("armv5e", true)
1193       .Case("armv6", true)
1194       .Case("armv6m", true)
1195       .Case("armv7", true)
1196       .Case("armv7em", true)
1197       .Case("armv7k", true)
1198       .Case("armv7m", true)
1199       .Case("armv7s", true)
1200       .Case("arm64", true)
1201       .Case("ppc", true)
1202       .Case("ppc64", true)
1203       .Default(false);
1204 }
1205
1206 unsigned MachOObjectFile::getArch() const {
1207   return getArch(getCPUType(this));
1208 }
1209
1210 Triple MachOObjectFile::getArch(const char **McpuDefault,
1211                                 Triple *ThumbTriple) const {
1212   *ThumbTriple = getThumbArch(Header.cputype, Header.cpusubtype, McpuDefault);
1213   return getArch(Header.cputype, Header.cpusubtype, McpuDefault);
1214 }
1215
1216 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
1217   DataRefImpl DRI;
1218   DRI.d.a = Index;
1219   return section_rel_begin(DRI);
1220 }
1221
1222 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
1223   DataRefImpl DRI;
1224   DRI.d.a = Index;
1225   return section_rel_end(DRI);
1226 }
1227
1228 dice_iterator MachOObjectFile::begin_dices() const {
1229   DataRefImpl DRI;
1230   if (!DataInCodeLoadCmd)
1231     return dice_iterator(DiceRef(DRI, this));
1232
1233   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1234   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
1235   return dice_iterator(DiceRef(DRI, this));
1236 }
1237
1238 dice_iterator MachOObjectFile::end_dices() const {
1239   DataRefImpl DRI;
1240   if (!DataInCodeLoadCmd)
1241     return dice_iterator(DiceRef(DRI, this));
1242
1243   MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1244   unsigned Offset = DicLC.dataoff + DicLC.datasize;
1245   DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1246   return dice_iterator(DiceRef(DRI, this));
1247 }
1248
1249 ExportEntry::ExportEntry(ArrayRef<uint8_t> T) 
1250   : Trie(T), Malformed(false), Done(false) { }
1251
1252 void ExportEntry::moveToFirst() {
1253   pushNode(0);
1254   pushDownUntilBottom();
1255 }
1256
1257 void ExportEntry::moveToEnd() {
1258   Stack.clear();
1259   Done = true;
1260 }
1261
1262 bool ExportEntry::operator==(const ExportEntry &Other) const {
1263   // Common case, one at end, other iterating from begin. 
1264   if (Done || Other.Done)
1265     return (Done == Other.Done);
1266   // Not equal if different stack sizes.
1267   if (Stack.size() != Other.Stack.size())
1268     return false;
1269   // Not equal if different cumulative strings.
1270   if (!CumulativeString.equals(Other.CumulativeString))
1271     return false;
1272   // Equal if all nodes in both stacks match.
1273   for (unsigned i=0; i < Stack.size(); ++i) {
1274     if (Stack[i].Start != Other.Stack[i].Start)
1275       return false;
1276   }
1277   return true;  
1278 }
1279
1280 uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr) {
1281   unsigned Count;
1282   uint64_t Result = decodeULEB128(Ptr, &Count);
1283   Ptr += Count;
1284   if (Ptr > Trie.end()) {
1285     Ptr = Trie.end();
1286     Malformed = true;
1287   }
1288   return Result;
1289 }
1290
1291 StringRef ExportEntry::name() const {
1292   return CumulativeString;
1293 }
1294
1295 uint64_t ExportEntry::flags() const {
1296   return Stack.back().Flags;
1297 }
1298
1299 uint64_t ExportEntry::address() const {
1300   return Stack.back().Address;
1301 }
1302
1303 uint64_t ExportEntry::other() const {
1304   return Stack.back().Other;
1305 }
1306
1307 StringRef ExportEntry::otherName() const {
1308   const char* ImportName = Stack.back().ImportName;
1309   if (ImportName)
1310     return StringRef(ImportName);
1311   return StringRef();
1312 }
1313
1314 uint32_t ExportEntry::nodeOffset() const {
1315   return Stack.back().Start - Trie.begin();
1316 }
1317
1318 ExportEntry::NodeState::NodeState(const uint8_t *Ptr) 
1319   : Start(Ptr), Current(Ptr), Flags(0), Address(0), Other(0), 
1320     ImportName(nullptr), ChildCount(0), NextChildIndex(0),  
1321     ParentStringLength(0), IsExportNode(false) {
1322 }
1323
1324 void ExportEntry::pushNode(uint64_t offset) {
1325   const uint8_t *Ptr = Trie.begin() + offset;
1326   NodeState State(Ptr);
1327   uint64_t ExportInfoSize = readULEB128(State.Current);
1328   State.IsExportNode = (ExportInfoSize != 0);
1329   const uint8_t* Children = State.Current + ExportInfoSize;
1330   if (State.IsExportNode) {
1331     State.Flags = readULEB128(State.Current);
1332     if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
1333       State.Address = 0;
1334       State.Other = readULEB128(State.Current); // dylib ordinal
1335       State.ImportName = reinterpret_cast<const char*>(State.Current);
1336     } else {
1337       State.Address = readULEB128(State.Current);
1338       if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
1339         State.Other = readULEB128(State.Current); 
1340     }
1341   }
1342   State.ChildCount = *Children;
1343   State.Current = Children + 1;
1344   State.NextChildIndex = 0;
1345   State.ParentStringLength = CumulativeString.size();
1346   Stack.push_back(State);
1347 }
1348
1349 void ExportEntry::pushDownUntilBottom() {
1350   while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
1351     NodeState &Top = Stack.back();
1352     CumulativeString.resize(Top.ParentStringLength);
1353     for (;*Top.Current != 0; Top.Current++) {
1354       char C = *Top.Current;
1355       CumulativeString.push_back(C);
1356     }
1357     Top.Current += 1;
1358     uint64_t childNodeIndex = readULEB128(Top.Current);
1359     Top.NextChildIndex += 1;
1360     pushNode(childNodeIndex);
1361   }
1362   if (!Stack.back().IsExportNode) {
1363     Malformed = true;
1364     moveToEnd();
1365   }
1366 }
1367
1368 // We have a trie data structure and need a way to walk it that is compatible
1369 // with the C++ iterator model. The solution is a non-recursive depth first
1370 // traversal where the iterator contains a stack of parent nodes along with a
1371 // string that is the accumulation of all edge strings along the parent chain
1372 // to this point.
1373 //
1374 // There is one "export" node for each exported symbol.  But because some
1375 // symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
1376 // node may have child nodes too.  
1377 //
1378 // The algorithm for moveNext() is to keep moving down the leftmost unvisited
1379 // child until hitting a node with no children (which is an export node or
1380 // else the trie is malformed). On the way down, each node is pushed on the
1381 // stack ivar.  If there is no more ways down, it pops up one and tries to go
1382 // down a sibling path until a childless node is reached.
1383 void ExportEntry::moveNext() {
1384   if (Stack.empty() || !Stack.back().IsExportNode) {
1385     Malformed = true;
1386     moveToEnd();
1387     return;
1388   }
1389
1390   Stack.pop_back();
1391   while (!Stack.empty()) {
1392     NodeState &Top = Stack.back();
1393     if (Top.NextChildIndex < Top.ChildCount) {
1394       pushDownUntilBottom();
1395       // Now at the next export node.
1396       return;
1397     } else {
1398       if (Top.IsExportNode) {
1399         // This node has no children but is itself an export node.
1400         CumulativeString.resize(Top.ParentStringLength);
1401         return;
1402       }
1403       Stack.pop_back();
1404     }
1405   }
1406   Done = true;
1407 }
1408
1409 iterator_range<export_iterator> 
1410 MachOObjectFile::exports(ArrayRef<uint8_t> Trie) {
1411   ExportEntry Start(Trie);
1412   if (Trie.size() == 0)
1413     Start.moveToEnd();
1414   else
1415     Start.moveToFirst();
1416
1417   ExportEntry Finish(Trie);
1418   Finish.moveToEnd();
1419
1420   return iterator_range<export_iterator>(export_iterator(Start), 
1421                                          export_iterator(Finish));
1422 }
1423
1424 iterator_range<export_iterator> MachOObjectFile::exports() const {
1425   return exports(getDyldInfoExportsTrie());
1426 }
1427
1428
1429 MachORebaseEntry::MachORebaseEntry(ArrayRef<uint8_t> Bytes, bool is64Bit)
1430     : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
1431       RemainingLoopCount(0), AdvanceAmount(0), RebaseType(0),
1432       PointerSize(is64Bit ? 8 : 4), Malformed(false), Done(false) {}
1433
1434 void MachORebaseEntry::moveToFirst() {
1435   Ptr = Opcodes.begin();
1436   moveNext();
1437 }
1438
1439 void MachORebaseEntry::moveToEnd() {
1440   Ptr = Opcodes.end();
1441   RemainingLoopCount = 0;
1442   Done = true;
1443 }
1444
1445 void MachORebaseEntry::moveNext() {
1446   // If in the middle of some loop, move to next rebasing in loop.
1447   SegmentOffset += AdvanceAmount;
1448   if (RemainingLoopCount) {
1449     --RemainingLoopCount;
1450     return;
1451   }
1452   if (Ptr == Opcodes.end()) {
1453     Done = true;
1454     return;
1455   }
1456   bool More = true;
1457   while (More && !Malformed) {
1458     // Parse next opcode and set up next loop.
1459     uint8_t Byte = *Ptr++;
1460     uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
1461     uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
1462     switch (Opcode) {
1463     case MachO::REBASE_OPCODE_DONE:
1464       More = false;
1465       Done = true;
1466       moveToEnd();
1467       DEBUG_WITH_TYPE("mach-o-rebase", llvm::dbgs() << "REBASE_OPCODE_DONE\n");
1468       break;
1469     case MachO::REBASE_OPCODE_SET_TYPE_IMM:
1470       RebaseType = ImmValue;
1471       DEBUG_WITH_TYPE(
1472           "mach-o-rebase",
1473           llvm::dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
1474                        << "RebaseType=" << (int) RebaseType << "\n");
1475       break;
1476     case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1477       SegmentIndex = ImmValue;
1478       SegmentOffset = readULEB128();
1479       DEBUG_WITH_TYPE(
1480           "mach-o-rebase",
1481           llvm::dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
1482                        << "SegmentIndex=" << SegmentIndex << ", "
1483                        << format("SegmentOffset=0x%06X", SegmentOffset)
1484                        << "\n");
1485       break;
1486     case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
1487       SegmentOffset += readULEB128();
1488       DEBUG_WITH_TYPE("mach-o-rebase",
1489                       llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
1490                                    << format("SegmentOffset=0x%06X",
1491                                              SegmentOffset) << "\n");
1492       break;
1493     case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
1494       SegmentOffset += ImmValue * PointerSize;
1495       DEBUG_WITH_TYPE("mach-o-rebase",
1496                       llvm::dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
1497                                    << format("SegmentOffset=0x%06X",
1498                                              SegmentOffset) << "\n");
1499       break;
1500     case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
1501       AdvanceAmount = PointerSize;
1502       RemainingLoopCount = ImmValue - 1;
1503       DEBUG_WITH_TYPE(
1504           "mach-o-rebase",
1505           llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
1506                        << format("SegmentOffset=0x%06X", SegmentOffset)
1507                        << ", AdvanceAmount=" << AdvanceAmount
1508                        << ", RemainingLoopCount=" << RemainingLoopCount
1509                        << "\n");
1510       return;
1511     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
1512       AdvanceAmount = PointerSize;
1513       RemainingLoopCount = readULEB128() - 1;
1514       DEBUG_WITH_TYPE(
1515           "mach-o-rebase",
1516           llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
1517                        << format("SegmentOffset=0x%06X", SegmentOffset)
1518                        << ", AdvanceAmount=" << AdvanceAmount
1519                        << ", RemainingLoopCount=" << RemainingLoopCount
1520                        << "\n");
1521       return;
1522     case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
1523       AdvanceAmount = readULEB128() + PointerSize;
1524       RemainingLoopCount = 0;
1525       DEBUG_WITH_TYPE(
1526           "mach-o-rebase",
1527           llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
1528                        << format("SegmentOffset=0x%06X", SegmentOffset)
1529                        << ", AdvanceAmount=" << AdvanceAmount
1530                        << ", RemainingLoopCount=" << RemainingLoopCount
1531                        << "\n");
1532       return;
1533     case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
1534       RemainingLoopCount = readULEB128() - 1;
1535       AdvanceAmount = readULEB128() + PointerSize;
1536       DEBUG_WITH_TYPE(
1537           "mach-o-rebase",
1538           llvm::dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
1539                        << format("SegmentOffset=0x%06X", SegmentOffset)
1540                        << ", AdvanceAmount=" << AdvanceAmount
1541                        << ", RemainingLoopCount=" << RemainingLoopCount
1542                        << "\n");
1543       return;
1544     default:
1545       Malformed = true;
1546     }
1547   }
1548 }
1549
1550 uint64_t MachORebaseEntry::readULEB128() {
1551   unsigned Count;
1552   uint64_t Result = decodeULEB128(Ptr, &Count);
1553   Ptr += Count;
1554   if (Ptr > Opcodes.end()) {
1555     Ptr = Opcodes.end();
1556     Malformed = true;
1557   }
1558   return Result;
1559 }
1560
1561 uint32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
1562
1563 uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
1564
1565 StringRef MachORebaseEntry::typeName() const {
1566   switch (RebaseType) {
1567   case MachO::REBASE_TYPE_POINTER:
1568     return "pointer";
1569   case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
1570     return "text abs32";
1571   case MachO::REBASE_TYPE_TEXT_PCREL32:
1572     return "text rel32";
1573   }
1574   return "unknown";
1575 }
1576
1577 bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
1578   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
1579   return (Ptr == Other.Ptr) &&
1580          (RemainingLoopCount == Other.RemainingLoopCount) &&
1581          (Done == Other.Done);
1582 }
1583
1584 iterator_range<rebase_iterator>
1585 MachOObjectFile::rebaseTable(ArrayRef<uint8_t> Opcodes, bool is64) {
1586   MachORebaseEntry Start(Opcodes, is64);
1587   Start.moveToFirst();
1588
1589   MachORebaseEntry Finish(Opcodes, is64);
1590   Finish.moveToEnd();
1591
1592   return iterator_range<rebase_iterator>(rebase_iterator(Start),
1593                                          rebase_iterator(Finish));
1594 }
1595
1596 iterator_range<rebase_iterator> MachOObjectFile::rebaseTable() const {
1597   return rebaseTable(getDyldInfoRebaseOpcodes(), is64Bit());
1598 }
1599
1600
1601 MachOBindEntry::MachOBindEntry(ArrayRef<uint8_t> Bytes, bool is64Bit,
1602                                Kind BK)
1603     : Opcodes(Bytes), Ptr(Bytes.begin()), SegmentOffset(0), SegmentIndex(0),
1604       Ordinal(0), Flags(0), Addend(0), RemainingLoopCount(0), AdvanceAmount(0),
1605       BindType(0), PointerSize(is64Bit ? 8 : 4),
1606       TableKind(BK), Malformed(false), Done(false) {}
1607
1608 void MachOBindEntry::moveToFirst() {
1609   Ptr = Opcodes.begin();
1610   moveNext();
1611 }
1612
1613 void MachOBindEntry::moveToEnd() {
1614   Ptr = Opcodes.end();
1615   RemainingLoopCount = 0;
1616   Done = true;
1617 }
1618
1619 void MachOBindEntry::moveNext() {
1620   // If in the middle of some loop, move to next binding in loop.
1621   SegmentOffset += AdvanceAmount;
1622   if (RemainingLoopCount) {
1623     --RemainingLoopCount;
1624     return;
1625   }
1626   if (Ptr == Opcodes.end()) {
1627     Done = true;
1628     return;
1629   }
1630   bool More = true;
1631   while (More && !Malformed) {
1632     // Parse next opcode and set up next loop.
1633     uint8_t Byte = *Ptr++;
1634     uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
1635     uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
1636     int8_t SignExtended;
1637     const uint8_t *SymStart;
1638     switch (Opcode) {
1639     case MachO::BIND_OPCODE_DONE:
1640       if (TableKind == Kind::Lazy) {
1641         // Lazying bindings have a DONE opcode between entries.  Need to ignore
1642         // it to advance to next entry.  But need not if this is last entry.
1643         bool NotLastEntry = false;
1644         for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
1645           if (*P) {
1646             NotLastEntry = true;
1647           }
1648         }
1649         if (NotLastEntry)
1650           break;
1651       }
1652       More = false;
1653       Done = true;
1654       moveToEnd();
1655       DEBUG_WITH_TYPE("mach-o-bind", llvm::dbgs() << "BIND_OPCODE_DONE\n");
1656       break;
1657     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
1658       Ordinal = ImmValue;
1659       DEBUG_WITH_TYPE(
1660           "mach-o-bind",
1661           llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
1662                        << "Ordinal=" << Ordinal << "\n");
1663       break;
1664     case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
1665       Ordinal = readULEB128();
1666       DEBUG_WITH_TYPE(
1667           "mach-o-bind",
1668           llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
1669                        << "Ordinal=" << Ordinal << "\n");
1670       break;
1671     case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
1672       if (ImmValue) {
1673         SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
1674         Ordinal = SignExtended;
1675       } else
1676         Ordinal = 0;
1677       DEBUG_WITH_TYPE(
1678           "mach-o-bind",
1679           llvm::dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
1680                        << "Ordinal=" << Ordinal << "\n");
1681       break;
1682     case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
1683       Flags = ImmValue;
1684       SymStart = Ptr;
1685       while (*Ptr) {
1686         ++Ptr;
1687       }
1688       SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
1689                              Ptr-SymStart);
1690       ++Ptr;
1691       DEBUG_WITH_TYPE(
1692           "mach-o-bind",
1693           llvm::dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
1694                        << "SymbolName=" << SymbolName << "\n");
1695       if (TableKind == Kind::Weak) {
1696         if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
1697           return;
1698       }
1699       break;
1700     case MachO::BIND_OPCODE_SET_TYPE_IMM:
1701       BindType = ImmValue;
1702       DEBUG_WITH_TYPE(
1703           "mach-o-bind",
1704           llvm::dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
1705                        << "BindType=" << (int)BindType << "\n");
1706       break;
1707     case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
1708       Addend = readSLEB128();
1709       if (TableKind == Kind::Lazy)
1710         Malformed = true;
1711       DEBUG_WITH_TYPE(
1712           "mach-o-bind",
1713           llvm::dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
1714                        << "Addend=" << Addend << "\n");
1715       break;
1716     case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
1717       SegmentIndex = ImmValue;
1718       SegmentOffset = readULEB128();
1719       DEBUG_WITH_TYPE(
1720           "mach-o-bind",
1721           llvm::dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
1722                        << "SegmentIndex=" << SegmentIndex << ", "
1723                        << format("SegmentOffset=0x%06X", SegmentOffset)
1724                        << "\n");
1725       break;
1726     case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
1727       SegmentOffset += readULEB128();
1728       DEBUG_WITH_TYPE("mach-o-bind",
1729                       llvm::dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
1730                                    << format("SegmentOffset=0x%06X",
1731                                              SegmentOffset) << "\n");
1732       break;
1733     case MachO::BIND_OPCODE_DO_BIND:
1734       AdvanceAmount = PointerSize;
1735       RemainingLoopCount = 0;
1736       DEBUG_WITH_TYPE("mach-o-bind",
1737                       llvm::dbgs() << "BIND_OPCODE_DO_BIND: "
1738                                    << format("SegmentOffset=0x%06X",
1739                                              SegmentOffset) << "\n");
1740       return;
1741      case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
1742       AdvanceAmount = readULEB128() + PointerSize;
1743       RemainingLoopCount = 0;
1744       if (TableKind == Kind::Lazy)
1745         Malformed = true;
1746       DEBUG_WITH_TYPE(
1747           "mach-o-bind",
1748           llvm::dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
1749                        << format("SegmentOffset=0x%06X", SegmentOffset)
1750                        << ", AdvanceAmount=" << AdvanceAmount
1751                        << ", RemainingLoopCount=" << RemainingLoopCount
1752                        << "\n");
1753       return;
1754     case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
1755       AdvanceAmount = ImmValue * PointerSize + PointerSize;
1756       RemainingLoopCount = 0;
1757       if (TableKind == Kind::Lazy)
1758         Malformed = true;
1759       DEBUG_WITH_TYPE("mach-o-bind",
1760                       llvm::dbgs()
1761                       << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
1762                       << format("SegmentOffset=0x%06X",
1763                                              SegmentOffset) << "\n");
1764       return;
1765     case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
1766       RemainingLoopCount = readULEB128() - 1;
1767       AdvanceAmount = readULEB128() + PointerSize;
1768       if (TableKind == Kind::Lazy)
1769         Malformed = true;
1770       DEBUG_WITH_TYPE(
1771           "mach-o-bind",
1772           llvm::dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
1773                        << format("SegmentOffset=0x%06X", SegmentOffset)
1774                        << ", AdvanceAmount=" << AdvanceAmount
1775                        << ", RemainingLoopCount=" << RemainingLoopCount
1776                        << "\n");
1777       return;
1778     default:
1779       Malformed = true;
1780     }
1781   }
1782 }
1783
1784 uint64_t MachOBindEntry::readULEB128() {
1785   unsigned Count;
1786   uint64_t Result = decodeULEB128(Ptr, &Count);
1787   Ptr += Count;
1788   if (Ptr > Opcodes.end()) {
1789     Ptr = Opcodes.end();
1790     Malformed = true;
1791   }
1792   return Result;
1793 }
1794
1795 int64_t MachOBindEntry::readSLEB128() {
1796   unsigned Count;
1797   int64_t Result = decodeSLEB128(Ptr, &Count);
1798   Ptr += Count;
1799   if (Ptr > Opcodes.end()) {
1800     Ptr = Opcodes.end();
1801     Malformed = true;
1802   }
1803   return Result;
1804 }
1805
1806
1807 uint32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
1808
1809 uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
1810
1811 StringRef MachOBindEntry::typeName() const {
1812   switch (BindType) {
1813   case MachO::BIND_TYPE_POINTER:
1814     return "pointer";
1815   case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
1816     return "text abs32";
1817   case MachO::BIND_TYPE_TEXT_PCREL32:
1818     return "text rel32";
1819   }
1820   return "unknown";
1821 }
1822
1823 StringRef MachOBindEntry::symbolName() const { return SymbolName; }
1824
1825 int64_t MachOBindEntry::addend() const { return Addend; }
1826
1827 uint32_t MachOBindEntry::flags() const { return Flags; }
1828
1829 int MachOBindEntry::ordinal() const { return Ordinal; }
1830
1831 bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
1832   assert(Opcodes == Other.Opcodes && "compare iterators of different files");
1833   return (Ptr == Other.Ptr) &&
1834          (RemainingLoopCount == Other.RemainingLoopCount) &&
1835          (Done == Other.Done);
1836 }
1837
1838 iterator_range<bind_iterator>
1839 MachOObjectFile::bindTable(ArrayRef<uint8_t> Opcodes, bool is64,
1840                            MachOBindEntry::Kind BKind) {
1841   MachOBindEntry Start(Opcodes, is64, BKind);
1842   Start.moveToFirst();
1843
1844   MachOBindEntry Finish(Opcodes, is64, BKind);
1845   Finish.moveToEnd();
1846
1847   return iterator_range<bind_iterator>(bind_iterator(Start),
1848                                        bind_iterator(Finish));
1849 }
1850
1851 iterator_range<bind_iterator> MachOObjectFile::bindTable() const {
1852   return bindTable(getDyldInfoBindOpcodes(), is64Bit(),
1853                    MachOBindEntry::Kind::Regular);
1854 }
1855
1856 iterator_range<bind_iterator> MachOObjectFile::lazyBindTable() const {
1857   return bindTable(getDyldInfoLazyBindOpcodes(), is64Bit(),
1858                    MachOBindEntry::Kind::Lazy);
1859 }
1860
1861 iterator_range<bind_iterator> MachOObjectFile::weakBindTable() const {
1862   return bindTable(getDyldInfoWeakBindOpcodes(), is64Bit(),
1863                    MachOBindEntry::Kind::Weak);
1864 }
1865
1866 MachOObjectFile::load_command_iterator
1867 MachOObjectFile::begin_load_commands() const {
1868   return LoadCommands.begin();
1869 }
1870
1871 MachOObjectFile::load_command_iterator
1872 MachOObjectFile::end_load_commands() const {
1873   return LoadCommands.end();
1874 }
1875
1876 iterator_range<MachOObjectFile::load_command_iterator>
1877 MachOObjectFile::load_commands() const {
1878   return iterator_range<load_command_iterator>(begin_load_commands(),
1879                                                end_load_commands());
1880 }
1881
1882 StringRef
1883 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1884   ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1885   return parseSegmentOrSectionName(Raw.data());
1886 }
1887
1888 ArrayRef<char>
1889 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
1890   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
1891   const section_base *Base =
1892     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1893   return makeArrayRef(Base->sectname);
1894 }
1895
1896 ArrayRef<char>
1897 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
1898   assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
1899   const section_base *Base =
1900     reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1901   return makeArrayRef(Base->segname);
1902 }
1903
1904 bool
1905 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
1906   const {
1907   if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
1908     return false;
1909   return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
1910 }
1911
1912 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
1913     const MachO::any_relocation_info &RE) const {
1914   if (isLittleEndian())
1915     return RE.r_word1 & 0xffffff;
1916   return RE.r_word1 >> 8;
1917 }
1918
1919 bool MachOObjectFile::getPlainRelocationExternal(
1920     const MachO::any_relocation_info &RE) const {
1921   if (isLittleEndian())
1922     return (RE.r_word1 >> 27) & 1;
1923   return (RE.r_word1 >> 4) & 1;
1924 }
1925
1926 bool MachOObjectFile::getScatteredRelocationScattered(
1927     const MachO::any_relocation_info &RE) const {
1928   return RE.r_word0 >> 31;
1929 }
1930
1931 uint32_t MachOObjectFile::getScatteredRelocationValue(
1932     const MachO::any_relocation_info &RE) const {
1933   return RE.r_word1;
1934 }
1935
1936 uint32_t MachOObjectFile::getScatteredRelocationType(
1937     const MachO::any_relocation_info &RE) const {
1938   return (RE.r_word0 >> 24) & 0xf;
1939 }
1940
1941 unsigned MachOObjectFile::getAnyRelocationAddress(
1942     const MachO::any_relocation_info &RE) const {
1943   if (isRelocationScattered(RE))
1944     return getScatteredRelocationAddress(RE);
1945   return getPlainRelocationAddress(RE);
1946 }
1947
1948 unsigned MachOObjectFile::getAnyRelocationPCRel(
1949     const MachO::any_relocation_info &RE) const {
1950   if (isRelocationScattered(RE))
1951     return getScatteredRelocationPCRel(this, RE);
1952   return getPlainRelocationPCRel(this, RE);
1953 }
1954
1955 unsigned MachOObjectFile::getAnyRelocationLength(
1956     const MachO::any_relocation_info &RE) const {
1957   if (isRelocationScattered(RE))
1958     return getScatteredRelocationLength(RE);
1959   return getPlainRelocationLength(this, RE);
1960 }
1961
1962 unsigned
1963 MachOObjectFile::getAnyRelocationType(
1964                                    const MachO::any_relocation_info &RE) const {
1965   if (isRelocationScattered(RE))
1966     return getScatteredRelocationType(RE);
1967   return getPlainRelocationType(this, RE);
1968 }
1969
1970 SectionRef
1971 MachOObjectFile::getAnyRelocationSection(
1972                                    const MachO::any_relocation_info &RE) const {
1973   if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
1974     return *section_end();
1975   unsigned SecNum = getPlainRelocationSymbolNum(RE);
1976   if (SecNum == MachO::R_ABS || SecNum > Sections.size())
1977     return *section_end();
1978   DataRefImpl DRI;
1979   DRI.d.a = SecNum - 1;
1980   return SectionRef(DRI, this);
1981 }
1982
1983 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
1984   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
1985   return getStruct<MachO::section>(this, Sections[DRI.d.a]);
1986 }
1987
1988 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
1989   assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
1990   return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
1991 }
1992
1993 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
1994                                            unsigned Index) const {
1995   const char *Sec = getSectionPtr(this, L, Index);
1996   return getStruct<MachO::section>(this, Sec);
1997 }
1998
1999 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
2000                                                 unsigned Index) const {
2001   const char *Sec = getSectionPtr(this, L, Index);
2002   return getStruct<MachO::section_64>(this, Sec);
2003 }
2004
2005 MachO::nlist
2006 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
2007   const char *P = reinterpret_cast<const char *>(DRI.p);
2008   return getStruct<MachO::nlist>(this, P);
2009 }
2010
2011 MachO::nlist_64
2012 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
2013   const char *P = reinterpret_cast<const char *>(DRI.p);
2014   return getStruct<MachO::nlist_64>(this, P);
2015 }
2016
2017 MachO::linkedit_data_command
2018 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
2019   return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
2020 }
2021
2022 MachO::segment_command
2023 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
2024   return getStruct<MachO::segment_command>(this, L.Ptr);
2025 }
2026
2027 MachO::segment_command_64
2028 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
2029   return getStruct<MachO::segment_command_64>(this, L.Ptr);
2030 }
2031
2032 MachO::linker_option_command
2033 MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
2034   return getStruct<MachO::linker_option_command>(this, L.Ptr);
2035 }
2036
2037 MachO::version_min_command
2038 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
2039   return getStruct<MachO::version_min_command>(this, L.Ptr);
2040 }
2041
2042 MachO::dylib_command
2043 MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
2044   return getStruct<MachO::dylib_command>(this, L.Ptr);
2045 }
2046
2047 MachO::dyld_info_command
2048 MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
2049   return getStruct<MachO::dyld_info_command>(this, L.Ptr);
2050 }
2051
2052 MachO::dylinker_command
2053 MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
2054   return getStruct<MachO::dylinker_command>(this, L.Ptr);
2055 }
2056
2057 MachO::uuid_command
2058 MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
2059   return getStruct<MachO::uuid_command>(this, L.Ptr);
2060 }
2061
2062 MachO::rpath_command
2063 MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
2064   return getStruct<MachO::rpath_command>(this, L.Ptr);
2065 }
2066
2067 MachO::source_version_command
2068 MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
2069   return getStruct<MachO::source_version_command>(this, L.Ptr);
2070 }
2071
2072 MachO::entry_point_command
2073 MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
2074   return getStruct<MachO::entry_point_command>(this, L.Ptr);
2075 }
2076
2077 MachO::encryption_info_command
2078 MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
2079   return getStruct<MachO::encryption_info_command>(this, L.Ptr);
2080 }
2081
2082 MachO::encryption_info_command_64
2083 MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
2084   return getStruct<MachO::encryption_info_command_64>(this, L.Ptr);
2085 }
2086
2087 MachO::sub_framework_command
2088 MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
2089   return getStruct<MachO::sub_framework_command>(this, L.Ptr);
2090 }
2091
2092 MachO::sub_umbrella_command
2093 MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
2094   return getStruct<MachO::sub_umbrella_command>(this, L.Ptr);
2095 }
2096
2097 MachO::sub_library_command
2098 MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
2099   return getStruct<MachO::sub_library_command>(this, L.Ptr);
2100 }
2101
2102 MachO::sub_client_command
2103 MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
2104   return getStruct<MachO::sub_client_command>(this, L.Ptr);
2105 }
2106
2107 MachO::routines_command
2108 MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
2109   return getStruct<MachO::routines_command>(this, L.Ptr);
2110 }
2111
2112 MachO::routines_command_64
2113 MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
2114   return getStruct<MachO::routines_command_64>(this, L.Ptr);
2115 }
2116
2117 MachO::thread_command
2118 MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
2119   return getStruct<MachO::thread_command>(this, L.Ptr);
2120 }
2121
2122 MachO::any_relocation_info
2123 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
2124   DataRefImpl Sec;
2125   Sec.d.a = Rel.d.a;
2126   uint32_t Offset;
2127   if (is64Bit()) {
2128     MachO::section_64 Sect = getSection64(Sec);
2129     Offset = Sect.reloff;
2130   } else {
2131     MachO::section Sect = getSection(Sec);
2132     Offset = Sect.reloff;
2133   }
2134
2135   auto P = reinterpret_cast<const MachO::any_relocation_info *>(
2136       getPtr(this, Offset)) + Rel.d.b;
2137   return getStruct<MachO::any_relocation_info>(
2138       this, reinterpret_cast<const char *>(P));
2139 }
2140
2141 MachO::data_in_code_entry
2142 MachOObjectFile::getDice(DataRefImpl Rel) const {
2143   const char *P = reinterpret_cast<const char *>(Rel.p);
2144   return getStruct<MachO::data_in_code_entry>(this, P);
2145 }
2146
2147 const MachO::mach_header &MachOObjectFile::getHeader() const {
2148   return Header;
2149 }
2150
2151 const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
2152   assert(is64Bit());
2153   return Header64;
2154 }
2155
2156 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
2157                                              const MachO::dysymtab_command &DLC,
2158                                              unsigned Index) const {
2159   uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
2160   return getStruct<uint32_t>(this, getPtr(this, Offset));
2161 }
2162
2163 MachO::data_in_code_entry
2164 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
2165                                          unsigned Index) const {
2166   uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
2167   return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
2168 }
2169
2170 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
2171   if (SymtabLoadCmd)
2172     return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
2173
2174   // If there is no SymtabLoadCmd return a load command with zero'ed fields.
2175   MachO::symtab_command Cmd;
2176   Cmd.cmd = MachO::LC_SYMTAB;
2177   Cmd.cmdsize = sizeof(MachO::symtab_command);
2178   Cmd.symoff = 0;
2179   Cmd.nsyms = 0;
2180   Cmd.stroff = 0;
2181   Cmd.strsize = 0;
2182   return Cmd;
2183 }
2184
2185 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
2186   if (DysymtabLoadCmd)
2187     return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
2188
2189   // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
2190   MachO::dysymtab_command Cmd;
2191   Cmd.cmd = MachO::LC_DYSYMTAB;
2192   Cmd.cmdsize = sizeof(MachO::dysymtab_command);
2193   Cmd.ilocalsym = 0;
2194   Cmd.nlocalsym = 0;
2195   Cmd.iextdefsym = 0;
2196   Cmd.nextdefsym = 0;
2197   Cmd.iundefsym = 0;
2198   Cmd.nundefsym = 0;
2199   Cmd.tocoff = 0;
2200   Cmd.ntoc = 0;
2201   Cmd.modtaboff = 0;
2202   Cmd.nmodtab = 0;
2203   Cmd.extrefsymoff = 0;
2204   Cmd.nextrefsyms = 0;
2205   Cmd.indirectsymoff = 0;
2206   Cmd.nindirectsyms = 0;
2207   Cmd.extreloff = 0;
2208   Cmd.nextrel = 0;
2209   Cmd.locreloff = 0;
2210   Cmd.nlocrel = 0;
2211   return Cmd;
2212 }
2213
2214 MachO::linkedit_data_command
2215 MachOObjectFile::getDataInCodeLoadCommand() const {
2216   if (DataInCodeLoadCmd)
2217     return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
2218
2219   // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
2220   MachO::linkedit_data_command Cmd;
2221   Cmd.cmd = MachO::LC_DATA_IN_CODE;
2222   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2223   Cmd.dataoff = 0;
2224   Cmd.datasize = 0;
2225   return Cmd;
2226 }
2227
2228 MachO::linkedit_data_command
2229 MachOObjectFile::getLinkOptHintsLoadCommand() const {
2230   if (LinkOptHintsLoadCmd)
2231     return getStruct<MachO::linkedit_data_command>(this, LinkOptHintsLoadCmd);
2232
2233   // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
2234   // fields.
2235   MachO::linkedit_data_command Cmd;
2236   Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
2237   Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
2238   Cmd.dataoff = 0;
2239   Cmd.datasize = 0;
2240   return Cmd;
2241 }
2242
2243 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
2244   if (!DyldInfoLoadCmd) 
2245     return ArrayRef<uint8_t>();
2246
2247   MachO::dyld_info_command DyldInfo 
2248                    = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2249   const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2250                                              getPtr(this, DyldInfo.rebase_off));
2251   return ArrayRef<uint8_t>(Ptr, DyldInfo.rebase_size);
2252 }
2253
2254 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
2255   if (!DyldInfoLoadCmd) 
2256     return ArrayRef<uint8_t>();
2257
2258   MachO::dyld_info_command DyldInfo 
2259                    = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2260   const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2261                                                getPtr(this, DyldInfo.bind_off));
2262   return ArrayRef<uint8_t>(Ptr, DyldInfo.bind_size);
2263 }
2264
2265 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
2266   if (!DyldInfoLoadCmd) 
2267     return ArrayRef<uint8_t>();
2268
2269   MachO::dyld_info_command DyldInfo 
2270                    = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2271   const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2272                                           getPtr(this, DyldInfo.weak_bind_off));
2273   return ArrayRef<uint8_t>(Ptr, DyldInfo.weak_bind_size);
2274 }
2275
2276 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
2277   if (!DyldInfoLoadCmd) 
2278     return ArrayRef<uint8_t>();
2279
2280   MachO::dyld_info_command DyldInfo 
2281                    = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2282   const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2283                                           getPtr(this, DyldInfo.lazy_bind_off));
2284   return ArrayRef<uint8_t>(Ptr, DyldInfo.lazy_bind_size);
2285 }
2286
2287 ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
2288   if (!DyldInfoLoadCmd) 
2289     return ArrayRef<uint8_t>();
2290
2291   MachO::dyld_info_command DyldInfo 
2292                    = getStruct<MachO::dyld_info_command>(this, DyldInfoLoadCmd);
2293   const uint8_t *Ptr = reinterpret_cast<const uint8_t*>(
2294                                              getPtr(this, DyldInfo.export_off));
2295   return ArrayRef<uint8_t>(Ptr, DyldInfo.export_size);
2296 }
2297
2298 ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
2299   if (!UuidLoadCmd)
2300     return ArrayRef<uint8_t>();
2301   // Returning a pointer is fine as uuid doesn't need endian swapping.
2302   const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
2303   return ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Ptr), 16);
2304 }
2305
2306 StringRef MachOObjectFile::getStringTableData() const {
2307   MachO::symtab_command S = getSymtabLoadCommand();
2308   return getData().substr(S.stroff, S.strsize);
2309 }
2310
2311 bool MachOObjectFile::is64Bit() const {
2312   return getType() == getMachOType(false, true) ||
2313     getType() == getMachOType(true, true);
2314 }
2315
2316 void MachOObjectFile::ReadULEB128s(uint64_t Index,
2317                                    SmallVectorImpl<uint64_t> &Out) const {
2318   DataExtractor extractor(ObjectFile::getData(), true, 0);
2319
2320   uint32_t offset = Index;
2321   uint64_t data = 0;
2322   while (uint64_t delta = extractor.getULEB128(&offset)) {
2323     data += delta;
2324     Out.push_back(data);
2325   }
2326 }
2327
2328 bool MachOObjectFile::isRelocatableObject() const {
2329   return getHeader().filetype == MachO::MH_OBJECT;
2330 }
2331
2332 ErrorOr<std::unique_ptr<MachOObjectFile>>
2333 ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer) {
2334   StringRef Magic = Buffer.getBuffer().slice(0, 4);
2335   std::error_code EC;
2336   std::unique_ptr<MachOObjectFile> Ret;
2337   if (Magic == "\xFE\xED\xFA\xCE")
2338     Ret.reset(new MachOObjectFile(Buffer, false, false, EC));
2339   else if (Magic == "\xCE\xFA\xED\xFE")
2340     Ret.reset(new MachOObjectFile(Buffer, true, false, EC));
2341   else if (Magic == "\xFE\xED\xFA\xCF")
2342     Ret.reset(new MachOObjectFile(Buffer, false, true, EC));
2343   else if (Magic == "\xCF\xFA\xED\xFE")
2344     Ret.reset(new MachOObjectFile(Buffer, true, true, EC));
2345   else
2346     return object_error::parse_failed;
2347
2348   if (EC)
2349     return EC;
2350   return std::move(Ret);
2351 }
2352