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