[llvm-objdump] support -rebase option for mach-o to dump rebasing info
[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 class MachOObjectFile : public ObjectFile {
140 public:
141   struct LoadCommandInfo {
142     const char *Ptr;      // Where in memory the load command is.
143     MachO::load_command C; // The command itself.
144   };
145
146   MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
147                   std::error_code &EC);
148
149   void moveSymbolNext(DataRefImpl &Symb) const override;
150   std::error_code getSymbolName(DataRefImpl Symb,
151                                 StringRef &Res) const override;
152
153   // MachO specific.
154   std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const;
155
156   std::error_code getSymbolAddress(DataRefImpl Symb,
157                                    uint64_t &Res) const override;
158   std::error_code getSymbolAlignment(DataRefImpl Symb,
159                                      uint32_t &Res) const override;
160   std::error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const override;
161   std::error_code getSymbolType(DataRefImpl Symb,
162                                 SymbolRef::Type &Res) const override;
163   uint32_t getSymbolFlags(DataRefImpl Symb) const override;
164   std::error_code getSymbolSection(DataRefImpl Symb,
165                                    section_iterator &Res) const override;
166
167   void moveSectionNext(DataRefImpl &Sec) const override;
168   std::error_code getSectionName(DataRefImpl Sec,
169                                  StringRef &Res) const override;
170   std::error_code getSectionAddress(DataRefImpl Sec,
171                                     uint64_t &Res) const override;
172   std::error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const override;
173   std::error_code getSectionContents(DataRefImpl Sec,
174                                      StringRef &Res) const override;
175   std::error_code getSectionAlignment(DataRefImpl Sec,
176                                       uint64_t &Res) const override;
177   std::error_code isSectionText(DataRefImpl Sec, bool &Res) const override;
178   std::error_code isSectionData(DataRefImpl Sec, bool &Res) const override;
179   std::error_code isSectionBSS(DataRefImpl Sec, bool &Res) const override;
180   std::error_code isSectionRequiredForExecution(DataRefImpl Sec,
181                                                 bool &Res) const override;
182   std::error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const override;
183   std::error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const override;
184   std::error_code isSectionReadOnlyData(DataRefImpl Sec,
185                                         bool &Res) const override;
186   std::error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
187                                         bool &Result) const override;
188   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
189   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
190
191   void moveRelocationNext(DataRefImpl &Rel) const override;
192   std::error_code getRelocationAddress(DataRefImpl Rel,
193                                        uint64_t &Res) const override;
194   std::error_code getRelocationOffset(DataRefImpl Rel,
195                                       uint64_t &Res) const override;
196   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
197   std::error_code getRelocationType(DataRefImpl Rel,
198                                     uint64_t &Res) const override;
199   std::error_code
200   getRelocationTypeName(DataRefImpl Rel,
201                         SmallVectorImpl<char> &Result) const override;
202   std::error_code
203   getRelocationValueString(DataRefImpl Rel,
204                            SmallVectorImpl<char> &Result) const override;
205   std::error_code getRelocationHidden(DataRefImpl Rel,
206                                       bool &Result) const override;
207
208   // MachO specific.
209   std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const;
210
211   // TODO: Would be useful to have an iterator based version
212   // of the load command interface too.
213
214   basic_symbol_iterator symbol_begin_impl() const override;
215   basic_symbol_iterator symbol_end_impl() const override;
216
217   // MachO specific.
218   basic_symbol_iterator getSymbolByIndex(unsigned Index) const;
219
220   section_iterator section_begin() const override;
221   section_iterator section_end() const override;
222
223   uint8_t getBytesInAddress() const override;
224
225   StringRef getFileFormatName() const override;
226   unsigned getArch() const override;
227   Triple getArch(const char **McpuDefault, Triple *ThumbTriple) const;
228
229   relocation_iterator section_rel_begin(unsigned Index) const;
230   relocation_iterator section_rel_end(unsigned Index) const;
231
232   dice_iterator begin_dices() const;
233   dice_iterator end_dices() const;
234   
235   /// For use iterating over all exported symbols.
236   iterator_range<export_iterator> exports() const;
237   
238   /// For use examining a trie not in a MachOObjectFile.
239   static iterator_range<export_iterator> exports(ArrayRef<uint8_t> Trie);
240
241   /// For use iterating over all rebase table entries.
242   iterator_range<rebase_iterator> rebaseTable() const;
243
244   /// For use examining rebase opcodes not in a MachOObjectFile.
245   static iterator_range<rebase_iterator> rebaseTable(ArrayRef<uint8_t> Opcodes,
246                                                      bool is64);
247
248   // In a MachO file, sections have a segment name. This is used in the .o
249   // files. They have a single segment, but this field specifies which segment
250   // a section should be put in in the final object.
251   StringRef getSectionFinalSegmentName(DataRefImpl Sec) const;
252
253   // Names are stored as 16 bytes. These returns the raw 16 bytes without
254   // interpreting them as a C string.
255   ArrayRef<char> getSectionRawName(DataRefImpl Sec) const;
256   ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const;
257
258   // MachO specific Info about relocations.
259   bool isRelocationScattered(const MachO::any_relocation_info &RE) const;
260   unsigned getPlainRelocationSymbolNum(
261                                     const MachO::any_relocation_info &RE) const;
262   bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const;
263   bool getScatteredRelocationScattered(
264                                     const MachO::any_relocation_info &RE) const;
265   uint32_t getScatteredRelocationValue(
266                                     const MachO::any_relocation_info &RE) const;
267   unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const;
268   unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const;
269   unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const;
270   unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const;
271   SectionRef getRelocationSection(const MachO::any_relocation_info &RE) const;
272
273   // Walk load commands.
274   LoadCommandInfo getFirstLoadCommandInfo() const;
275   LoadCommandInfo getNextLoadCommandInfo(const LoadCommandInfo &L) const;
276
277   // MachO specific structures.
278   MachO::section getSection(DataRefImpl DRI) const;
279   MachO::section_64 getSection64(DataRefImpl DRI) const;
280   MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const;
281   MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const;
282   MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const;
283   MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const;
284
285   MachO::linkedit_data_command
286   getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
287   MachO::segment_command
288   getSegmentLoadCommand(const LoadCommandInfo &L) const;
289   MachO::segment_command_64
290   getSegment64LoadCommand(const LoadCommandInfo &L) const;
291   MachO::linker_options_command
292   getLinkerOptionsLoadCommand(const LoadCommandInfo &L) const;
293   MachO::version_min_command
294   getVersionMinLoadCommand(const LoadCommandInfo &L) const;
295   MachO::dylib_command
296   getDylibIDLoadCommand(const LoadCommandInfo &L) const;
297   MachO::dyld_info_command
298   getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
299   MachO::dylinker_command
300   getDylinkerCommand(const LoadCommandInfo &L) const;
301   MachO::uuid_command
302   getUuidCommand(const LoadCommandInfo &L) const;
303   MachO::source_version_command
304   getSourceVersionCommand(const LoadCommandInfo &L) const;
305   MachO::entry_point_command
306   getEntryPointCommand(const LoadCommandInfo &L) const;
307
308   MachO::any_relocation_info getRelocation(DataRefImpl Rel) const;
309   MachO::data_in_code_entry getDice(DataRefImpl Rel) const;
310   MachO::mach_header getHeader() const;
311   MachO::mach_header_64 getHeader64() const;
312   uint32_t
313   getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC,
314                               unsigned Index) const;
315   MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset,
316                                                     unsigned Index) const;
317   MachO::symtab_command getSymtabLoadCommand() const;
318   MachO::dysymtab_command getDysymtabLoadCommand() const;
319   MachO::linkedit_data_command getDataInCodeLoadCommand() const;
320   ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const;
321   ArrayRef<uint8_t> getDyldInfoBindOpcodes() const;
322   ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const;
323   ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const;
324   ArrayRef<uint8_t> getDyldInfoExportsTrie() const;
325
326   StringRef getStringTableData() const;
327   bool is64Bit() const;
328   void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
329
330   static StringRef guessLibraryShortName(StringRef Name, bool &isFramework,
331                                          StringRef &Suffix);
332
333   static Triple::ArchType getArch(uint32_t CPUType);
334   static Triple getArch(uint32_t CPUType, uint32_t CPUSubType,
335                         const char **McpuDefault = nullptr);
336   static Triple getThumbArch(uint32_t CPUType, uint32_t CPUSubType,
337                              const char **McpuDefault = nullptr);
338   static Triple getArch(uint32_t CPUType, uint32_t CPUSubType,
339                         const char **McpuDefault, Triple *ThumbTriple);
340   static bool isValidArch(StringRef ArchFlag);
341   static Triple getHostArch();
342
343   bool isRelocatableObject() const override;
344
345   static bool classof(const Binary *v) {
346     return v->isMachO();
347   }
348
349 private:
350   typedef SmallVector<const char*, 1> SectionList;
351   SectionList Sections;
352   typedef SmallVector<const char*, 1> LibraryList;
353   LibraryList Libraries;
354   typedef SmallVector<StringRef, 1> LibraryShortName;
355   mutable LibraryShortName LibrariesShortNames;
356   const char *SymtabLoadCmd;
357   const char *DysymtabLoadCmd;
358   const char *DataInCodeLoadCmd;
359   const char *DyldInfoLoadCmd;
360 };
361
362 /// DiceRef
363 inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner)
364   : DicePimpl(DiceP) , OwningObject(Owner) {}
365
366 inline bool DiceRef::operator==(const DiceRef &Other) const {
367   return DicePimpl == Other.DicePimpl;
368 }
369
370 inline bool DiceRef::operator<(const DiceRef &Other) const {
371   return DicePimpl < Other.DicePimpl;
372 }
373
374 inline void DiceRef::moveNext() {
375   const MachO::data_in_code_entry *P =
376     reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p);
377   DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1);
378 }
379
380 // Since a Mach-O data in code reference, a DiceRef, can only be created when
381 // the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for
382 // the methods that get the values of the fields of the reference.
383
384 inline std::error_code DiceRef::getOffset(uint32_t &Result) const {
385   const MachOObjectFile *MachOOF =
386     static_cast<const MachOObjectFile *>(OwningObject);
387   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
388   Result = Dice.offset;
389   return object_error::success;
390 }
391
392 inline std::error_code DiceRef::getLength(uint16_t &Result) const {
393   const MachOObjectFile *MachOOF =
394     static_cast<const MachOObjectFile *>(OwningObject);
395   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
396   Result = Dice.length;
397   return object_error::success;
398 }
399
400 inline std::error_code DiceRef::getKind(uint16_t &Result) const {
401   const MachOObjectFile *MachOOF =
402     static_cast<const MachOObjectFile *>(OwningObject);
403   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
404   Result = Dice.kind;
405   return object_error::success;
406 }
407
408 inline DataRefImpl DiceRef::getRawDataRefImpl() const {
409   return DicePimpl;
410 }
411
412 inline const ObjectFile *DiceRef::getObjectFile() const {
413   return OwningObject;
414 }
415
416 }
417 }
418
419 #endif
420