Make getRelocationSection MachO only.
[oota-llvm.git] / include / llvm / Object / MachO.h
1 //===- MachO.h - MachO object file implementation ---------------*- 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 declares the MachOObjectFile class, which implement the ObjectFile
11 // interface for MachO files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_OBJECT_MACHO_H
16 #define LLVM_OBJECT_MACHO_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/MachO.h"
23
24 namespace llvm {
25 namespace object {
26
27 /// DiceRef - This is a value type class that represents a single
28 /// data in code entry in the table in a Mach-O object file.
29 class DiceRef {
30   DataRefImpl DicePimpl;
31   const ObjectFile *OwningObject;
32
33 public:
34   DiceRef() : OwningObject(nullptr) { }
35
36   DiceRef(DataRefImpl DiceP, const ObjectFile *Owner);
37
38   bool operator==(const DiceRef &Other) const;
39   bool operator<(const DiceRef &Other) const;
40
41   void moveNext();
42
43   std::error_code getOffset(uint32_t &Result) const;
44   std::error_code getLength(uint16_t &Result) const;
45   std::error_code getKind(uint16_t &Result) const;
46
47   DataRefImpl getRawDataRefImpl() const;
48   const ObjectFile *getObjectFile() const;
49 };
50 typedef content_iterator<DiceRef> dice_iterator;
51
52 /// ExportEntry encapsulates the current-state-of-the-walk used when doing a
53 /// non-recursive walk of the trie data structure.  This allows you to iterate
54 /// across all exported symbols using:
55 ///      for (const llvm::object::ExportEntry &AnExport : Obj->exports()) {
56 ///      }
57 class ExportEntry {
58 public:
59   ExportEntry(ArrayRef<uint8_t> Trie);
60
61   StringRef name() const;
62   uint64_t flags() const;
63   uint64_t address() const;
64   uint64_t other() const;
65   StringRef otherName() const;
66   uint32_t nodeOffset() const;
67
68   bool operator==(const ExportEntry &) const;
69
70   void moveNext();
71
72 private:
73   friend class MachOObjectFile;
74   void moveToFirst();
75   void moveToEnd();
76   uint64_t readULEB128(const uint8_t *&p);
77   void pushDownUntilBottom();
78   void pushNode(uint64_t Offset);
79
80   // Represents a node in the mach-o exports trie.
81   struct NodeState {
82     NodeState(const uint8_t *Ptr);
83     const uint8_t *Start;
84     const uint8_t *Current;
85     uint64_t Flags;
86     uint64_t Address;
87     uint64_t Other;
88     const char *ImportName;
89     unsigned ChildCount;
90     unsigned NextChildIndex;
91     unsigned ParentStringLength;
92     bool IsExportNode;
93   };
94
95   ArrayRef<uint8_t> Trie;
96   SmallString<256> CumulativeString;
97   SmallVector<NodeState, 16> Stack;
98   bool Malformed;
99   bool Done;
100 };
101 typedef content_iterator<ExportEntry> export_iterator;
102
103 /// MachORebaseEntry encapsulates the current state in the decompression of   
104 /// rebasing opcodes. This allows you to iterate through the compressed table of
105 /// rebasing using:
106 ///    for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
107 ///    }
108 class MachORebaseEntry {
109 public:
110   MachORebaseEntry(ArrayRef<uint8_t> opcodes, bool is64Bit);
111
112   uint32_t segmentIndex() const;
113   uint64_t segmentOffset() const;
114   StringRef typeName() const;
115
116   bool operator==(const MachORebaseEntry &) const;
117
118   void moveNext();
119   
120 private:
121   friend class MachOObjectFile;
122   void moveToFirst();
123   void moveToEnd();
124   uint64_t readULEB128();
125
126   ArrayRef<uint8_t> Opcodes;
127   const uint8_t *Ptr;
128   uint64_t SegmentOffset;
129   uint32_t SegmentIndex;
130   uint64_t RemainingLoopCount;
131   uint64_t AdvanceAmount;
132   uint8_t  RebaseType;
133   uint8_t  PointerSize;
134   bool     Malformed;
135   bool     Done;
136 };
137 typedef content_iterator<MachORebaseEntry> rebase_iterator;
138
139 /// MachOBindEntry encapsulates the current state in the decompression of
140 /// binding opcodes. This allows you to iterate through the compressed table of
141 /// bindings using:
142 ///    for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
143 ///    }
144 class MachOBindEntry {
145 public:
146   enum class Kind { Regular, Lazy, Weak };
147
148   MachOBindEntry(ArrayRef<uint8_t> Opcodes, bool is64Bit, MachOBindEntry::Kind);
149
150   uint32_t segmentIndex() const;
151   uint64_t segmentOffset() const;
152   StringRef typeName() const;
153   StringRef symbolName() const;
154   uint32_t flags() const;
155   int64_t addend() const;
156   int ordinal() const;
157
158   bool operator==(const MachOBindEntry &) const;
159
160   void moveNext();
161
162 private:
163   friend class MachOObjectFile;
164   void moveToFirst();
165   void moveToEnd();
166   uint64_t readULEB128();
167   int64_t readSLEB128();
168
169   ArrayRef<uint8_t> Opcodes;
170   const uint8_t *Ptr;
171   uint64_t SegmentOffset;
172   uint32_t SegmentIndex;
173   StringRef SymbolName;
174   int      Ordinal;
175   uint32_t Flags;
176   int64_t  Addend;
177   uint64_t RemainingLoopCount;
178   uint64_t AdvanceAmount;
179   uint8_t  BindType;
180   uint8_t  PointerSize;
181   Kind     TableKind;
182   bool     Malformed;
183   bool     Done;
184 };
185 typedef content_iterator<MachOBindEntry> bind_iterator;
186
187 class MachOObjectFile : public ObjectFile {
188 public:
189   struct LoadCommandInfo {
190     const char *Ptr;      // Where in memory the load command is.
191     MachO::load_command C; // The command itself.
192   };
193   typedef SmallVector<LoadCommandInfo, 4> LoadCommandList;
194   typedef LoadCommandList::const_iterator load_command_iterator;
195
196   MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
197                   std::error_code &EC);
198
199   void moveSymbolNext(DataRefImpl &Symb) const override;
200   std::error_code getSymbolName(DataRefImpl Symb,
201                                 StringRef &Res) const override;
202
203   // MachO specific.
204   std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const;
205   unsigned getSectionType(SectionRef Sec) const;
206
207   std::error_code getSymbolAddress(DataRefImpl Symb,
208                                    uint64_t &Res) const override;
209   uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
210   uint64_t getSymbolSize(DataRefImpl Symb) const override;
211   std::error_code getSymbolType(DataRefImpl Symb,
212                                 SymbolRef::Type &Res) const override;
213   uint32_t getSymbolFlags(DataRefImpl Symb) const override;
214   std::error_code getSymbolSection(DataRefImpl Symb,
215                                    section_iterator &Res) const override;
216
217   void moveSectionNext(DataRefImpl &Sec) const override;
218   std::error_code getSectionName(DataRefImpl Sec,
219                                  StringRef &Res) const override;
220   uint64_t getSectionAddress(DataRefImpl Sec) const override;
221   uint64_t getSectionSize(DataRefImpl Sec) const override;
222   std::error_code getSectionContents(DataRefImpl Sec,
223                                      StringRef &Res) const override;
224   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
225   bool isSectionText(DataRefImpl Sec) const override;
226   bool isSectionData(DataRefImpl Sec) const override;
227   bool isSectionBSS(DataRefImpl Sec) const override;
228   bool isSectionVirtual(DataRefImpl Sec) const override;
229   bool sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb) const override;
230   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
231   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
232
233   void moveRelocationNext(DataRefImpl &Rel) const override;
234   std::error_code getRelocationAddress(DataRefImpl Rel,
235                                        uint64_t &Res) const override;
236   std::error_code getRelocationOffset(DataRefImpl Rel,
237                                       uint64_t &Res) const override;
238   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
239   section_iterator getRelocationSection(DataRefImpl Rel) const;
240   std::error_code getRelocationType(DataRefImpl Rel,
241                                     uint64_t &Res) const override;
242   std::error_code
243   getRelocationTypeName(DataRefImpl Rel,
244                         SmallVectorImpl<char> &Result) const override;
245   std::error_code getRelocationHidden(DataRefImpl Rel,
246                                       bool &Result) const override;
247   uint8_t getRelocationLength(DataRefImpl Rel) const;
248
249   // MachO specific.
250   std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const;
251
252   // TODO: Would be useful to have an iterator based version
253   // of the load command interface too.
254
255   basic_symbol_iterator symbol_begin_impl() const override;
256   basic_symbol_iterator symbol_end_impl() const override;
257
258   // MachO specific.
259   basic_symbol_iterator getSymbolByIndex(unsigned Index) const;
260
261   section_iterator section_begin() const override;
262   section_iterator section_end() const override;
263
264   uint8_t getBytesInAddress() const override;
265
266   StringRef getFileFormatName() const override;
267   unsigned getArch() const override;
268   Triple getArch(const char **McpuDefault, Triple *ThumbTriple) const;
269
270   relocation_iterator section_rel_begin(unsigned Index) const;
271   relocation_iterator section_rel_end(unsigned Index) const;
272
273   dice_iterator begin_dices() const;
274   dice_iterator end_dices() const;
275
276   load_command_iterator begin_load_commands() const;
277   load_command_iterator end_load_commands() const;
278   iterator_range<load_command_iterator> load_commands() const;
279
280   /// For use iterating over all exported symbols.
281   iterator_range<export_iterator> exports() const;
282
283   /// For use examining a trie not in a MachOObjectFile.
284   static iterator_range<export_iterator> exports(ArrayRef<uint8_t> Trie);
285
286   /// For use iterating over all rebase table entries.
287   iterator_range<rebase_iterator> rebaseTable() const;
288
289   /// For use examining rebase opcodes not in a MachOObjectFile.
290   static iterator_range<rebase_iterator> rebaseTable(ArrayRef<uint8_t> Opcodes,
291                                                      bool is64);
292
293   /// For use iterating over all bind table entries.
294   iterator_range<bind_iterator> bindTable() const;
295
296   /// For use iterating over all lazy bind table entries.
297   iterator_range<bind_iterator> lazyBindTable() const;
298
299   /// For use iterating over all lazy bind table entries.
300   iterator_range<bind_iterator> weakBindTable() const;
301
302   /// For use examining bind opcodes not in a MachOObjectFile.
303   static iterator_range<bind_iterator> bindTable(ArrayRef<uint8_t> Opcodes,
304                                                  bool is64,
305                                                  MachOBindEntry::Kind);
306
307
308   // In a MachO file, sections have a segment name. This is used in the .o
309   // files. They have a single segment, but this field specifies which segment
310   // a section should be put in in the final object.
311   StringRef getSectionFinalSegmentName(DataRefImpl Sec) const;
312
313   // Names are stored as 16 bytes. These returns the raw 16 bytes without
314   // interpreting them as a C string.
315   ArrayRef<char> getSectionRawName(DataRefImpl Sec) const;
316   ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const;
317
318   // MachO specific Info about relocations.
319   bool isRelocationScattered(const MachO::any_relocation_info &RE) const;
320   unsigned getPlainRelocationSymbolNum(
321                                     const MachO::any_relocation_info &RE) const;
322   bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const;
323   bool getScatteredRelocationScattered(
324                                     const MachO::any_relocation_info &RE) const;
325   uint32_t getScatteredRelocationValue(
326                                     const MachO::any_relocation_info &RE) const;
327   uint32_t getScatteredRelocationType(
328                                     const MachO::any_relocation_info &RE) const;
329   unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const;
330   unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const;
331   unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const;
332   unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const;
333   SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const;
334
335   // MachO specific structures.
336   MachO::section getSection(DataRefImpl DRI) const;
337   MachO::section_64 getSection64(DataRefImpl DRI) const;
338   MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const;
339   MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const;
340   MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const;
341   MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const;
342
343   MachO::linkedit_data_command
344   getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
345   MachO::segment_command
346   getSegmentLoadCommand(const LoadCommandInfo &L) const;
347   MachO::segment_command_64
348   getSegment64LoadCommand(const LoadCommandInfo &L) const;
349   MachO::linker_option_command
350   getLinkerOptionLoadCommand(const LoadCommandInfo &L) const;
351   MachO::version_min_command
352   getVersionMinLoadCommand(const LoadCommandInfo &L) const;
353   MachO::dylib_command
354   getDylibIDLoadCommand(const LoadCommandInfo &L) const;
355   MachO::dyld_info_command
356   getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
357   MachO::dylinker_command
358   getDylinkerCommand(const LoadCommandInfo &L) const;
359   MachO::uuid_command
360   getUuidCommand(const LoadCommandInfo &L) const;
361   MachO::rpath_command
362   getRpathCommand(const LoadCommandInfo &L) const;
363   MachO::source_version_command
364   getSourceVersionCommand(const LoadCommandInfo &L) const;
365   MachO::entry_point_command
366   getEntryPointCommand(const LoadCommandInfo &L) const;
367   MachO::encryption_info_command
368   getEncryptionInfoCommand(const LoadCommandInfo &L) const;
369   MachO::encryption_info_command_64
370   getEncryptionInfoCommand64(const LoadCommandInfo &L) const;
371   MachO::sub_framework_command
372   getSubFrameworkCommand(const LoadCommandInfo &L) const;
373   MachO::sub_umbrella_command
374   getSubUmbrellaCommand(const LoadCommandInfo &L) const;
375   MachO::sub_library_command
376   getSubLibraryCommand(const LoadCommandInfo &L) const;
377   MachO::sub_client_command
378   getSubClientCommand(const LoadCommandInfo &L) const;
379   MachO::routines_command
380   getRoutinesCommand(const LoadCommandInfo &L) const;
381   MachO::routines_command_64
382   getRoutinesCommand64(const LoadCommandInfo &L) const;
383   MachO::thread_command
384   getThreadCommand(const LoadCommandInfo &L) const;
385
386   MachO::any_relocation_info getRelocation(DataRefImpl Rel) const;
387   MachO::data_in_code_entry getDice(DataRefImpl Rel) const;
388   const MachO::mach_header &getHeader() const;
389   const MachO::mach_header_64 &getHeader64() const;
390   uint32_t
391   getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC,
392                               unsigned Index) const;
393   MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset,
394                                                     unsigned Index) const;
395   MachO::symtab_command getSymtabLoadCommand() const;
396   MachO::dysymtab_command getDysymtabLoadCommand() const;
397   MachO::linkedit_data_command getDataInCodeLoadCommand() const;
398   MachO::linkedit_data_command getLinkOptHintsLoadCommand() const;
399   ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const;
400   ArrayRef<uint8_t> getDyldInfoBindOpcodes() const;
401   ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const;
402   ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const;
403   ArrayRef<uint8_t> getDyldInfoExportsTrie() const;
404   ArrayRef<uint8_t> getUuid() const;
405
406   StringRef getStringTableData() const;
407   bool is64Bit() const;
408   void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
409
410   static StringRef guessLibraryShortName(StringRef Name, bool &isFramework,
411                                          StringRef &Suffix);
412
413   static Triple::ArchType getArch(uint32_t CPUType);
414   static Triple getArch(uint32_t CPUType, uint32_t CPUSubType,
415                         const char **McpuDefault = nullptr);
416   static Triple getThumbArch(uint32_t CPUType, uint32_t CPUSubType,
417                              const char **McpuDefault = nullptr);
418   static Triple getArch(uint32_t CPUType, uint32_t CPUSubType,
419                         const char **McpuDefault, Triple *ThumbTriple);
420   static bool isValidArch(StringRef ArchFlag);
421   static Triple getHostArch();
422
423   bool isRelocatableObject() const override;
424
425   bool hasPageZeroSegment() const { return HasPageZeroSegment; }
426
427   static bool classof(const Binary *v) {
428     return v->isMachO();
429   }
430
431 private:
432   union {
433     MachO::mach_header_64 Header64;
434     MachO::mach_header Header;
435   };
436   typedef SmallVector<const char*, 1> SectionList;
437   SectionList Sections;
438   typedef SmallVector<const char*, 1> LibraryList;
439   LibraryList Libraries;
440   LoadCommandList LoadCommands;
441   typedef SmallVector<StringRef, 1> LibraryShortName;
442   mutable LibraryShortName LibrariesShortNames;
443   const char *SymtabLoadCmd;
444   const char *DysymtabLoadCmd;
445   const char *DataInCodeLoadCmd;
446   const char *LinkOptHintsLoadCmd;
447   const char *DyldInfoLoadCmd;
448   const char *UuidLoadCmd;
449   bool HasPageZeroSegment;
450 };
451
452 /// DiceRef
453 inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner)
454   : DicePimpl(DiceP) , OwningObject(Owner) {}
455
456 inline bool DiceRef::operator==(const DiceRef &Other) const {
457   return DicePimpl == Other.DicePimpl;
458 }
459
460 inline bool DiceRef::operator<(const DiceRef &Other) const {
461   return DicePimpl < Other.DicePimpl;
462 }
463
464 inline void DiceRef::moveNext() {
465   const MachO::data_in_code_entry *P =
466     reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p);
467   DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1);
468 }
469
470 // Since a Mach-O data in code reference, a DiceRef, can only be created when
471 // the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for
472 // the methods that get the values of the fields of the reference.
473
474 inline std::error_code DiceRef::getOffset(uint32_t &Result) const {
475   const MachOObjectFile *MachOOF =
476     static_cast<const MachOObjectFile *>(OwningObject);
477   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
478   Result = Dice.offset;
479   return std::error_code();
480 }
481
482 inline std::error_code DiceRef::getLength(uint16_t &Result) const {
483   const MachOObjectFile *MachOOF =
484     static_cast<const MachOObjectFile *>(OwningObject);
485   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
486   Result = Dice.length;
487   return std::error_code();
488 }
489
490 inline std::error_code DiceRef::getKind(uint16_t &Result) const {
491   const MachOObjectFile *MachOOF =
492     static_cast<const MachOObjectFile *>(OwningObject);
493   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
494   Result = Dice.kind;
495   return std::error_code();
496 }
497
498 inline DataRefImpl DiceRef::getRawDataRefImpl() const {
499   return DicePimpl;
500 }
501
502 inline const ObjectFile *DiceRef::getObjectFile() const {
503   return OwningObject;
504 }
505
506 } // namespace object
507 } // namespace llvm
508
509 #endif
510