xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Object/MachO.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- MachO.h - MachO object file implementation ---------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the MachOObjectFile class, which implement the ObjectFile
10 // interface for MachO files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_OBJECT_MACHO_H
15 #define LLVM_OBJECT_MACHO_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/BinaryFormat/MachO.h"
24 #include "llvm/BinaryFormat/Swift.h"
25 #include "llvm/Object/Binary.h"
26 #include "llvm/Object/ObjectFile.h"
27 #include "llvm/Object/SymbolicFile.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/TargetParser/SubtargetFeature.h"
34 #include "llvm/TargetParser/Triple.h"
35 #include <cstdint>
36 #include <memory>
37 #include <string>
38 #include <system_error>
39 
40 namespace llvm {
41 namespace object {
42 
43 /// DiceRef - This is a value type class that represents a single
44 /// data in code entry in the table in a Mach-O object file.
45 class DiceRef {
46   DataRefImpl DicePimpl;
47   const ObjectFile *OwningObject = nullptr;
48 
49 public:
50   DiceRef() = default;
51   DiceRef(DataRefImpl DiceP, const ObjectFile *Owner);
52 
53   bool operator==(const DiceRef &Other) const;
54   bool operator<(const DiceRef &Other) const;
55 
56   void moveNext();
57 
58   std::error_code getOffset(uint32_t &Result) const;
59   std::error_code getLength(uint16_t &Result) const;
60   std::error_code getKind(uint16_t &Result) const;
61 
62   DataRefImpl getRawDataRefImpl() const;
63   const ObjectFile *getObjectFile() const;
64 };
65 using dice_iterator = content_iterator<DiceRef>;
66 
67 /// ExportEntry encapsulates the current-state-of-the-walk used when doing a
68 /// non-recursive walk of the trie data structure.  This allows you to iterate
69 /// across all exported symbols using:
70 ///      Error Err = Error::success();
71 ///      for (const llvm::object::ExportEntry &AnExport : Obj->exports(&Err)) {
72 ///      }
73 ///      if (Err) { report error ...
74 class ExportEntry {
75 public:
76   LLVM_ABI ExportEntry(Error *Err, const MachOObjectFile *O,
77                        ArrayRef<uint8_t> Trie);
78 
79   LLVM_ABI StringRef name() const;
80   LLVM_ABI uint64_t flags() const;
81   LLVM_ABI uint64_t address() const;
82   LLVM_ABI uint64_t other() const;
83   LLVM_ABI StringRef otherName() const;
84   LLVM_ABI uint32_t nodeOffset() const;
85 
86   LLVM_ABI bool operator==(const ExportEntry &) const;
87 
88   LLVM_ABI void moveNext();
89 
90 private:
91   friend class MachOObjectFile;
92 
93   void moveToFirst();
94   void moveToEnd();
95   uint64_t readULEB128(const uint8_t *&p, const char **error);
96   void pushDownUntilBottom();
97   void pushNode(uint64_t Offset);
98 
99   // Represents a node in the mach-o exports trie.
100   struct NodeState {
101     LLVM_ABI NodeState(const uint8_t *Ptr);
102 
103     const uint8_t *Start;
104     const uint8_t *Current;
105     uint64_t Flags = 0;
106     uint64_t Address = 0;
107     uint64_t Other = 0;
108     const char *ImportName = nullptr;
109     unsigned ChildCount = 0;
110     unsigned NextChildIndex = 0;
111     unsigned ParentStringLength = 0;
112     bool IsExportNode = false;
113   };
114   using NodeList = SmallVector<NodeState, 16>;
115   using node_iterator = NodeList::const_iterator;
116 
117   Error *E;
118   const MachOObjectFile *O;
119   ArrayRef<uint8_t> Trie;
120   SmallString<256> CumulativeString;
121   NodeList Stack;
122   bool Done = false;
123 
nodes()124   iterator_range<node_iterator> nodes() const {
125     return make_range(Stack.begin(), Stack.end());
126   }
127 };
128 using export_iterator = content_iterator<ExportEntry>;
129 
130 // Segment info so SegIndex/SegOffset pairs in a Mach-O Bind or Rebase entry
131 // can be checked and translated.  Only the SegIndex/SegOffset pairs from
132 // checked entries are to be used with the segmentName(), sectionName() and
133 // address() methods below.
134 class BindRebaseSegInfo {
135 public:
136   LLVM_ABI BindRebaseSegInfo(const MachOObjectFile *Obj);
137 
138   // Used to check a Mach-O Bind or Rebase entry for errors when iterating.
139   LLVM_ABI const char *checkSegAndOffsets(int32_t SegIndex, uint64_t SegOffset,
140                                           uint8_t PointerSize,
141                                           uint64_t Count = 1,
142                                           uint64_t Skip = 0);
143   // Used with valid SegIndex/SegOffset values from checked entries.
144   LLVM_ABI StringRef segmentName(int32_t SegIndex);
145   LLVM_ABI StringRef sectionName(int32_t SegIndex, uint64_t SegOffset);
146   LLVM_ABI uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
147 
148 private:
149   struct SectionInfo {
150     uint64_t Address;
151     uint64_t Size;
152     StringRef SectionName;
153     StringRef SegmentName;
154     uint64_t OffsetInSegment;
155     uint64_t SegmentStartAddress;
156     int32_t SegmentIndex;
157   };
158   const SectionInfo &findSection(int32_t SegIndex, uint64_t SegOffset);
159 
160   SmallVector<SectionInfo, 32> Sections;
161   int32_t MaxSegIndex;
162 };
163 
164 /// MachORebaseEntry encapsulates the current state in the decompression of
165 /// rebasing opcodes. This allows you to iterate through the compressed table of
166 /// rebasing using:
167 ///    Error Err = Error::success();
168 ///    for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(&Err)) {
169 ///    }
170 ///    if (Err) { report error ...
171 class MachORebaseEntry {
172 public:
173   LLVM_ABI MachORebaseEntry(Error *Err, const MachOObjectFile *O,
174                             ArrayRef<uint8_t> opcodes, bool is64Bit);
175 
176   LLVM_ABI int32_t segmentIndex() const;
177   LLVM_ABI uint64_t segmentOffset() const;
178   LLVM_ABI StringRef typeName() const;
179   LLVM_ABI StringRef segmentName() const;
180   LLVM_ABI StringRef sectionName() const;
181   LLVM_ABI uint64_t address() const;
182 
183   LLVM_ABI bool operator==(const MachORebaseEntry &) const;
184 
185   LLVM_ABI void moveNext();
186 
187 private:
188   friend class MachOObjectFile;
189 
190   void moveToFirst();
191   void moveToEnd();
192   uint64_t readULEB128(const char **error);
193 
194   Error *E;
195   const MachOObjectFile *O;
196   ArrayRef<uint8_t> Opcodes;
197   const uint8_t *Ptr;
198   uint64_t SegmentOffset = 0;
199   int32_t SegmentIndex = -1;
200   uint64_t RemainingLoopCount = 0;
201   uint64_t AdvanceAmount = 0;
202   uint8_t  RebaseType = 0;
203   uint8_t  PointerSize;
204   bool     Done = false;
205 };
206 using rebase_iterator = content_iterator<MachORebaseEntry>;
207 
208 /// MachOBindEntry encapsulates the current state in the decompression of
209 /// binding opcodes. This allows you to iterate through the compressed table of
210 /// bindings using:
211 ///    Error Err = Error::success();
212 ///    for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(&Err)) {
213 ///    }
214 ///    if (Err) { report error ...
215 class MachOBindEntry {
216 public:
217   enum class Kind { Regular, Lazy, Weak };
218 
219   LLVM_ABI MachOBindEntry(Error *Err, const MachOObjectFile *O,
220                           ArrayRef<uint8_t> Opcodes, bool is64Bit,
221                           MachOBindEntry::Kind);
222 
223   LLVM_ABI int32_t segmentIndex() const;
224   LLVM_ABI uint64_t segmentOffset() const;
225   LLVM_ABI StringRef typeName() const;
226   LLVM_ABI StringRef symbolName() const;
227   LLVM_ABI uint32_t flags() const;
228   LLVM_ABI int64_t addend() const;
229   LLVM_ABI int ordinal() const;
230 
231   LLVM_ABI StringRef segmentName() const;
232   LLVM_ABI StringRef sectionName() const;
233   LLVM_ABI uint64_t address() const;
234 
235   LLVM_ABI bool operator==(const MachOBindEntry &) const;
236 
237   LLVM_ABI void moveNext();
238 
239 private:
240   friend class MachOObjectFile;
241 
242   void moveToFirst();
243   void moveToEnd();
244   uint64_t readULEB128(const char **error);
245   int64_t readSLEB128(const char **error);
246 
247   Error *E;
248   const MachOObjectFile *O;
249   ArrayRef<uint8_t> Opcodes;
250   const uint8_t *Ptr;
251   uint64_t SegmentOffset = 0;
252   int32_t  SegmentIndex = -1;
253   StringRef SymbolName;
254   bool     LibraryOrdinalSet = false;
255   int      Ordinal = 0;
256   uint32_t Flags = 0;
257   int64_t  Addend = 0;
258   uint64_t RemainingLoopCount = 0;
259   uint64_t AdvanceAmount = 0;
260   uint8_t  BindType = 0;
261   uint8_t  PointerSize;
262   Kind     TableKind;
263   bool     Done = false;
264 };
265 using bind_iterator = content_iterator<MachOBindEntry>;
266 
267 /// ChainedFixupTarget holds all the information about an external symbol
268 /// necessary to bind this binary to that symbol. These values are referenced
269 /// indirectly by chained fixup binds. This structure captures values from all
270 /// import and symbol formats.
271 ///
272 /// Be aware there are two notions of weak here:
273 ///   WeakImport == true
274 ///     The associated bind may be set to 0 if this symbol is missing from its
275 ///     parent library. This is called a "weak import."
276 ///   LibOrdinal == BIND_SPECIAL_DYLIB_WEAK_LOOKUP
277 ///     This symbol may be coalesced with other libraries vending the same
278 ///     symbol. E.g., C++'s "operator new". This is called a "weak bind."
279 struct ChainedFixupTarget {
280 public:
ChainedFixupTargetChainedFixupTarget281   ChainedFixupTarget(int LibOrdinal, uint32_t NameOffset, StringRef Symbol,
282                      uint64_t Addend, bool WeakImport)
283       : LibOrdinal(LibOrdinal), NameOffset(NameOffset), SymbolName(Symbol),
284         Addend(Addend), WeakImport(WeakImport) {}
285 
libOrdinalChainedFixupTarget286   int libOrdinal() { return LibOrdinal; }
nameOffsetChainedFixupTarget287   uint32_t nameOffset() { return NameOffset; }
symbolNameChainedFixupTarget288   StringRef symbolName() { return SymbolName; }
addendChainedFixupTarget289   uint64_t addend() { return Addend; }
weakImportChainedFixupTarget290   bool weakImport() { return WeakImport; }
weakBindChainedFixupTarget291   bool weakBind() {
292     return LibOrdinal == MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP;
293   }
294 
295 private:
296   int LibOrdinal;
297   uint32_t NameOffset;
298   StringRef SymbolName;
299   uint64_t Addend;
300   bool WeakImport;
301 };
302 
303 struct ChainedFixupsSegment {
ChainedFixupsSegmentChainedFixupsSegment304   ChainedFixupsSegment(uint8_t SegIdx, uint32_t Offset,
305                        const MachO::dyld_chained_starts_in_segment &Header,
306                        std::vector<uint16_t> &&PageStarts)
307       : SegIdx(SegIdx), Offset(Offset), Header(Header),
308         PageStarts(PageStarts){};
309 
310   uint32_t SegIdx;
311   uint32_t Offset; // dyld_chained_starts_in_image::seg_info_offset[SegIdx]
312   MachO::dyld_chained_starts_in_segment Header;
313   std::vector<uint16_t> PageStarts; // page_start[] entries, host endianness
314 };
315 
316 /// MachOAbstractFixupEntry is an abstract class representing a fixup in a
317 /// MH_DYLDLINK file. Fixups generally represent rebases and binds. Binds also
318 /// subdivide into additional subtypes (weak, lazy, reexport).
319 ///
320 /// The two concrete subclasses of MachOAbstractFixupEntry are:
321 ///
322 ///   MachORebaseBindEntry   - for dyld opcode-based tables, including threaded-
323 ///                            rebase, where rebases are mixed in with other
324 ///                            bind opcodes.
325 ///   MachOChainedFixupEntry - for pointer chains embedded in data pages.
326 class MachOAbstractFixupEntry {
327 public:
328   LLVM_ABI MachOAbstractFixupEntry(Error *Err, const MachOObjectFile *O);
329 
330   LLVM_ABI int32_t segmentIndex() const;
331   LLVM_ABI uint64_t segmentOffset() const;
332   LLVM_ABI uint64_t segmentAddress() const;
333   LLVM_ABI StringRef segmentName() const;
334   LLVM_ABI StringRef sectionName() const;
335   LLVM_ABI StringRef typeName() const;
336   LLVM_ABI StringRef symbolName() const;
337   LLVM_ABI uint32_t flags() const;
338   LLVM_ABI int64_t addend() const;
339   LLVM_ABI int ordinal() const;
340 
341   /// \return the location of this fixup as a VM Address. For the VM
342   /// Address this fixup is pointing to, use pointerValue().
343   LLVM_ABI uint64_t address() const;
344 
345   /// \return the VM Address pointed to by this fixup. Use
346   /// pointerValue() to compare against other VM Addresses, such as
347   /// section addresses or segment vmaddrs.
pointerValue()348   uint64_t pointerValue() const { return PointerValue; }
349 
350   /// \return the raw "on-disk" representation of the fixup. For
351   /// Threaded rebases and Chained pointers these values are generally
352   /// encoded into various different pointer formats. This value is
353   /// exposed in API for tools that want to display and annotate the
354   /// raw bits.
rawValue()355   uint64_t rawValue() const { return RawValue; }
356 
357   LLVM_ABI void moveNext();
358 
359 protected:
360   Error *E;
361   const MachOObjectFile *O;
362   uint64_t SegmentOffset = 0;
363   int32_t SegmentIndex = -1;
364   StringRef SymbolName;
365   int32_t Ordinal = 0;
366   uint32_t Flags = 0;
367   int64_t Addend = 0;
368   uint64_t PointerValue = 0;
369   uint64_t RawValue = 0;
370   bool Done = false;
371 
372   LLVM_ABI void moveToFirst();
373   LLVM_ABI void moveToEnd();
374 
375   /// \return the vm address of the start of __TEXT segment.
textAddress()376   uint64_t textAddress() const { return TextAddress; }
377 
378 private:
379   uint64_t TextAddress;
380 };
381 
382 class MachOChainedFixupEntry : public MachOAbstractFixupEntry {
383 public:
384   enum class FixupKind { Bind, Rebase };
385 
386   LLVM_ABI MachOChainedFixupEntry(Error *Err, const MachOObjectFile *O,
387                                   bool Parse);
388 
389   LLVM_ABI bool operator==(const MachOChainedFixupEntry &) const;
390 
isBind()391   bool isBind() const { return Kind == FixupKind::Bind; }
isRebase()392   bool isRebase() const { return Kind == FixupKind::Rebase; }
393 
394   LLVM_ABI void moveNext();
395   LLVM_ABI void moveToFirst();
396   LLVM_ABI void moveToEnd();
397 
398 private:
399   void findNextPageWithFixups();
400 
401   std::vector<ChainedFixupTarget> FixupTargets;
402   std::vector<ChainedFixupsSegment> Segments;
403   ArrayRef<uint8_t> SegmentData;
404   FixupKind Kind;
405   uint32_t InfoSegIndex = 0; // Index into Segments
406   uint32_t PageIndex = 0;    // Index into Segments[InfoSegIdx].PageStarts
407   uint32_t PageOffset = 0;   // Page offset of the current fixup
408 };
409 using fixup_iterator = content_iterator<MachOChainedFixupEntry>;
410 
411 class LLVM_ABI MachOObjectFile : public ObjectFile {
412 public:
413   struct LoadCommandInfo {
414     const char *Ptr;      // Where in memory the load command is.
415     MachO::load_command C; // The command itself.
416   };
417   using LoadCommandList = SmallVector<LoadCommandInfo, 4>;
418   using load_command_iterator = LoadCommandList::const_iterator;
419 
420   static Expected<std::unique_ptr<MachOObjectFile>>
421   create(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
422          uint32_t UniversalCputype = 0, uint32_t UniversalIndex = 0,
423          size_t MachOFilesetEntryOffset = 0);
424 
425   static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch);
426 
427   void moveSymbolNext(DataRefImpl &Symb) const override;
428 
429   uint64_t getNValue(DataRefImpl Sym) const;
430   Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
431 
432   // MachO specific.
433   Error checkSymbolTable() const;
434 
435   std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const;
436   unsigned getSectionType(SectionRef Sec) const;
437 
438   Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
439   uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
440   uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
441   Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
442   Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
443   Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
444   unsigned getSymbolSectionID(SymbolRef Symb) const;
445   unsigned getSectionID(SectionRef Sec) const;
446 
447   void moveSectionNext(DataRefImpl &Sec) const override;
448   Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
449   uint64_t getSectionAddress(DataRefImpl Sec) const override;
450   uint64_t getSectionIndex(DataRefImpl Sec) const override;
451   uint64_t getSectionSize(DataRefImpl Sec) const override;
452   ArrayRef<uint8_t> getSectionContents(uint32_t Offset, uint64_t Size) const;
453   Expected<ArrayRef<uint8_t>>
454   getSectionContents(DataRefImpl Sec) const override;
455   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
456   Expected<SectionRef> getSection(unsigned SectionIndex) const;
457   Expected<SectionRef> getSection(StringRef SectionName) const;
458   bool isSectionCompressed(DataRefImpl Sec) const override;
459   bool isSectionText(DataRefImpl Sec) const override;
460   bool isSectionData(DataRefImpl Sec) const override;
461   bool isSectionBSS(DataRefImpl Sec) const override;
462   bool isSectionVirtual(DataRefImpl Sec) const override;
463   bool isSectionBitcode(DataRefImpl Sec) const override;
464   bool isDebugSection(DataRefImpl Sec) const override;
465 
466   /// Return the raw contents of an entire segment.
467   ArrayRef<uint8_t> getSegmentContents(StringRef SegmentName) const;
468   ArrayRef<uint8_t> getSegmentContents(size_t SegmentIndex) const;
469 
470   /// When dsymutil generates the companion file, it strips all unnecessary
471   /// sections (e.g. everything in the _TEXT segment) by omitting their body
472   /// and setting the offset in their corresponding load command to zero.
473   ///
474   /// While the load command itself is valid, reading the section corresponds
475   /// to reading the number of bytes specified in the load command, starting
476   /// from offset 0 (i.e. the Mach-O header at the beginning of the file).
477   bool isSectionStripped(DataRefImpl Sec) const override;
478 
479   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
480   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
481 
482   relocation_iterator extrel_begin() const;
483   relocation_iterator extrel_end() const;
external_relocations()484   iterator_range<relocation_iterator> external_relocations() const {
485     return make_range(extrel_begin(), extrel_end());
486   }
487 
488   relocation_iterator locrel_begin() const;
489   relocation_iterator locrel_end() const;
490 
491   void moveRelocationNext(DataRefImpl &Rel) const override;
492   uint64_t getRelocationOffset(DataRefImpl Rel) const override;
493   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
494   section_iterator getRelocationSection(DataRefImpl Rel) const;
495   uint64_t getRelocationType(DataRefImpl Rel) const override;
496   void getRelocationTypeName(DataRefImpl Rel,
497                              SmallVectorImpl<char> &Result) const override;
498   uint8_t getRelocationLength(DataRefImpl Rel) const;
499 
500   // MachO specific.
501   std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const;
502   uint32_t getLibraryCount() const;
503 
504   section_iterator getRelocationRelocatedSection(relocation_iterator Rel) const;
505 
506   // TODO: Would be useful to have an iterator based version
507   // of the load command interface too.
508 
509   basic_symbol_iterator symbol_begin() const override;
510   basic_symbol_iterator symbol_end() const override;
511 
512   bool is64Bit() const override;
513 
514   // MachO specific.
515   symbol_iterator getSymbolByIndex(unsigned Index) const;
516   uint64_t getSymbolIndex(DataRefImpl Symb) const;
517 
518   section_iterator section_begin() const override;
519   section_iterator section_end() const override;
520 
521   uint8_t getBytesInAddress() const override;
522 
523   StringRef getFileFormatName() const override;
524   Triple::ArchType getArch() const override;
getFeatures()525   Expected<SubtargetFeatures> getFeatures() const override {
526     return SubtargetFeatures();
527   }
528   Triple getArchTriple(const char **McpuDefault = nullptr) const;
529 
530   relocation_iterator section_rel_begin(unsigned Index) const;
531   relocation_iterator section_rel_end(unsigned Index) const;
532 
533   dice_iterator begin_dices() const;
534   dice_iterator end_dices() const;
535 
536   load_command_iterator begin_load_commands() const;
537   load_command_iterator end_load_commands() const;
538   iterator_range<load_command_iterator> load_commands() const;
539 
540   /// For use iterating over all exported symbols.
541   iterator_range<export_iterator> exports(Error &Err) const;
542 
543   /// For use examining a trie not in a MachOObjectFile.
544   static iterator_range<export_iterator> exports(Error &Err,
545                                                  ArrayRef<uint8_t> Trie,
546                                                  const MachOObjectFile *O =
547                                                                       nullptr);
548 
549   /// For use iterating over all rebase table entries.
550   iterator_range<rebase_iterator> rebaseTable(Error &Err);
551 
552   /// For use examining rebase opcodes in a MachOObjectFile.
553   static iterator_range<rebase_iterator> rebaseTable(Error &Err,
554                                                      MachOObjectFile *O,
555                                                      ArrayRef<uint8_t> Opcodes,
556                                                      bool is64);
557 
558   /// For use iterating over all bind table entries.
559   iterator_range<bind_iterator> bindTable(Error &Err);
560 
561   /// For iterating over all chained fixups.
562   iterator_range<fixup_iterator> fixupTable(Error &Err);
563 
564   /// For use iterating over all lazy bind table entries.
565   iterator_range<bind_iterator> lazyBindTable(Error &Err);
566 
567   /// For use iterating over all weak bind table entries.
568   iterator_range<bind_iterator> weakBindTable(Error &Err);
569 
570   /// For use examining bind opcodes in a MachOObjectFile.
571   static iterator_range<bind_iterator> bindTable(Error &Err,
572                                                  MachOObjectFile *O,
573                                                  ArrayRef<uint8_t> Opcodes,
574                                                  bool is64,
575                                                  MachOBindEntry::Kind);
576 
577   // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
578   // that fully contains a pointer at that location. Multiple fixups in a bind
579   // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
580   // be tested via the Count and Skip parameters.
581   //
582   // This is used by MachOBindEntry::moveNext() to validate a MachOBindEntry.
583   const char *BindEntryCheckSegAndOffsets(int32_t SegIndex, uint64_t SegOffset,
584                                           uint8_t PointerSize,
585                                           uint64_t Count = 1,
586                                           uint64_t Skip = 0) const {
587     return BindRebaseSectionTable->checkSegAndOffsets(SegIndex, SegOffset,
588                                                      PointerSize, Count, Skip);
589   }
590 
591   // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
592   // that fully contains a pointer at that location. Multiple fixups in a rebase
593   // (such as with the REBASE_OPCODE_DO_*_TIMES* opcodes) can be tested via the
594   // Count and Skip parameters.
595   //
596   // This is used by MachORebaseEntry::moveNext() to validate a MachORebaseEntry
597   const char *RebaseEntryCheckSegAndOffsets(int32_t SegIndex,
598                                             uint64_t SegOffset,
599                                             uint8_t PointerSize,
600                                             uint64_t Count = 1,
601                                             uint64_t Skip = 0) const {
602     return BindRebaseSectionTable->checkSegAndOffsets(SegIndex, SegOffset,
603                                                       PointerSize, Count, Skip);
604   }
605 
606   /// For use with the SegIndex of a checked Mach-O Bind or Rebase entry to
607   /// get the segment name.
BindRebaseSegmentName(int32_t SegIndex)608   StringRef BindRebaseSegmentName(int32_t SegIndex) const {
609     return BindRebaseSectionTable->segmentName(SegIndex);
610   }
611 
612   /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
613   /// Rebase entry to get the section name.
BindRebaseSectionName(uint32_t SegIndex,uint64_t SegOffset)614   StringRef BindRebaseSectionName(uint32_t SegIndex, uint64_t SegOffset) const {
615     return BindRebaseSectionTable->sectionName(SegIndex, SegOffset);
616   }
617 
618   /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
619   /// Rebase entry to get the address.
BindRebaseAddress(uint32_t SegIndex,uint64_t SegOffset)620   uint64_t BindRebaseAddress(uint32_t SegIndex, uint64_t SegOffset) const {
621     return BindRebaseSectionTable->address(SegIndex, SegOffset);
622   }
623 
624   // In a MachO file, sections have a segment name. This is used in the .o
625   // files. They have a single segment, but this field specifies which segment
626   // a section should be put in the final object.
627   StringRef getSectionFinalSegmentName(DataRefImpl Sec) const;
628 
629   // Names are stored as 16 bytes. These returns the raw 16 bytes without
630   // interpreting them as a C string.
631   ArrayRef<char> getSectionRawName(DataRefImpl Sec) const;
632   ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const;
633 
634   // MachO specific Info about relocations.
635   bool isRelocationScattered(const MachO::any_relocation_info &RE) const;
636   unsigned getPlainRelocationSymbolNum(
637                                     const MachO::any_relocation_info &RE) const;
638   bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const;
639   bool getScatteredRelocationScattered(
640                                     const MachO::any_relocation_info &RE) const;
641   uint32_t getScatteredRelocationValue(
642                                     const MachO::any_relocation_info &RE) const;
643   uint32_t getScatteredRelocationType(
644                                     const MachO::any_relocation_info &RE) const;
645   unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const;
646   unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const;
647   unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const;
648   unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const;
649   SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const;
650 
651   // MachO specific structures.
652   MachO::section getSection(DataRefImpl DRI) const;
653   MachO::section_64 getSection64(DataRefImpl DRI) const;
654   MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const;
655   MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const;
656   MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const;
657   MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const;
658 
659   MachO::linkedit_data_command
660   getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
661   MachO::segment_command
662   getSegmentLoadCommand(const LoadCommandInfo &L) const;
663   MachO::segment_command_64
664   getSegment64LoadCommand(const LoadCommandInfo &L) const;
665   MachO::linker_option_command
666   getLinkerOptionLoadCommand(const LoadCommandInfo &L) const;
667   MachO::version_min_command
668   getVersionMinLoadCommand(const LoadCommandInfo &L) const;
669   MachO::note_command
670   getNoteLoadCommand(const LoadCommandInfo &L) const;
671   MachO::build_version_command
672   getBuildVersionLoadCommand(const LoadCommandInfo &L) const;
673   MachO::build_tool_version
674   getBuildToolVersion(unsigned index) const;
675   MachO::dylib_command
676   getDylibIDLoadCommand(const LoadCommandInfo &L) const;
677   MachO::dyld_info_command
678   getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
679   MachO::dylinker_command
680   getDylinkerCommand(const LoadCommandInfo &L) const;
681   MachO::uuid_command
682   getUuidCommand(const LoadCommandInfo &L) const;
683   MachO::rpath_command
684   getRpathCommand(const LoadCommandInfo &L) const;
685   MachO::source_version_command
686   getSourceVersionCommand(const LoadCommandInfo &L) const;
687   MachO::entry_point_command
688   getEntryPointCommand(const LoadCommandInfo &L) const;
689   MachO::encryption_info_command
690   getEncryptionInfoCommand(const LoadCommandInfo &L) const;
691   MachO::encryption_info_command_64
692   getEncryptionInfoCommand64(const LoadCommandInfo &L) const;
693   MachO::sub_framework_command
694   getSubFrameworkCommand(const LoadCommandInfo &L) const;
695   MachO::sub_umbrella_command
696   getSubUmbrellaCommand(const LoadCommandInfo &L) const;
697   MachO::sub_library_command
698   getSubLibraryCommand(const LoadCommandInfo &L) const;
699   MachO::sub_client_command
700   getSubClientCommand(const LoadCommandInfo &L) const;
701   MachO::routines_command
702   getRoutinesCommand(const LoadCommandInfo &L) const;
703   MachO::routines_command_64
704   getRoutinesCommand64(const LoadCommandInfo &L) const;
705   MachO::thread_command
706   getThreadCommand(const LoadCommandInfo &L) const;
707   MachO::fileset_entry_command
708   getFilesetEntryLoadCommand(const LoadCommandInfo &L) const;
709 
710   MachO::any_relocation_info getRelocation(DataRefImpl Rel) const;
711   MachO::data_in_code_entry getDice(DataRefImpl Rel) const;
712   const MachO::mach_header &getHeader() const;
713   const MachO::mach_header_64 &getHeader64() const;
714   uint32_t
715   getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC,
716                               unsigned Index) const;
717   MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset,
718                                                     unsigned Index) const;
719   MachO::symtab_command getSymtabLoadCommand() const;
720   MachO::dysymtab_command getDysymtabLoadCommand() const;
721   MachO::linkedit_data_command getDataInCodeLoadCommand() const;
722   MachO::linkedit_data_command getLinkOptHintsLoadCommand() const;
723   ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const;
724   ArrayRef<uint8_t> getDyldInfoBindOpcodes() const;
725   ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const;
726   ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const;
727   ArrayRef<uint8_t> getDyldInfoExportsTrie() const;
728 
729   /// If the optional is std::nullopt, no header was found, but the object was
730   /// well-formed.
731   Expected<std::optional<MachO::dyld_chained_fixups_header>>
732   getChainedFixupsHeader() const;
733   Expected<std::vector<ChainedFixupTarget>> getDyldChainedFixupTargets() const;
734 
735   // Note: This is a limited, temporary API, which will be removed when Apple
736   // upstreams their implementation. Please do not rely on this.
737   Expected<std::optional<MachO::linkedit_data_command>>
738   getChainedFixupsLoadCommand() const;
739   // Returns the number of sections listed in dyld_chained_starts_in_image, and
740   // a ChainedFixupsSegment for each segment that has fixups.
741   Expected<std::pair<size_t, std::vector<ChainedFixupsSegment>>>
742   getChainedFixupsSegments() const;
743   ArrayRef<uint8_t> getDyldExportsTrie() const;
744 
745   SmallVector<uint64_t> getFunctionStarts() const;
746   ArrayRef<uint8_t> getUuid() const;
747 
748   StringRef getStringTableData() const;
749 
750   void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
751 
752   static StringRef guessLibraryShortName(StringRef Name, bool &isFramework,
753                                          StringRef &Suffix);
754 
755   static Triple::ArchType getArch(uint32_t CPUType, uint32_t CPUSubType);
756   static Triple getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
757                               const char **McpuDefault = nullptr,
758                               const char **ArchFlag = nullptr);
759   static bool isValidArch(StringRef ArchFlag);
760   static ArrayRef<StringRef> getValidArchs();
761   static Triple getHostArch();
762 
763   bool isRelocatableObject() const override;
764 
765   StringRef mapDebugSectionName(StringRef Name) const override;
766 
767   llvm::binaryformat::Swift5ReflectionSectionKind
768   mapReflectionSectionNameToEnumValue(StringRef SectionName) const override;
769 
hasPageZeroSegment()770   bool hasPageZeroSegment() const { return HasPageZeroSegment; }
771 
getMachOFilesetEntryOffset()772   size_t getMachOFilesetEntryOffset() const { return MachOFilesetEntryOffset; }
773 
classof(const Binary * v)774   static bool classof(const Binary *v) {
775     return v->isMachO();
776   }
777 
778   static uint32_t
getVersionMinMajor(MachO::version_min_command & C,bool SDK)779   getVersionMinMajor(MachO::version_min_command &C, bool SDK) {
780     uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
781     return (VersionOrSDK >> 16) & 0xffff;
782   }
783 
784   static uint32_t
getVersionMinMinor(MachO::version_min_command & C,bool SDK)785   getVersionMinMinor(MachO::version_min_command &C, bool SDK) {
786     uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
787     return (VersionOrSDK >> 8) & 0xff;
788   }
789 
790   static uint32_t
getVersionMinUpdate(MachO::version_min_command & C,bool SDK)791   getVersionMinUpdate(MachO::version_min_command &C, bool SDK) {
792     uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
793     return VersionOrSDK & 0xff;
794   }
795 
getBuildPlatform(uint32_t platform)796   static std::string getBuildPlatform(uint32_t platform) {
797     switch (platform) {
798 #define PLATFORM(platform, id, name, build_name, target, tapi_target,          \
799                  marketing)                                                    \
800   case MachO::PLATFORM_##platform:                                             \
801     return #name;
802 #include "llvm/BinaryFormat/MachO.def"
803     default:
804       std::string ret;
805       raw_string_ostream ss(ret);
806       ss << format_hex(platform, 8, true);
807       return ret;
808     }
809   }
810 
getBuildTool(uint32_t tools)811   static std::string getBuildTool(uint32_t tools) {
812     switch (tools) {
813     case MachO::TOOL_CLANG: return "clang";
814     case MachO::TOOL_SWIFT: return "swift";
815     case MachO::TOOL_LD: return "ld";
816     case MachO::TOOL_LLD:
817       return "lld";
818     default:
819       std::string ret;
820       raw_string_ostream ss(ret);
821       ss << format_hex(tools, 8, true);
822       return ret;
823     }
824   }
825 
getVersionString(uint32_t version)826   static std::string getVersionString(uint32_t version) {
827     uint32_t major = (version >> 16) & 0xffff;
828     uint32_t minor = (version >> 8) & 0xff;
829     uint32_t update = version & 0xff;
830 
831     SmallString<32> Version;
832     Version = utostr(major) + "." + utostr(minor);
833     if (update != 0)
834       Version += "." + utostr(update);
835     return std::string(std::string(Version));
836   }
837 
838   /// If the input path is a .dSYM bundle (as created by the dsymutil tool),
839   /// return the paths to the object files found in the bundle, otherwise return
840   /// an empty vector. If the path appears to be a .dSYM bundle but no objects
841   /// were found or there was a filesystem error, then return an error.
842   static Expected<std::vector<std::string>>
843   findDsymObjectMembers(StringRef Path);
844 
845 private:
846   MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
847                   Error &Err, uint32_t UniversalCputype = 0,
848                   uint32_t UniversalIndex = 0,
849                   size_t MachOFilesetEntryOffset = 0);
850 
851   uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
852 
853   union {
854     MachO::mach_header_64 Header64;
855     MachO::mach_header Header;
856   };
857   using SectionList = SmallVector<const char*, 1>;
858   SectionList Sections;
859   using LibraryList = SmallVector<const char*, 1>;
860   LibraryList Libraries;
861   LoadCommandList LoadCommands;
862   using LibraryShortName = SmallVector<StringRef, 1>;
863   using BuildToolList = SmallVector<const char*, 1>;
864   BuildToolList BuildTools;
865   mutable LibraryShortName LibrariesShortNames;
866   std::unique_ptr<BindRebaseSegInfo> BindRebaseSectionTable;
867   const char *SymtabLoadCmd = nullptr;
868   const char *DysymtabLoadCmd = nullptr;
869   const char *DataInCodeLoadCmd = nullptr;
870   const char *LinkOptHintsLoadCmd = nullptr;
871   const char *DyldInfoLoadCmd = nullptr;
872   const char *FuncStartsLoadCmd = nullptr;
873   const char *DyldChainedFixupsLoadCmd = nullptr;
874   const char *DyldExportsTrieLoadCmd = nullptr;
875   const char *UuidLoadCmd = nullptr;
876   bool HasPageZeroSegment = false;
877   size_t MachOFilesetEntryOffset = 0;
878 };
879 
880 /// DiceRef
DiceRef(DataRefImpl DiceP,const ObjectFile * Owner)881 inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner)
882   : DicePimpl(DiceP) , OwningObject(Owner) {}
883 
884 inline bool DiceRef::operator==(const DiceRef &Other) const {
885   return DicePimpl == Other.DicePimpl;
886 }
887 
888 inline bool DiceRef::operator<(const DiceRef &Other) const {
889   return DicePimpl < Other.DicePimpl;
890 }
891 
moveNext()892 inline void DiceRef::moveNext() {
893   const MachO::data_in_code_entry *P =
894     reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p);
895   DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1);
896 }
897 
898 // Since a Mach-O data in code reference, a DiceRef, can only be created when
899 // the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for
900 // the methods that get the values of the fields of the reference.
901 
getOffset(uint32_t & Result)902 inline std::error_code DiceRef::getOffset(uint32_t &Result) const {
903   const MachOObjectFile *MachOOF =
904     static_cast<const MachOObjectFile *>(OwningObject);
905   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
906   Result = Dice.offset;
907   return std::error_code();
908 }
909 
getLength(uint16_t & Result)910 inline std::error_code DiceRef::getLength(uint16_t &Result) const {
911   const MachOObjectFile *MachOOF =
912     static_cast<const MachOObjectFile *>(OwningObject);
913   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
914   Result = Dice.length;
915   return std::error_code();
916 }
917 
getKind(uint16_t & Result)918 inline std::error_code DiceRef::getKind(uint16_t &Result) const {
919   const MachOObjectFile *MachOOF =
920     static_cast<const MachOObjectFile *>(OwningObject);
921   MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
922   Result = Dice.kind;
923   return std::error_code();
924 }
925 
getRawDataRefImpl()926 inline DataRefImpl DiceRef::getRawDataRefImpl() const {
927   return DicePimpl;
928 }
929 
getObjectFile()930 inline const ObjectFile *DiceRef::getObjectFile() const {
931   return OwningObject;
932 }
933 
934 } // end namespace object
935 } // end namespace llvm
936 
937 #endif // LLVM_OBJECT_MACHO_H
938