]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Object/MachO.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/iterator_range.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/MC/SubtargetFeature.h"
26 #include "llvm/Object/Binary.h"
27 #include "llvm/Object/ObjectFile.h"
28 #include "llvm/Object/SymbolicFile.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/MachO.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <cstdint>
35 #include <memory>
36 #include <string>
37 #include <system_error>
38
39 namespace llvm {
40 namespace object {
41
42 /// DiceRef - This is a value type class that represents a single
43 /// data in code entry in the table in a Mach-O object file.
44 class DiceRef {
45   DataRefImpl DicePimpl;
46   const ObjectFile *OwningObject = nullptr;
47
48 public:
49   DiceRef() = default;
50   DiceRef(DataRefImpl DiceP, const ObjectFile *Owner);
51
52   bool operator==(const DiceRef &Other) const;
53   bool operator<(const DiceRef &Other) const;
54
55   void moveNext();
56
57   std::error_code getOffset(uint32_t &Result) const;
58   std::error_code getLength(uint16_t &Result) const;
59   std::error_code getKind(uint16_t &Result) const;
60
61   DataRefImpl getRawDataRefImpl() const;
62   const ObjectFile *getObjectFile() const;
63 };
64 using dice_iterator = content_iterator<DiceRef>;
65
66 /// ExportEntry encapsulates the current-state-of-the-walk used when doing a
67 /// non-recursive walk of the trie data structure.  This allows you to iterate
68 /// across all exported symbols using:
69 ///      for (const llvm::object::ExportEntry &AnExport : Obj->exports()) {
70 ///      }
71 class ExportEntry {
72 public:
73   ExportEntry(ArrayRef<uint8_t> Trie);
74
75   StringRef name() const;
76   uint64_t flags() const;
77   uint64_t address() const;
78   uint64_t other() const;
79   StringRef otherName() const;
80   uint32_t nodeOffset() const;
81
82   bool operator==(const ExportEntry &) const;
83
84   void moveNext();
85
86 private:
87   friend class MachOObjectFile;
88
89   void moveToFirst();
90   void moveToEnd();
91   uint64_t readULEB128(const uint8_t *&p);
92   void pushDownUntilBottom();
93   void pushNode(uint64_t Offset);
94
95   // Represents a node in the mach-o exports trie.
96   struct NodeState {
97     NodeState(const uint8_t *Ptr);
98
99     const uint8_t *Start;
100     const uint8_t *Current;
101     uint64_t Flags = 0;
102     uint64_t Address = 0;
103     uint64_t Other = 0;
104     const char *ImportName = nullptr;
105     unsigned ChildCount = 0;
106     unsigned NextChildIndex = 0;
107     unsigned ParentStringLength = 0;
108     bool IsExportNode = false;
109   };
110
111   ArrayRef<uint8_t> Trie;
112   SmallString<256> CumulativeString;
113   SmallVector<NodeState, 16> Stack;
114   bool Malformed = false;
115   bool Done = false;
116 };
117 using export_iterator = content_iterator<ExportEntry>;
118
119 // Segment info so SegIndex/SegOffset pairs in a Mach-O Bind or Rebase entry
120 // can be checked and translated.  Only the SegIndex/SegOffset pairs from
121 // checked entries are to be used with the segmentName(), sectionName() and
122 // address() methods below.
123 class BindRebaseSegInfo {
124 public:
125   BindRebaseSegInfo(const MachOObjectFile *Obj);
126
127   // Used to check a Mach-O Bind or Rebase entry for errors when iterating.
128   const char *checkSegAndOffset(int32_t SegIndex, uint64_t SegOffset,
129                                 bool endInvalid);
130   const char *checkCountAndSkip(uint32_t Count, uint32_t Skip,
131                                 uint8_t PointerSize, int32_t SegIndex,
132                                 uint64_t SegOffset);
133   // Used with valid SegIndex/SegOffset values from checked entries.
134   StringRef segmentName(int32_t SegIndex);
135   StringRef sectionName(int32_t SegIndex, uint64_t SegOffset);
136   uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
137
138 private:
139   struct SectionInfo {
140     uint64_t Address;
141     uint64_t Size;
142     StringRef SectionName;
143     StringRef SegmentName;
144     uint64_t OffsetInSegment;
145     uint64_t SegmentStartAddress;
146     int32_t SegmentIndex;
147   };
148   const SectionInfo &findSection(int32_t SegIndex, uint64_t SegOffset);
149
150   SmallVector<SectionInfo, 32> Sections;
151   int32_t MaxSegIndex;
152 };
153
154 /// MachORebaseEntry encapsulates the current state in the decompression of
155 /// rebasing opcodes. This allows you to iterate through the compressed table of
156 /// rebasing using:
157 ///    Error Err;
158 ///    for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(&Err)) {
159 ///    }
160 ///    if (Err) { report error ...
161 class MachORebaseEntry {
162 public:
163   MachORebaseEntry(Error *Err, const MachOObjectFile *O,
164                    ArrayRef<uint8_t> opcodes, bool is64Bit);
165
166   int32_t segmentIndex() const;
167   uint64_t segmentOffset() const;
168   StringRef typeName() const;
169   StringRef segmentName() const;
170   StringRef sectionName() const;
171   uint64_t address() const;
172
173   bool operator==(const MachORebaseEntry &) const;
174
175   void moveNext();
176
177 private:
178   friend class MachOObjectFile;
179
180   void moveToFirst();
181   void moveToEnd();
182   uint64_t readULEB128(const char **error);
183
184   Error *E;
185   const MachOObjectFile *O;
186   ArrayRef<uint8_t> Opcodes;
187   const uint8_t *Ptr;
188   uint64_t SegmentOffset = 0;
189   int32_t SegmentIndex = -1;
190   uint64_t RemainingLoopCount = 0;
191   uint64_t AdvanceAmount = 0;
192   uint8_t  RebaseType = 0;
193   uint8_t  PointerSize;
194   bool     Done = false;
195 };
196 using rebase_iterator = content_iterator<MachORebaseEntry>;
197
198 /// MachOBindEntry encapsulates the current state in the decompression of
199 /// binding opcodes. This allows you to iterate through the compressed table of
200 /// bindings using:
201 ///    Error Err;
202 ///    for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(&Err)) {
203 ///    }
204 ///    if (Err) { report error ...
205 class MachOBindEntry {
206 public:
207   enum class Kind { Regular, Lazy, Weak };
208
209   MachOBindEntry(Error *Err, const MachOObjectFile *O,
210                  ArrayRef<uint8_t> Opcodes, bool is64Bit, MachOBindEntry::Kind);
211
212   int32_t segmentIndex() const;
213   uint64_t segmentOffset() const;
214   StringRef typeName() const;
215   StringRef symbolName() const;
216   uint32_t flags() const;
217   int64_t addend() const;
218   int ordinal() const;
219
220   StringRef segmentName() const;
221   StringRef sectionName() const;
222   uint64_t address() const;
223
224   bool operator==(const MachOBindEntry &) const;
225
226   void moveNext();
227
228 private:
229   friend class MachOObjectFile;
230
231   void moveToFirst();
232   void moveToEnd();
233   uint64_t readULEB128(const char **error);
234   int64_t readSLEB128(const char **error);
235
236   Error *E;
237   const MachOObjectFile *O;
238   ArrayRef<uint8_t> Opcodes;
239   const uint8_t *Ptr;
240   uint64_t SegmentOffset = 0;
241   int32_t  SegmentIndex = -1;
242   StringRef SymbolName;
243   bool     LibraryOrdinalSet = false;
244   int      Ordinal = 0;
245   uint32_t Flags = 0;
246   int64_t  Addend = 0;
247   uint64_t RemainingLoopCount = 0;
248   uint64_t AdvanceAmount = 0;
249   uint8_t  BindType = 0;
250   uint8_t  PointerSize;
251   Kind     TableKind;
252   bool     Done = false;
253 };
254 using bind_iterator = content_iterator<MachOBindEntry>;
255
256 class MachOObjectFile : public ObjectFile {
257 public:
258   struct LoadCommandInfo {
259     const char *Ptr;      // Where in memory the load command is.
260     MachO::load_command C; // The command itself.
261   };
262   using LoadCommandList = SmallVector<LoadCommandInfo, 4>;
263   using load_command_iterator = LoadCommandList::const_iterator;
264
265   static Expected<std::unique_ptr<MachOObjectFile>>
266   create(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
267          uint32_t UniversalCputype = 0, uint32_t UniversalIndex = 0);
268
269   void moveSymbolNext(DataRefImpl &Symb) const override;
270
271   uint64_t getNValue(DataRefImpl Sym) const;
272   Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
273
274   // MachO specific.
275   Error checkSymbolTable() const;
276
277   std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const;
278   unsigned getSectionType(SectionRef Sec) const;
279
280   Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
281   uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
282   uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
283   Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
284   uint32_t getSymbolFlags(DataRefImpl Symb) const override;
285   Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
286   unsigned getSymbolSectionID(SymbolRef Symb) const;
287   unsigned getSectionID(SectionRef Sec) const;
288
289   void moveSectionNext(DataRefImpl &Sec) const override;
290   std::error_code getSectionName(DataRefImpl Sec,
291                                  StringRef &Res) const override;
292   uint64_t getSectionAddress(DataRefImpl Sec) const override;
293   uint64_t getSectionIndex(DataRefImpl Sec) const override;
294   uint64_t getSectionSize(DataRefImpl Sec) const override;
295   std::error_code getSectionContents(DataRefImpl Sec,
296                                      StringRef &Res) const override;
297   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
298   bool isSectionCompressed(DataRefImpl Sec) const override;
299   bool isSectionText(DataRefImpl Sec) const override;
300   bool isSectionData(DataRefImpl Sec) const override;
301   bool isSectionBSS(DataRefImpl Sec) const override;
302   bool isSectionVirtual(DataRefImpl Sec) const override;
303   bool isSectionBitcode(DataRefImpl Sec) const override;
304   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
305   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
306
307   void moveRelocationNext(DataRefImpl &Rel) const override;
308   uint64_t getRelocationOffset(DataRefImpl Rel) const override;
309   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
310   section_iterator getRelocationSection(DataRefImpl Rel) const;
311   uint64_t getRelocationType(DataRefImpl Rel) const override;
312   void getRelocationTypeName(DataRefImpl Rel,
313                              SmallVectorImpl<char> &Result) const override;
314   uint8_t getRelocationLength(DataRefImpl Rel) const;
315
316   // MachO specific.
317   std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const;
318   uint32_t getLibraryCount() const;
319
320   section_iterator getRelocationRelocatedSection(relocation_iterator Rel) const;
321
322   // TODO: Would be useful to have an iterator based version
323   // of the load command interface too.
324
325   basic_symbol_iterator symbol_begin() const override;
326   basic_symbol_iterator symbol_end() const override;
327
328   // MachO specific.
329   basic_symbol_iterator getSymbolByIndex(unsigned Index) const;
330   uint64_t getSymbolIndex(DataRefImpl Symb) const;
331
332   section_iterator section_begin() const override;
333   section_iterator section_end() const override;
334
335   uint8_t getBytesInAddress() const override;
336
337   StringRef getFileFormatName() const override;
338   unsigned getArch() const override;
339   SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); }
340   Triple getArchTriple(const char **McpuDefault = nullptr) const;
341
342   relocation_iterator section_rel_begin(unsigned Index) const;
343   relocation_iterator section_rel_end(unsigned Index) const;
344
345   dice_iterator begin_dices() const;
346   dice_iterator end_dices() const;
347
348   load_command_iterator begin_load_commands() const;
349   load_command_iterator end_load_commands() const;
350   iterator_range<load_command_iterator> load_commands() const;
351
352   /// For use iterating over all exported symbols.
353   iterator_range<export_iterator> exports() const;
354
355   /// For use examining a trie not in a MachOObjectFile.
356   static iterator_range<export_iterator> exports(ArrayRef<uint8_t> Trie);
357
358   /// For use iterating over all rebase table entries.
359   iterator_range<rebase_iterator> rebaseTable(Error &Err);
360
361   /// For use examining rebase opcodes in a MachOObjectFile.
362   static iterator_range<rebase_iterator> rebaseTable(Error &Err,
363                                                      MachOObjectFile *O,
364                                                      ArrayRef<uint8_t> Opcodes,
365                                                      bool is64);
366
367   /// For use iterating over all bind table entries.
368   iterator_range<bind_iterator> bindTable(Error &Err);
369
370   /// For use iterating over all lazy bind table entries.
371   iterator_range<bind_iterator> lazyBindTable(Error &Err);
372
373   /// For use iterating over all weak bind table entries.
374   iterator_range<bind_iterator> weakBindTable(Error &Err);
375
376   /// For use examining bind opcodes in a MachOObjectFile.
377   static iterator_range<bind_iterator> bindTable(Error &Err,
378                                                  MachOObjectFile *O,
379                                                  ArrayRef<uint8_t> Opcodes,
380                                                  bool is64,
381                                                  MachOBindEntry::Kind);
382
383   /// For use with a SegIndex,SegOffset pair in MachOBindEntry::moveNext() to
384   /// validate a MachOBindEntry.
385   const char *BindEntryCheckSegAndOffset(int32_t SegIndex, uint64_t SegOffset,
386                                          bool endInvalid) const {
387     return BindRebaseSectionTable->checkSegAndOffset(SegIndex, SegOffset,
388                                                      endInvalid);
389   }
390   /// For use in MachOBindEntry::moveNext() to validate a MachOBindEntry for
391   /// the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode.
392   const char *BindEntryCheckCountAndSkip(uint32_t Count, uint32_t Skip,
393                                          uint8_t PointerSize, int32_t SegIndex,
394                                          uint64_t SegOffset) const {
395     return BindRebaseSectionTable->checkCountAndSkip(Count, Skip, PointerSize,
396                                                      SegIndex, SegOffset);
397   }
398
399   /// For use with a SegIndex,SegOffset pair in MachORebaseEntry::moveNext() to
400   /// validate a MachORebaseEntry.
401   const char *RebaseEntryCheckSegAndOffset(int32_t SegIndex, uint64_t SegOffset,
402                                            bool endInvalid) const {
403     return BindRebaseSectionTable->checkSegAndOffset(SegIndex, SegOffset,
404                                                      endInvalid);
405   }
406   /// For use in MachORebaseEntry::moveNext() to validate a MachORebaseEntry for
407   /// the REBASE_OPCODE_DO_*_TIMES* opcodes.
408   const char *RebaseEntryCheckCountAndSkip(uint32_t Count, uint32_t Skip,
409                                          uint8_t PointerSize, int32_t SegIndex,
410                                          uint64_t SegOffset) const {
411     return BindRebaseSectionTable->checkCountAndSkip(Count, Skip, PointerSize,
412                                                      SegIndex, SegOffset);
413   }
414
415   /// For use with the SegIndex of a checked Mach-O Bind or Rebase entry to
416   /// get the segment name.
417   StringRef BindRebaseSegmentName(int32_t SegIndex) const {
418     return BindRebaseSectionTable->segmentName(SegIndex);
419   }
420
421   /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
422   /// Rebase entry to get the section name.
423   StringRef BindRebaseSectionName(uint32_t SegIndex, uint64_t SegOffset) const {
424     return BindRebaseSectionTable->sectionName(SegIndex, SegOffset);
425   }
426
427   /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
428   /// Rebase entry to get the address.
429   uint64_t BindRebaseAddress(uint32_t SegIndex, uint64_t SegOffset) const {
430     return BindRebaseSectionTable->address(SegIndex, SegOffset);
431   }
432
433   // In a MachO file, sections have a segment name. This is used in the .o
434   // files. They have a single segment, but this field specifies which segment
435   // a section should be put in in the final object.
436   StringRef getSectionFinalSegmentName(DataRefImpl Sec) const;
437
438   // Names are stored as 16 bytes. These returns the raw 16 bytes without
439   // interpreting them as a C string.
440   ArrayRef<char> getSectionRawName(DataRefImpl Sec) const;
441   ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const;
442
443   // MachO specific Info about relocations.
444   bool isRelocationScattered(const MachO::any_relocation_info &RE) const;
445   unsigned getPlainRelocationSymbolNum(
446                                     const MachO::any_relocation_info &RE) const;
447   bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const;
448   bool getScatteredRelocationScattered(
449                                     const MachO::any_relocation_info &RE) const;
450   uint32_t getScatteredRelocationValue(
451                                     const MachO::any_relocation_info &RE) const;
452   uint32_t getScatteredRelocationType(
453                                     const MachO::any_relocation_info &RE) const;
454   unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const;
455   unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const;
456   unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const;
457   unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const;
458   SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const;
459
460   // MachO specific structures.
461   MachO::section getSection(DataRefImpl DRI) const;
462   MachO::section_64 getSection64(DataRefImpl DRI) const;
463   MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const;
464   MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const;
465   MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const;
466   MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const;
467
468   MachO::linkedit_data_command
469   getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
470   MachO::segment_command
471   getSegmentLoadCommand(const LoadCommandInfo &L) const;
472   MachO::segment_command_64
473   getSegment64LoadCommand(const LoadCommandInfo &L) const;
474   MachO::linker_option_command
475   getLinkerOptionLoadCommand(const LoadCommandInfo &L) const;
476   MachO::version_min_command
477   getVersionMinLoadCommand(const LoadCommandInfo &L) const;
478   MachO::note_command
479   getNoteLoadCommand(const LoadCommandInfo &L) const;
480   MachO::build_version_command
481   getBuildVersionLoadCommand(const LoadCommandInfo &L) const;
482   MachO::build_tool_version
483   getBuildToolVersion(unsigned index) const;
484   MachO::dylib_command
485   getDylibIDLoadCommand(const LoadCommandInfo &L) const;
486   MachO::dyld_info_command
487   getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
488   MachO::dylinker_command
489   getDylinkerCommand(const LoadCommandInfo &L) const;
490   MachO::uuid_command
491   getUuidCommand(const LoadCommandInfo &L) const;
492   MachO::rpath_command
493   getRpathCommand(const LoadCommandInfo &L) const;
494   MachO::source_version_command
495   getSourceVersionCommand(const LoadCommandInfo &L) const;
496   MachO::entry_point_command
497   getEntryPointCommand(const LoadCommandInfo &L) const;
498   MachO::encryption_info_command
499   getEncryptionInfoCommand(const LoadCommandInfo &L) const;
500   MachO::encryption_info_command_64
501   getEncryptionInfoCommand64(const LoadCommandInfo &L) const;
502   MachO::sub_framework_command
503   getSubFrameworkCommand(const LoadCommandInfo &L) const;
504   MachO::sub_umbrella_command
505   getSubUmbrellaCommand(const LoadCommandInfo &L) const;
506   MachO::sub_library_command
507   getSubLibraryCommand(const LoadCommandInfo &L) const;
508   MachO::sub_client_command
509   getSubClientCommand(const LoadCommandInfo &L) const;
510   MachO::routines_command
511   getRoutinesCommand(const LoadCommandInfo &L) const;
512   MachO::routines_command_64
513   getRoutinesCommand64(const LoadCommandInfo &L) const;
514   MachO::thread_command
515   getThreadCommand(const LoadCommandInfo &L) const;
516
517   MachO::any_relocation_info getRelocation(DataRefImpl Rel) const;
518   MachO::data_in_code_entry getDice(DataRefImpl Rel) const;
519   const MachO::mach_header &getHeader() const;
520   const MachO::mach_header_64 &getHeader64() const;
521   uint32_t
522   getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC,
523                               unsigned Index) const;
524   MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset,
525                                                     unsigned Index) const;
526   MachO::symtab_command getSymtabLoadCommand() const;
527   MachO::dysymtab_command getDysymtabLoadCommand() const;
528   MachO::linkedit_data_command getDataInCodeLoadCommand() const;
529   MachO::linkedit_data_command getLinkOptHintsLoadCommand() const;
530   ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const;
531   ArrayRef<uint8_t> getDyldInfoBindOpcodes() const;
532   ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const;
533   ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const;
534   ArrayRef<uint8_t> getDyldInfoExportsTrie() const;
535   ArrayRef<uint8_t> getUuid() const;
536
537   StringRef getStringTableData() const;
538   bool is64Bit() const;
539   void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
540
541   static StringRef guessLibraryShortName(StringRef Name, bool &isFramework,
542                                          StringRef &Suffix);
543
544   static Triple::ArchType getArch(uint32_t CPUType);
545   static Triple getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
546                               const char **McpuDefault = nullptr,
547                               const char **ArchFlag = nullptr);
548   static bool isValidArch(StringRef ArchFlag);
549   static Triple getHostArch();
550
551   bool isRelocatableObject() const override;
552
553   bool hasPageZeroSegment() const { return HasPageZeroSegment; }
554
555   static bool classof(const Binary *v) {
556     return v->isMachO();
557   }
558
559   static uint32_t
560   getVersionMinMajor(MachO::version_min_command &C, bool SDK) {
561     uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
562     return (VersionOrSDK >> 16) & 0xffff;
563   }
564
565   static uint32_t
566   getVersionMinMinor(MachO::version_min_command &C, bool SDK) {
567     uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
568     return (VersionOrSDK >> 8) & 0xff;
569   }
570
571   static uint32_t
572   getVersionMinUpdate(MachO::version_min_command &C, bool SDK) {
573     uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
574     return VersionOrSDK & 0xff;
575   }
576
577   static std::string getBuildPlatform(uint32_t platform) {
578     switch (platform) {
579     case MachO::PLATFORM_MACOS: return "macos";
580     case MachO::PLATFORM_IOS: return "ios";
581     case MachO::PLATFORM_TVOS: return "tvos";
582     case MachO::PLATFORM_WATCHOS: return "watchos";
583     case MachO::PLATFORM_BRIDGEOS: return "bridgeos";
584     default:
585       std::string ret;
586       raw_string_ostream ss(ret);
587       ss << format_hex(platform, 8, true);
588       return ss.str();
589     }
590   }
591
592   static std::string getBuildTool(uint32_t tools) {
593     switch (tools) {
594     case MachO::TOOL_CLANG: return "clang";
595     case MachO::TOOL_SWIFT: return "swift";
596     case MachO::TOOL_LD: return "ld";
597     default:
598       std::string ret;
599       raw_string_ostream ss(ret);
600       ss << format_hex(tools, 8, true);
601       return ss.str();
602     }
603   }
604
605   static std::string getVersionString(uint32_t version) {
606     uint32_t major = (version >> 16) & 0xffff;
607     uint32_t minor = (version >> 8) & 0xff;
608     uint32_t update = version & 0xff;
609
610     SmallString<32> Version;
611     Version = utostr(major) + "." + utostr(minor);
612     if (update != 0)
613       Version += "." + utostr(update);
614     return Version.str();
615   }
616
617 private:
618   MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
619                   Error &Err, uint32_t UniversalCputype = 0,
620                   uint32_t UniversalIndex = 0);
621
622   uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
623
624   union {
625     MachO::mach_header_64 Header64;
626     MachO::mach_header Header;
627   };
628   using SectionList = SmallVector<const char*, 1>;
629   SectionList Sections;
630   using LibraryList = SmallVector<const char*, 1>;
631   LibraryList Libraries;
632   LoadCommandList LoadCommands;
633   using LibraryShortName = SmallVector<StringRef, 1>;
634   using BuildToolList = SmallVector<const char*, 1>;
635   BuildToolList BuildTools;
636   mutable LibraryShortName LibrariesShortNames;
637   std::unique_ptr<BindRebaseSegInfo> BindRebaseSectionTable;
638   const char *SymtabLoadCmd = nullptr;
639   const char *DysymtabLoadCmd = nullptr;
640   const char *DataInCodeLoadCmd = nullptr;
641   const char *LinkOptHintsLoadCmd = nullptr;
642   const char *DyldInfoLoadCmd = nullptr;
643   const char *UuidLoadCmd = nullptr;
644   bool HasPageZeroSegment = false;
645 };
646
647 /// DiceRef
648 inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner)
649   : DicePimpl(DiceP) , OwningObject(Owner) {}
650
651 inline bool DiceRef::operator==(const DiceRef &Other) const {
652   return DicePimpl == Other.DicePimpl;
653 }
654
655 inline bool DiceRef::operator<(const DiceRef &Other) const {
656   return DicePimpl < Other.DicePimpl;
657 }
658
659 inline void DiceRef::moveNext() {
660   const MachO::data_in_code_entry *P =
661     reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p);
662   DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1);
663 }
664
665 // Since a Mach-O data in code reference, a DiceRef, can only be created when
666 // the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for
667 // the methods that get the values of the fields of the reference.
668
669 inline std::error_code DiceRef::getOffset(uint32_t &Result) const {
670   const MachOObjectFile *MachOOF =
671     static_cast<const MachOObjectFile *>(OwningObject);
672   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
673   Result = Dice.offset;
674   return std::error_code();
675 }
676
677 inline std::error_code DiceRef::getLength(uint16_t &Result) const {
678   const MachOObjectFile *MachOOF =
679     static_cast<const MachOObjectFile *>(OwningObject);
680   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
681   Result = Dice.length;
682   return std::error_code();
683 }
684
685 inline std::error_code DiceRef::getKind(uint16_t &Result) const {
686   const MachOObjectFile *MachOOF =
687     static_cast<const MachOObjectFile *>(OwningObject);
688   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
689   Result = Dice.kind;
690   return std::error_code();
691 }
692
693 inline DataRefImpl DiceRef::getRawDataRefImpl() const {
694   return DicePimpl;
695 }
696
697 inline const ObjectFile *DiceRef::getObjectFile() const {
698   return OwningObject;
699 }
700
701 } // end namespace object
702 } // end namespace llvm
703
704 #endif // LLVM_OBJECT_MACHO_H