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