LLVM 24.0.0git
MachO.h
Go to the documentation of this file.
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"
21#include "llvm/ADT/StringRef.h"
25#include "llvm/Object/Binary.h"
29#include "llvm/Support/Error.h"
30#include "llvm/Support/Format.h"
35#include <cstdint>
36#include <memory>
37#include <string>
38#include <system_error>
39
40namespace llvm {
41namespace 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.
45class DiceRef {
46 DataRefImpl DicePimpl;
47 const ObjectFile *OwningObject = nullptr;
48
49public:
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
63 const ObjectFile *getObjectFile() const;
64};
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 ...
75public:
78
79 LLVM_ABI StringRef name() const;
80 LLVM_ABI uint64_t flags() const;
82 LLVM_ABI uint64_t other() const;
85
86 LLVM_ABI bool operator==(const ExportEntry &) const;
87
88 LLVM_ABI void moveNext();
89
90private:
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 };
115 using node_iterator = NodeList::const_iterator;
116
117 Error *E;
118 const MachOObjectFile *O;
120 SmallString<256> CumulativeString;
121 NodeList Stack;
122 bool Done = false;
123
124 iterator_range<node_iterator> nodes() const { return Stack; }
125};
127
128// Segment info so SegIndex/SegOffset pairs in a Mach-O Bind or Rebase entry
129// can be checked and translated. Only the SegIndex/SegOffset pairs from
130// checked entries are to be used with the segmentName(), sectionName() and
131// address() methods below.
133public:
135
136 // Used to check a Mach-O Bind or Rebase entry for errors when iterating.
137 LLVM_ABI const char *checkSegAndOffsets(int32_t SegIndex, uint64_t SegOffset,
138 uint8_t PointerSize,
139 uint64_t Count = 1,
140 uint64_t Skip = 0);
141 // Used with valid SegIndex/SegOffset values from checked entries.
142 LLVM_ABI StringRef segmentName(int32_t SegIndex);
143 LLVM_ABI StringRef sectionName(int32_t SegIndex, uint64_t SegOffset);
144 LLVM_ABI uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
145
146private:
147 struct SectionInfo {
151 StringRef SegmentName;
152 uint64_t OffsetInSegment;
153 uint64_t SegmentStartAddress;
154 int32_t SegmentIndex;
155 };
156 const SectionInfo &findSection(int32_t SegIndex, uint64_t SegOffset);
157
159 int32_t MaxSegIndex;
160};
161
162/// MachORebaseEntry encapsulates the current state in the decompression of
163/// rebasing opcodes. This allows you to iterate through the compressed table of
164/// rebasing using:
165/// Error Err = Error::success();
166/// for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(&Err)) {
167/// }
168/// if (Err) { report error ...
170public:
172 ArrayRef<uint8_t> opcodes, bool is64Bit);
173
174 LLVM_ABI int32_t segmentIndex() const;
179 LLVM_ABI uint64_t address() const;
180
181 LLVM_ABI bool operator==(const MachORebaseEntry &) const;
182
183 LLVM_ABI void moveNext();
184
185private:
186 friend class MachOObjectFile;
187
188 void moveToFirst();
189 void moveToEnd();
190 uint64_t readULEB128(const char **error);
191
192 Error *E;
193 const MachOObjectFile *O;
194 ArrayRef<uint8_t> Opcodes;
195 const uint8_t *Ptr;
196 uint64_t SegmentOffset = 0;
197 int32_t SegmentIndex = -1;
198 uint64_t RemainingLoopCount = 0;
199 uint64_t AdvanceAmount = 0;
200 uint8_t RebaseType = 0;
201 uint8_t PointerSize;
202 bool Done = false;
203};
205
206/// MachOBindEntry encapsulates the current state in the decompression of
207/// binding opcodes. This allows you to iterate through the compressed table of
208/// bindings using:
209/// Error Err = Error::success();
210/// for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(&Err)) {
211/// }
212/// if (Err) { report error ...
214public:
215 enum class Kind { Regular, Lazy, Weak };
216
218 ArrayRef<uint8_t> Opcodes, bool is64Bit,
220
221 LLVM_ABI int32_t segmentIndex() const;
225 LLVM_ABI uint32_t flags() const;
226 LLVM_ABI int64_t addend() const;
227 LLVM_ABI int ordinal() const;
228
231 LLVM_ABI uint64_t address() const;
232
233 LLVM_ABI bool operator==(const MachOBindEntry &) const;
234
235 LLVM_ABI void moveNext();
236
237private:
238 friend class MachOObjectFile;
239
240 void moveToFirst();
241 void moveToEnd();
242 uint64_t readULEB128(const char **error);
243 int64_t readSLEB128(const char **error);
244
245 Error *E;
246 const MachOObjectFile *O;
247 ArrayRef<uint8_t> Opcodes;
248 const uint8_t *Ptr;
249 uint64_t SegmentOffset = 0;
250 int32_t SegmentIndex = -1;
251 StringRef SymbolName;
252 bool LibraryOrdinalSet = false;
253 int Ordinal = 0;
254 uint32_t Flags = 0;
255 int64_t Addend = 0;
256 uint64_t RemainingLoopCount = 0;
257 uint64_t AdvanceAmount = 0;
258 uint8_t BindType = 0;
259 uint8_t PointerSize;
260 Kind TableKind;
261 bool Done = false;
262};
264
265/// ChainedFixupTarget holds all the information about an external symbol
266/// necessary to bind this binary to that symbol. These values are referenced
267/// indirectly by chained fixup binds. This structure captures values from all
268/// import and symbol formats.
269///
270/// Be aware there are two notions of weak here:
271/// WeakImport == true
272/// The associated bind may be set to 0 if this symbol is missing from its
273/// parent library. This is called a "weak import."
274/// LibOrdinal == BIND_SPECIAL_DYLIB_WEAK_LOOKUP
275/// This symbol may be coalesced with other libraries vending the same
276/// symbol. E.g., C++'s "operator new". This is called a "weak bind."
278public:
279 ChainedFixupTarget(int LibOrdinal, uint32_t NameOffset, StringRef Symbol,
280 uint64_t Addend, bool WeakImport)
281 : LibOrdinal(LibOrdinal), NameOffset(NameOffset), SymbolName(Symbol),
282 Addend(Addend), WeakImport(WeakImport) {}
283
284 int libOrdinal() { return LibOrdinal; }
285 uint32_t nameOffset() { return NameOffset; }
286 StringRef symbolName() { return SymbolName; }
287 uint64_t addend() { return Addend; }
288 bool weakImport() { return WeakImport; }
289 bool weakBind() {
290 return LibOrdinal == MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP;
291 }
292
293private:
294 int LibOrdinal;
295 uint32_t NameOffset;
296 StringRef SymbolName;
297 uint64_t Addend;
298 bool WeakImport;
299};
300
307
309 uint32_t Offset; // dyld_chained_starts_in_image::seg_info_offset[SegIdx]
311 std::vector<uint16_t> PageStarts; // page_start[] entries, host endianness
312};
313
314/// MachOAbstractFixupEntry is an abstract class representing a fixup in a
315/// MH_DYLDLINK file. Fixups generally represent rebases and binds. Binds also
316/// subdivide into additional subtypes (weak, lazy, reexport).
317///
318/// The two concrete subclasses of MachOAbstractFixupEntry are:
319///
320/// MachORebaseBindEntry - for dyld opcode-based tables, including threaded-
321/// rebase, where rebases are mixed in with other
322/// bind opcodes.
323/// MachOChainedFixupEntry - for pointer chains embedded in data pages.
325public:
327
328 LLVM_ABI int32_t segmentIndex() const;
335 LLVM_ABI uint32_t flags() const;
336 LLVM_ABI int64_t addend() const;
337 LLVM_ABI int ordinal() const;
338
339 /// \return the location of this fixup as a VM Address. For the VM
340 /// Address this fixup is pointing to, use pointerValue().
341 LLVM_ABI uint64_t address() const;
342
343 /// \return the VM Address pointed to by this fixup. Use
344 /// pointerValue() to compare against other VM Addresses, such as
345 /// section addresses or segment vmaddrs.
347
348 /// \return the raw "on-disk" representation of the fixup. For
349 /// Threaded rebases and Chained pointers these values are generally
350 /// encoded into various different pointer formats. This value is
351 /// exposed in API for tools that want to display and annotate the
352 /// raw bits.
353 uint64_t rawValue() const { return RawValue; }
354
355 LLVM_ABI void moveNext();
356
357protected:
361 int32_t SegmentIndex = -1;
363 int32_t Ordinal = 0;
365 int64_t Addend = 0;
368 bool Done = false;
369
370 LLVM_ABI void moveToFirst();
371 LLVM_ABI void moveToEnd();
372
373 /// \return the vm address of the start of __TEXT segment.
374 uint64_t textAddress() const { return TextAddress; }
375
376private:
377 uint64_t TextAddress;
378};
379
381public:
382 enum class FixupKind { Bind, Rebase };
383
385 bool Parse);
386
387 LLVM_ABI bool operator==(const MachOChainedFixupEntry &) const;
388
389 bool isBind() const { return Kind == FixupKind::Bind; }
390 bool isRebase() const { return Kind == FixupKind::Rebase; }
391
392 /// \return the DYLD_CHAINED_PTR_* format of the segment of this fixup.
393 uint16_t pointerFormat() const { return PointerFormat; }
394
395 /// \return whether this is an arm64e authenticated rebase or bind, which
396 /// dyld signs with key(), diversity() and, if hasAddressDiversity(), the
397 /// address of the fixup.
398 bool isAuthenticated() const { return IsAuthenticated; }
399 /// \return the ptrauth key: 0 = IA, 1 = IB, 2 = DA, 3 = DB.
400 uint8_t key() const { return Key; }
401 uint16_t diversity() const { return Diversity; }
402 bool hasAddressDiversity() const { return HasAddressDiversity; }
403
404 LLVM_ABI void moveNext();
405 LLVM_ABI void moveToFirst();
406 LLVM_ABI void moveToEnd();
407
408private:
409 void findNextPageWithFixups();
410
411 std::vector<ChainedFixupTarget> FixupTargets;
412 std::vector<ChainedFixupsSegment> Segments;
413 ArrayRef<uint8_t> SegmentData;
415 uint16_t PointerFormat = 0;
416 uint16_t Diversity = 0;
417 uint8_t Key = 0;
418 bool IsAuthenticated = false;
419 bool HasAddressDiversity = false;
420 uint32_t InfoSegIndex = 0; // Index into Segments
421 uint32_t PageIndex = 0; // Index into Segments[InfoSegIdx].PageStarts
422 uint32_t PageOffset = 0; // Page offset of the current fixup
423};
425
426class LLVM_ABI MachOObjectFile : public ObjectFile {
427public:
429 const char *Ptr; // Where in memory the load command is.
430 MachO::load_command C; // The command itself.
431 };
434
436 create(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
437 uint32_t UniversalCputype = 0, uint32_t UniversalIndex = 0,
438 size_t MachOFilesetEntryOffset = 0);
439
440 static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch);
441
442 void moveSymbolNext(DataRefImpl &Symb) const override;
443
444 uint64_t getNValue(DataRefImpl Sym) const;
445 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
446
447 // MachO specific.
448 Error checkSymbolTable() const;
449
450 std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const;
451 unsigned getSectionType(SectionRef Sec) const;
452
454 uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
455 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
457 Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
459 unsigned getSymbolSectionID(SymbolRef Symb) const;
460 unsigned getSectionID(SectionRef Sec) const;
461
462 void moveSectionNext(DataRefImpl &Sec) const override;
464 uint64_t getSectionAddress(DataRefImpl Sec) const override;
465 uint64_t getSectionIndex(DataRefImpl Sec) const override;
466 uint64_t getSectionSize(DataRefImpl Sec) const override;
469 getSectionContents(DataRefImpl Sec) const override;
470 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
471 Expected<SectionRef> getSection(unsigned SectionIndex) const;
473 bool isSectionCompressed(DataRefImpl Sec) const override;
474 bool isSectionText(DataRefImpl Sec) const override;
475 bool isSectionData(DataRefImpl Sec) const override;
476 bool isSectionBSS(DataRefImpl Sec) const override;
477 bool isSectionVirtual(DataRefImpl Sec) const override;
478 bool isSectionBitcode(DataRefImpl Sec) const override;
479 bool isDebugSection(DataRefImpl Sec) const override;
480
481 /// Return the raw contents of an entire segment.
483 ArrayRef<uint8_t> getSegmentContents(size_t SegmentIndex) const;
484
485 /// When dsymutil generates the companion file, it strips all unnecessary
486 /// sections (e.g. everything in the _TEXT segment) by omitting their body
487 /// and setting the offset in their corresponding load command to zero.
488 ///
489 /// While the load command itself is valid, reading the section corresponds
490 /// to reading the number of bytes specified in the load command, starting
491 /// from offset 0 (i.e. the Mach-O header at the beginning of the file).
492 bool isSectionStripped(DataRefImpl Sec) const override;
493
496
502
503 relocation_iterator locrel_begin() const;
504 relocation_iterator locrel_end() const;
505
506 void moveRelocationNext(DataRefImpl &Rel) const override;
507 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
508 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
509 section_iterator getRelocationSection(DataRefImpl Rel) const;
510 uint64_t getRelocationType(DataRefImpl Rel) const override;
511 void getRelocationTypeName(DataRefImpl Rel,
512 SmallVectorImpl<char> &Result) const override;
513 uint8_t getRelocationLength(DataRefImpl Rel) const;
514
515 // MachO specific.
516 std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const;
517 uint32_t getLibraryCount() const;
518
519 section_iterator getRelocationRelocatedSection(relocation_iterator Rel) const;
520
521 // TODO: Would be useful to have an iterator based version
522 // of the load command interface too.
523
524 basic_symbol_iterator symbol_begin() const override;
525 basic_symbol_iterator symbol_end() const override;
526
527 bool is64Bit() const override;
528
529 // MachO specific.
530 symbol_iterator getSymbolByIndex(unsigned Index) const;
531 uint64_t getSymbolIndex(DataRefImpl Symb) const;
532
533 section_iterator section_begin() const override;
534 section_iterator section_end() const override;
535
536 uint8_t getBytesInAddress() const override;
537
538 StringRef getFileFormatName() const override;
539 Triple::ArchType getArch() const override;
541 return SubtargetFeatures();
542 }
543 Triple getArchTriple(const char **McpuDefault = nullptr) const;
544
545 relocation_iterator section_rel_begin(unsigned Index) const;
546 relocation_iterator section_rel_end(unsigned Index) const;
547
548 dice_iterator begin_dices() const;
549 dice_iterator end_dices() const;
550
551 load_command_iterator begin_load_commands() const;
552 load_command_iterator end_load_commands() const;
553 iterator_range<load_command_iterator> load_commands() const;
554
555 /// For use iterating over all exported symbols.
556 iterator_range<export_iterator> exports(Error &Err) const;
557
558 /// For use examining a trie not in a MachOObjectFile.
559 static iterator_range<export_iterator> exports(Error &Err,
561 const MachOObjectFile *O =
562 nullptr);
563
564 /// For use iterating over all rebase table entries.
565 iterator_range<rebase_iterator> rebaseTable(Error &Err);
566
567 /// For use examining rebase opcodes in a MachOObjectFile.
568 static iterator_range<rebase_iterator> rebaseTable(Error &Err,
570 ArrayRef<uint8_t> Opcodes,
571 bool is64);
572
573 /// For use iterating over all bind table entries.
574 iterator_range<bind_iterator> bindTable(Error &Err);
575
576 /// For iterating over all chained fixups.
577 iterator_range<fixup_iterator> fixupTable(Error &Err);
578
579 /// For use iterating over all lazy bind table entries.
580 iterator_range<bind_iterator> lazyBindTable(Error &Err);
581
582 /// For use iterating over all weak bind table entries.
583 iterator_range<bind_iterator> weakBindTable(Error &Err);
584
585 /// For use examining bind opcodes in a MachOObjectFile.
586 static iterator_range<bind_iterator> bindTable(Error &Err,
588 ArrayRef<uint8_t> Opcodes,
589 bool is64,
591
592 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
593 // that fully contains a pointer at that location. Multiple fixups in a bind
594 // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
595 // be tested via the Count and Skip parameters.
596 //
597 // This is used by MachOBindEntry::moveNext() to validate a MachOBindEntry.
598 const char *BindEntryCheckSegAndOffsets(int32_t SegIndex, 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 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
607 // that fully contains a pointer at that location. Multiple fixups in a rebase
608 // (such as with the REBASE_OPCODE_DO_*_TIMES* opcodes) can be tested via the
609 // Count and Skip parameters.
610 //
611 // This is used by MachORebaseEntry::moveNext() to validate a MachORebaseEntry
612 const char *RebaseEntryCheckSegAndOffsets(int32_t SegIndex,
613 uint64_t SegOffset,
614 uint8_t PointerSize,
615 uint64_t Count = 1,
616 uint64_t Skip = 0) const {
617 return BindRebaseSectionTable->checkSegAndOffsets(SegIndex, SegOffset,
618 PointerSize, Count, Skip);
619 }
620
621 /// For use with the SegIndex of a checked Mach-O Bind or Rebase entry to
622 /// get the segment name.
623 StringRef BindRebaseSegmentName(int32_t SegIndex) const {
624 return BindRebaseSectionTable->segmentName(SegIndex);
625 }
626
627 /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
628 /// Rebase entry to get the section name.
630 return BindRebaseSectionTable->sectionName(SegIndex, SegOffset);
631 }
632
633 /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or
634 /// Rebase entry to get the address.
635 uint64_t BindRebaseAddress(uint32_t SegIndex, uint64_t SegOffset) const {
636 return BindRebaseSectionTable->address(SegIndex, SegOffset);
637 }
638
639 // In a MachO file, sections have a segment name. This is used in the .o
640 // files. They have a single segment, but this field specifies which segment
641 // a section should be put in the final object.
642 StringRef getSectionFinalSegmentName(DataRefImpl Sec) const;
643
644 // Names are stored as 16 bytes. These returns the raw 16 bytes without
645 // interpreting them as a C string.
646 ArrayRef<char> getSectionRawName(DataRefImpl Sec) const;
647 ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const;
648
649 // MachO specific Info about relocations.
650 bool isRelocationScattered(const MachO::any_relocation_info &RE) const;
651 unsigned getPlainRelocationSymbolNum(
652 const MachO::any_relocation_info &RE) const;
653 bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const;
654 bool getScatteredRelocationScattered(
655 const MachO::any_relocation_info &RE) const;
656 uint32_t getScatteredRelocationValue(
657 const MachO::any_relocation_info &RE) const;
658 uint32_t getScatteredRelocationType(
659 const MachO::any_relocation_info &RE) const;
660 unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const;
661 unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const;
662 unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const;
663 unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const;
664 SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const;
665
666 // MachO specific structures.
668 MachO::section_64 getSection64(DataRefImpl DRI) const;
669 MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const;
670 MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const;
671 MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const;
672 MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const;
673
675 getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
677 getSegmentLoadCommand(const LoadCommandInfo &L) const;
679 getSegment64LoadCommand(const LoadCommandInfo &L) const;
681 getLinkerOptionLoadCommand(const LoadCommandInfo &L) const;
683 getVersionMinLoadCommand(const LoadCommandInfo &L) const;
685 getNoteLoadCommand(const LoadCommandInfo &L) const;
687 getBuildVersionLoadCommand(const LoadCommandInfo &L) const;
689 getTargetTripleLoadCommand(const LoadCommandInfo &L) const;
691 getBuildToolVersion(unsigned index) const;
693 getDylibIDLoadCommand(const LoadCommandInfo &L) const;
695 getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
697 getDylinkerCommand(const LoadCommandInfo &L) const;
699 getUuidCommand(const LoadCommandInfo &L) const;
701 getRpathCommand(const LoadCommandInfo &L) const;
703 getSourceVersionCommand(const LoadCommandInfo &L) const;
705 getEntryPointCommand(const LoadCommandInfo &L) const;
707 getEncryptionInfoCommand(const LoadCommandInfo &L) const;
709 getEncryptionInfoCommand64(const LoadCommandInfo &L) const;
711 getSubFrameworkCommand(const LoadCommandInfo &L) const;
713 getSubUmbrellaCommand(const LoadCommandInfo &L) const;
715 getSubLibraryCommand(const LoadCommandInfo &L) const;
717 getSubClientCommand(const LoadCommandInfo &L) const;
719 getRoutinesCommand(const LoadCommandInfo &L) const;
721 getRoutinesCommand64(const LoadCommandInfo &L) const;
723 getThreadCommand(const LoadCommandInfo &L) const;
725 getFilesetEntryLoadCommand(const LoadCommandInfo &L) const;
726
727 MachO::any_relocation_info getRelocation(DataRefImpl Rel) const;
728 MachO::data_in_code_entry getDice(DataRefImpl Rel) const;
729 const MachO::mach_header &getHeader() const;
730 const MachO::mach_header_64 &getHeader64() const;
732 getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC,
733 unsigned Index) const;
734 MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset,
735 unsigned Index) const;
736 MachO::symtab_command getSymtabLoadCommand() const;
737 MachO::dysymtab_command getDysymtabLoadCommand() const;
738 MachO::linkedit_data_command getDataInCodeLoadCommand() const;
739 MachO::linkedit_data_command getLinkOptHintsLoadCommand() const;
740 ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const;
741 ArrayRef<uint8_t> getDyldInfoBindOpcodes() const;
742 ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const;
743 ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const;
744 ArrayRef<uint8_t> getDyldInfoExportsTrie() const;
745
746 /// If the optional is std::nullopt, no header was found, but the object was
747 /// well-formed.
749 getChainedFixupsHeader() const;
750 Expected<std::vector<ChainedFixupTarget>> getDyldChainedFixupTargets() const;
751
752 // Note: This is a limited, temporary API, which will be removed when Apple
753 // upstreams their implementation. Please do not rely on this.
755 getChainedFixupsLoadCommand() const;
756 // Returns the number of sections listed in dyld_chained_starts_in_image, and
757 // a ChainedFixupsSegment for each segment that has fixups.
759 getChainedFixupsSegments() const;
760 ArrayRef<uint8_t> getDyldExportsTrie() const;
761
762 SmallVector<uint64_t> getFunctionStarts() const;
763 ArrayRef<uint8_t> getUuid() const;
764
765 StringRef getStringTableData() const;
766
767 void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
768
769 static StringRef guessLibraryShortName(StringRef Name, bool &isFramework,
770 StringRef &Suffix);
771
772 static Triple::ArchType getArch(uint32_t CPUType, uint32_t CPUSubType);
773 static Triple getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
774 const char **McpuDefault = nullptr,
775 const char **ArchFlag = nullptr);
776 static bool isValidArch(StringRef ArchFlag);
777 static ArrayRef<StringRef> getValidArchs();
778 static Triple getHostArch();
779
780 bool isRelocatableObject() const override;
781
782 StringRef mapDebugSectionName(StringRef Name) const override;
783
785 mapReflectionSectionNameToEnumValue(StringRef SectionName) const override;
786
787 bool hasPageZeroSegment() const { return HasPageZeroSegment; }
788
789 size_t getMachOFilesetEntryOffset() const { return MachOFilesetEntryOffset; }
790
791 static bool classof(const Binary *v) {
792 return v->isMachO();
793 }
794
795 static uint32_t
797 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
798 return (VersionOrSDK >> 16) & 0xffff;
799 }
800
801 static uint32_t
803 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
804 return (VersionOrSDK >> 8) & 0xff;
805 }
806
807 static uint32_t
809 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
810 return VersionOrSDK & 0xff;
811 }
812
813 static std::string getBuildPlatform(uint32_t platform) {
814 switch (platform) {
815#define PLATFORM(platform, id, name, build_name, target, tapi_target, \
816 marketing) \
817 case MachO::PLATFORM_##platform: \
818 return #name;
819#include "llvm/BinaryFormat/MachO.def"
820 default:
821 std::string ret;
822 raw_string_ostream ss(ret);
823 ss << format_hex(platform, 8, true);
824 return ret;
825 }
826 }
827
828 static std::string getBuildTool(uint32_t tools) {
829 switch (tools) {
830 case MachO::TOOL_CLANG: return "clang";
831 case MachO::TOOL_SWIFT: return "swift";
832 case MachO::TOOL_LD: return "ld";
833 case MachO::TOOL_LLD:
834 return "lld";
836 return "dsymutil";
837 default:
838 std::string ret;
839 raw_string_ostream ss(ret);
840 ss << format_hex(tools, 8, true);
841 return ret;
842 }
843 }
844
845 static std::string getVersionString(uint32_t version) {
846 uint32_t major = (version >> 16) & 0xffff;
847 uint32_t minor = (version >> 8) & 0xff;
848 uint32_t update = version & 0xff;
849
851 Version = utostr(major) + "." + utostr(minor);
852 if (update != 0)
853 Version += "." + utostr(update);
854 return std::string(std::string(Version));
855 }
856
857 /// If the input path is a .dSYM bundle (as created by the dsymutil tool),
858 /// return the paths to the object files found in the bundle, otherwise return
859 /// an empty vector. If the path appears to be a .dSYM bundle but no objects
860 /// were found or there was a filesystem error, then return an error.
862 findDsymObjectMembers(StringRef Path);
863
864private:
865 MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
866 Error &Err, uint32_t UniversalCputype = 0,
867 uint32_t UniversalIndex = 0,
868 size_t MachOFilesetEntryOffset = 0);
869
870 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
871
872 union {
875 };
876 using SectionList = SmallVector<const char*, 1>;
877 SectionList Sections;
878 using LibraryList = SmallVector<const char*, 1>;
879 LibraryList Libraries;
880 LoadCommandList LoadCommands;
881 using LibraryShortName = SmallVector<StringRef, 1>;
882 using BuildToolList = SmallVector<const char*, 1>;
883 BuildToolList BuildTools;
884 mutable LibraryShortName LibrariesShortNames;
885 std::unique_ptr<BindRebaseSegInfo> BindRebaseSectionTable;
886 const char *SymtabLoadCmd = nullptr;
887 const char *DysymtabLoadCmd = nullptr;
888 const char *DataInCodeLoadCmd = nullptr;
889 const char *LinkOptHintsLoadCmd = nullptr;
890 const char *DyldInfoLoadCmd = nullptr;
891 const char *FuncStartsLoadCmd = nullptr;
892 const char *DyldChainedFixupsLoadCmd = nullptr;
893 const char *DyldExportsTrieLoadCmd = nullptr;
894 const char *UuidLoadCmd = nullptr;
895 bool HasPageZeroSegment = false;
896 size_t MachOFilesetEntryOffset = 0;
897};
898
899/// DiceRef
901 : DicePimpl(DiceP) , OwningObject(Owner) {}
902
903inline bool DiceRef::operator==(const DiceRef &Other) const {
904 return DicePimpl == Other.DicePimpl;
905}
906
907inline bool DiceRef::operator<(const DiceRef &Other) const {
908 return DicePimpl < Other.DicePimpl;
909}
910
911inline void DiceRef::moveNext() {
913 reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p);
914 DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1);
915}
916
917// Since a Mach-O data in code reference, a DiceRef, can only be created when
918// the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for
919// the methods that get the values of the fields of the reference.
920
921inline std::error_code DiceRef::getOffset(uint32_t &Result) const {
922 const MachOObjectFile *MachOOF =
923 static_cast<const MachOObjectFile *>(OwningObject);
924 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
925 Result = Dice.offset;
926 return std::error_code();
927}
928
929inline std::error_code DiceRef::getLength(uint16_t &Result) const {
930 const MachOObjectFile *MachOOF =
931 static_cast<const MachOObjectFile *>(OwningObject);
932 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
933 Result = Dice.length;
934 return std::error_code();
935}
936
937inline std::error_code DiceRef::getKind(uint16_t &Result) const {
938 const MachOObjectFile *MachOOF =
939 static_cast<const MachOObjectFile *>(OwningObject);
940 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
941 Result = Dice.kind;
942 return std::error_code();
943}
944
946 return DicePimpl;
947}
948
949inline const ObjectFile *DiceRef::getObjectFile() const {
950 return OwningObject;
951}
952
953} // end namespace object
954} // end namespace llvm
955
956#endif // LLVM_OBJECT_MACHO_H
uint64_t uint64_t
Unify divergent function exit nodes
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
static ManagedStatic< DebugCounterOwner > Owner
static bool isDebugSection(const SectionBase &Sec)
#define P(N)
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define error(X)
static unsigned getSymbolSectionID(const ObjectFile &O, SymbolRef Sym)
static unsigned getSectionID(const ObjectFile &O, SectionRef Sec)
static std::unique_ptr< PDBSymbol > getSymbolType(const PDBSymbol &Symbol)
Definition UDTLayout.cpp:34
static uint64_t readULEB128(WasmObjectFile::ReadContext &Ctx)
static bool is64Bit(const char *name)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Manages the enabling and disabling of subtarget specific features.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
A range adaptor for a pair of iterators.
LLVM_ABI StringRef segmentName(int32_t SegIndex)
LLVM_ABI StringRef sectionName(int32_t SegIndex, uint64_t SegOffset)
LLVM_ABI BindRebaseSegInfo(const MachOObjectFile *Obj)
LLVM_ABI const char * checkSegAndOffsets(int32_t SegIndex, uint64_t SegOffset, uint8_t PointerSize, uint64_t Count=1, uint64_t Skip=0)
LLVM_ABI uint64_t address(uint32_t SegIndex, uint64_t SegOffset)
bool operator==(const DiceRef &Other) const
Definition MachO.h:903
std::error_code getOffset(uint32_t &Result) const
Definition MachO.h:921
std::error_code getLength(uint16_t &Result) const
Definition MachO.h:929
bool operator<(const DiceRef &Other) const
Definition MachO.h:907
DataRefImpl getRawDataRefImpl() const
Definition MachO.h:945
std::error_code getKind(uint16_t &Result) const
Definition MachO.h:937
const ObjectFile * getObjectFile() const
Definition MachO.h:949
LLVM_ABI StringRef name() const
LLVM_ABI ExportEntry(Error *Err, const MachOObjectFile *O, ArrayRef< uint8_t > Trie)
LLVM_ABI bool operator==(const ExportEntry &) const
LLVM_ABI StringRef otherName() const
LLVM_ABI uint64_t address() const
LLVM_ABI uint64_t flags() const
LLVM_ABI uint32_t nodeOffset() const
friend class MachOObjectFile
Definition MachO.h:91
LLVM_ABI uint64_t other() const
LLVM_ABI MachOAbstractFixupEntry(Error *Err, const MachOObjectFile *O)
const MachOObjectFile * O
Definition MachO.h:359
MachOBindEntry encapsulates the current state in the decompression of binding opcodes.
Definition MachO.h:213
LLVM_ABI uint32_t flags() const
LLVM_ABI bool operator==(const MachOBindEntry &) const
LLVM_ABI StringRef symbolName() const
LLVM_ABI StringRef sectionName() const
LLVM_ABI MachOBindEntry(Error *Err, const MachOObjectFile *O, ArrayRef< uint8_t > Opcodes, bool is64Bit, MachOBindEntry::Kind)
LLVM_ABI StringRef segmentName() const
LLVM_ABI uint64_t segmentOffset() const
LLVM_ABI int64_t addend() const
LLVM_ABI uint64_t address() const
friend class MachOObjectFile
Definition MachO.h:238
LLVM_ABI int32_t segmentIndex() const
LLVM_ABI StringRef typeName() const
LLVM_ABI bool operator==(const MachOChainedFixupEntry &) const
LLVM_ABI MachOChainedFixupEntry(Error *Err, const MachOObjectFile *O, bool Parse)
void moveSectionNext(DataRefImpl &Sec) const override
static std::string getVersionString(uint32_t version)
Definition MachO.h:845
MachO::mach_header_64 Header64
Definition MachO.h:873
bool isSectionData(DataRefImpl Sec) const override
uint64_t getSectionAlignment(DataRefImpl Sec) const override
Expected< SectionRef > getSection(unsigned SectionIndex) const
std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const
Expected< section_iterator > getSymbolSection(DataRefImpl Symb) const override
const char * RebaseEntryCheckSegAndOffsets(int32_t SegIndex, uint64_t SegOffset, uint8_t PointerSize, uint64_t Count=1, uint64_t Skip=0) const
Definition MachO.h:612
void moveSymbolNext(DataRefImpl &Symb) const override
MachO::mach_header Header
Definition MachO.h:874
uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override
relocation_iterator section_rel_begin(DataRefImpl Sec) const override
static std::string getBuildTool(uint32_t tools)
Definition MachO.h:828
const char * BindEntryCheckSegAndOffsets(int32_t SegIndex, uint64_t SegOffset, uint8_t PointerSize, uint64_t Count=1, uint64_t Skip=0) const
Definition MachO.h:598
static std::string getBuildPlatform(uint32_t platform)
Definition MachO.h:813
relocation_iterator section_rel_end(DataRefImpl Sec) const override
static bool classof(const Binary *v)
Definition MachO.h:791
unsigned getSectionType(SectionRef Sec) const
static Expected< std::unique_ptr< MachOObjectFile > > create(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits, uint32_t UniversalCputype=0, uint32_t UniversalIndex=0, size_t MachOFilesetEntryOffset=0)
Expected< uint32_t > getSymbolFlags(DataRefImpl Symb) const override
bool isSectionBSS(DataRefImpl Sec) const override
bool isSectionVirtual(DataRefImpl Sec) const override
Expected< StringRef > getSymbolName(DataRefImpl Symb) const override
LoadCommandList::const_iterator load_command_iterator
Definition MachO.h:433
iterator_range< relocation_iterator > external_relocations() const
Definition MachO.h:499
static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch)
static uint32_t getVersionMinUpdate(MachO::version_min_command &C, bool SDK)
Definition MachO.h:808
uint64_t BindRebaseAddress(uint32_t SegIndex, uint64_t SegOffset) const
For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase entry to get the address.
Definition MachO.h:635
StringRef BindRebaseSegmentName(int32_t SegIndex) const
For use with the SegIndex of a checked Mach-O Bind or Rebase entry to get the segment name.
Definition MachO.h:623
relocation_iterator extrel_begin() const
SmallVector< LoadCommandInfo, 4 > LoadCommandList
Definition MachO.h:432
MachO::data_in_code_entry getDice(DataRefImpl Rel) const
bool isSectionStripped(DataRefImpl Sec) const override
When dsymutil generates the companion file, it strips all unnecessary sections (e....
uint64_t getSectionIndex(DataRefImpl Sec) const override
StringRef BindRebaseSectionName(uint32_t SegIndex, uint64_t SegOffset) const
For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase entry to get the section ...
Definition MachO.h:629
static uint32_t getVersionMinMajor(MachO::version_min_command &C, bool SDK)
Definition MachO.h:796
uint64_t getSectionAddress(DataRefImpl Sec) const override
bool hasPageZeroSegment() const
Definition MachO.h:787
Expected< StringRef > getSectionName(DataRefImpl Sec) const override
bool isSectionText(DataRefImpl Sec) const override
bool isSectionCompressed(DataRefImpl Sec) const override
bool isSectionBitcode(DataRefImpl Sec) const override
Expected< SubtargetFeatures > getFeatures() const override
Definition MachO.h:540
uint32_t getSymbolAlignment(DataRefImpl Symb) const override
uint64_t getNValue(DataRefImpl Sym) const
ArrayRef< uint8_t > getSegmentContents(StringRef SegmentName) const
Return the raw contents of an entire segment.
ArrayRef< uint8_t > getSectionContents(uint64_t Offset, uint64_t Size) const
static uint32_t getVersionMinMinor(MachO::version_min_command &C, bool SDK)
Definition MachO.h:802
Expected< uint64_t > getSymbolAddress(DataRefImpl Symb) const override
size_t getMachOFilesetEntryOffset() const
Definition MachO.h:789
uint64_t getSectionSize(DataRefImpl Sec) const override
relocation_iterator extrel_end() const
LLVM_ABI int32_t segmentIndex() const
LLVM_ABI StringRef segmentName() const
LLVM_ABI MachORebaseEntry(Error *Err, const MachOObjectFile *O, ArrayRef< uint8_t > opcodes, bool is64Bit)
LLVM_ABI bool operator==(const MachORebaseEntry &) const
LLVM_ABI uint64_t address() const
LLVM_ABI StringRef sectionName() const
friend class MachOObjectFile
Definition MachO.h:186
LLVM_ABI uint64_t segmentOffset() const
LLVM_ABI StringRef typeName() const
This class is the base class for all object file types.
Definition ObjectFile.h:231
ObjectFile(unsigned int Type, MemoryBufferRef Source)
This is a value type class that represents a single section in the list of sections in the object fil...
Definition ObjectFile.h:83
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
@ TOOL_DSYMUTIL
Definition MachO.h:566
@ TOOL_SWIFT
Definition MachO.h:563
@ TOOL_CLANG
Definition MachO.h:562
@ BIND_SPECIAL_DYLIB_WEAK_LOOKUP
Definition MachO.h:260
Swift5ReflectionSectionKind
Definition Swift.h:14
Expected< const typename ELFT::Shdr * > getSection(typename ELFT::ShdrRange Sections, uint32_t Index)
Definition ELF.h:607
content_iterator< SectionRef > section_iterator
Definition ObjectFile.h:49
content_iterator< MachOBindEntry > bind_iterator
Definition MachO.h:263
content_iterator< MachOChainedFixupEntry > fixup_iterator
Definition MachO.h:424
content_iterator< MachORebaseEntry > rebase_iterator
Definition MachO.h:204
content_iterator< BasicSymbolRef > basic_symbol_iterator
content_iterator< ExportEntry > export_iterator
Definition MachO.h:126
content_iterator< RelocationRef > relocation_iterator
Definition ObjectFile.h:79
content_iterator< DiceRef > dice_iterator
Definition MachO.h:65
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
@ Done
Definition Threading.h:60
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::string utostr(uint64_t X, bool isNeg=false)
static Lanai::Fixups FixupKind(const MCExpr *Expr)
FormattedNumber format_hex(uint64_t N, unsigned Width, bool Upper=false)
format_hex - Output N as a fixed width hexadecimal.
Definition Format.h:164
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
Definition MachO.h:867
uint16_t length
Definition MachO.h:869
uint16_t kind
Definition MachO.h:870
uint32_t offset
Definition MachO.h:868
Definition MachO.h:964
ChainedFixupTarget(int LibOrdinal, uint32_t NameOffset, StringRef Symbol, uint64_t Addend, bool WeakImport)
Definition MachO.h:279
MachO::dyld_chained_starts_in_segment Header
Definition MachO.h:310
std::vector< uint16_t > PageStarts
Definition MachO.h:311
ChainedFixupsSegment(uint8_t SegIdx, uint32_t Offset, const MachO::dyld_chained_starts_in_segment &Header, std::vector< uint16_t > &&PageStarts)
Definition MachO.h:302