LLVM 22.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 {
125 return make_range(Stack.begin(), Stack.end());
126 }
127};
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.
135public:
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
148private:
149 struct SectionInfo {
151 uint64_t Size;
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
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 ...
172public:
174 ArrayRef<uint8_t> opcodes, bool is64Bit);
175
176 LLVM_ABI int32_t segmentIndex() const;
181 LLVM_ABI uint64_t address() const;
182
183 LLVM_ABI bool operator==(const MachORebaseEntry &) const;
184
185 LLVM_ABI void moveNext();
186
187private:
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;
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};
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 ...
216public:
217 enum class Kind { Regular, Lazy, Weak };
218
220 ArrayRef<uint8_t> Opcodes, bool is64Bit,
222
223 LLVM_ABI int32_t segmentIndex() const;
227 LLVM_ABI uint32_t flags() const;
228 LLVM_ABI int64_t addend() const;
229 LLVM_ABI int ordinal() const;
230
233 LLVM_ABI uint64_t address() const;
234
235 LLVM_ABI bool operator==(const MachOBindEntry &) const;
236
237 LLVM_ABI void moveNext();
238
239private:
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;
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};
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."
280public:
281 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
286 int libOrdinal() { return LibOrdinal; }
287 uint32_t nameOffset() { return NameOffset; }
288 StringRef symbolName() { return SymbolName; }
289 uint64_t addend() { return Addend; }
290 bool weakImport() { return WeakImport; }
291 bool weakBind() {
292 return LibOrdinal == MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP;
293 }
294
295private:
296 int LibOrdinal;
297 uint32_t NameOffset;
298 StringRef SymbolName;
299 uint64_t Addend;
300 bool WeakImport;
301};
302
306 std::vector<uint16_t> &&PageStarts)
309
311 uint32_t Offset; // dyld_chained_starts_in_image::seg_info_offset[SegIdx]
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.
327public:
329
330 LLVM_ABI int32_t segmentIndex() 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.
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.
355 uint64_t rawValue() const { return RawValue; }
356
357 LLVM_ABI void moveNext();
358
359protected:
363 int32_t SegmentIndex = -1;
365 int32_t Ordinal = 0;
367 int64_t Addend = 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.
376 uint64_t textAddress() const { return TextAddress; }
377
378private:
379 uint64_t TextAddress;
380};
381
383public:
384 enum class FixupKind { Bind, Rebase };
385
387 bool Parse);
388
389 LLVM_ABI bool operator==(const MachOChainedFixupEntry &) const;
390
391 bool isBind() const { return Kind == FixupKind::Bind; }
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
398private:
399 void findNextPageWithFixups();
400
401 std::vector<ChainedFixupTarget> FixupTargets;
402 std::vector<ChainedFixupsSegment> Segments;
403 ArrayRef<uint8_t> SegmentData;
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};
410
412public:
414 const char *Ptr; // Where in memory the load command is.
415 MachO::load_command C; // The command itself.
416 };
419
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;
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;
454 getSectionContents(DataRefImpl Sec) const override;
455 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
456 Expected<SectionRef> getSection(unsigned SectionIndex) 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;
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;
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,
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,
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,
573 ArrayRef<uint8_t> Opcodes,
574 bool is64,
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.
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.
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.
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.
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
660 getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
662 getSegmentLoadCommand(const LoadCommandInfo &L) const;
664 getSegment64LoadCommand(const LoadCommandInfo &L) const;
666 getLinkerOptionLoadCommand(const LoadCommandInfo &L) const;
668 getVersionMinLoadCommand(const LoadCommandInfo &L) const;
670 getNoteLoadCommand(const LoadCommandInfo &L) const;
672 getBuildVersionLoadCommand(const LoadCommandInfo &L) const;
674 getBuildToolVersion(unsigned index) const;
676 getDylibIDLoadCommand(const LoadCommandInfo &L) const;
678 getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
680 getDylinkerCommand(const LoadCommandInfo &L) const;
682 getUuidCommand(const LoadCommandInfo &L) const;
684 getRpathCommand(const LoadCommandInfo &L) const;
686 getSourceVersionCommand(const LoadCommandInfo &L) const;
688 getEntryPointCommand(const LoadCommandInfo &L) const;
690 getEncryptionInfoCommand(const LoadCommandInfo &L) const;
692 getEncryptionInfoCommand64(const LoadCommandInfo &L) const;
694 getSubFrameworkCommand(const LoadCommandInfo &L) const;
696 getSubUmbrellaCommand(const LoadCommandInfo &L) const;
698 getSubLibraryCommand(const LoadCommandInfo &L) const;
700 getSubClientCommand(const LoadCommandInfo &L) const;
702 getRoutinesCommand(const LoadCommandInfo &L) const;
704 getRoutinesCommand64(const LoadCommandInfo &L) const;
706 getThreadCommand(const LoadCommandInfo &L) const;
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;
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.
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.
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.
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
768 mapReflectionSectionNameToEnumValue(StringRef SectionName) const override;
769
770 bool hasPageZeroSegment() const { return HasPageZeroSegment; }
771
772 size_t getMachOFilesetEntryOffset() const { return MachOFilesetEntryOffset; }
773
774 static bool classof(const Binary *v) {
775 return v->isMachO();
776 }
777
778 static uint32_t
780 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
781 return (VersionOrSDK >> 16) & 0xffff;
782 }
783
784 static uint32_t
786 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
787 return (VersionOrSDK >> 8) & 0xff;
788 }
789
790 static uint32_t
792 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
793 return VersionOrSDK & 0xff;
794 }
795
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
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
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.
843 findDsymObjectMembers(StringRef Path);
844
845private:
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 {
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
881inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner)
882 : DicePimpl(DiceP) , OwningObject(Owner) {}
883
884inline bool DiceRef::operator==(const DiceRef &Other) const {
885 return DicePimpl == Other.DicePimpl;
886}
887
888inline bool DiceRef::operator<(const DiceRef &Other) const {
889 return DicePimpl < Other.DicePimpl;
890}
891
892inline void DiceRef::moveNext() {
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
902inline 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
910inline 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
918inline 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
927 return DicePimpl;
928}
929
930inline 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
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static StringRef getSymbolName(SymbolKind SymKind)
#define LLVM_ABI
Definition: Compiler.h:213
std::string Name
uint32_t Index
uint64_t Size
static bool isDebugSection(const SectionBase &Sec)
Definition: ELFObjcopy.cpp:49
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1328
uint64_t Offset
Definition: ELF_riscv.cpp:478
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 unsigned getSymbolSectionID(const ObjectFile &O, SymbolRef Sym)
Definition: SymbolSize.cpp:39
static unsigned getSectionID(const ObjectFile &O, SectionRef Sec)
Definition: SymbolSize.cpp:29
static std::unique_ptr< PDBSymbol > getSymbolType(const PDBSymbol &Symbol)
Definition: UDTLayout.cpp:35
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: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...
Definition: SmallVector.h:574
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
Manages the enabling and disabling of subtarget specific features.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:47
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 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)
DiceRef - This is a value type class that represents a single data in code entry in the table in a Ma...
Definition: MachO.h:45
bool operator==(const DiceRef &Other) const
Definition: MachO.h:884
std::error_code getOffset(uint32_t &Result) const
Definition: MachO.h:902
std::error_code getLength(uint16_t &Result) const
Definition: MachO.h:910
bool operator<(const DiceRef &Other) const
Definition: MachO.h:888
DataRefImpl getRawDataRefImpl() const
Definition: MachO.h:926
std::error_code getKind(uint16_t &Result) const
Definition: MachO.h:918
const ObjectFile * getObjectFile() const
Definition: MachO.h:930
ExportEntry encapsulates the current-state-of-the-walk used when doing a non-recursive walk of the tr...
Definition: MachO.h:74
LLVM_ABI StringRef name() const
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
LLVM_ABI uint64_t other() const
MachOAbstractFixupEntry is an abstract class representing a fixup in a MH_DYLDLINK file.
Definition: MachO.h:326
LLVM_ABI StringRef sectionName() const
LLVM_ABI uint64_t segmentAddress() const
LLVM_ABI StringRef symbolName() const
LLVM_ABI StringRef segmentName() const
const MachOObjectFile * O
Definition: MachO.h:361
LLVM_ABI uint64_t segmentOffset() const
MachOBindEntry encapsulates the current state in the decompression of binding opcodes.
Definition: MachO.h:215
LLVM_ABI uint32_t flags() const
LLVM_ABI StringRef symbolName() const
LLVM_ABI StringRef sectionName() const
LLVM_ABI StringRef segmentName() const
LLVM_ABI uint64_t segmentOffset() const
LLVM_ABI int64_t addend() const
LLVM_ABI uint64_t address() const
LLVM_ABI int32_t segmentIndex() const
LLVM_ABI StringRef typeName() const
static std::string getVersionString(uint32_t version)
Definition: MachO.h:826
MachO::mach_header_64 Header64
Definition: MachO.h:854
const char * RebaseEntryCheckSegAndOffsets(int32_t SegIndex, uint64_t SegOffset, uint8_t PointerSize, uint64_t Count=1, uint64_t Skip=0) const
Definition: MachO.h:597
MachO::mach_header Header
Definition: MachO.h:855
static std::string getBuildTool(uint32_t tools)
Definition: MachO.h:811
const char * BindEntryCheckSegAndOffsets(int32_t SegIndex, uint64_t SegOffset, uint8_t PointerSize, uint64_t Count=1, uint64_t Skip=0) const
Definition: MachO.h:583
static std::string getBuildPlatform(uint32_t platform)
Definition: MachO.h:796
static bool classof(const Binary *v)
Definition: MachO.h:774
iterator_range< relocation_iterator > external_relocations() const
Definition: MachO.h:484
static uint32_t getVersionMinUpdate(MachO::version_min_command &C, bool SDK)
Definition: MachO.h:791
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:620
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:608
MachO::data_in_code_entry getDice(DataRefImpl Rel) 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:614
static uint32_t getVersionMinMajor(MachO::version_min_command &C, bool SDK)
Definition: MachO.h:779
bool hasPageZeroSegment() const
Definition: MachO.h:770
Expected< SubtargetFeatures > getFeatures() const override
Definition: MachO.h:525
static uint32_t getVersionMinMinor(MachO::version_min_command &C, bool SDK)
Definition: MachO.h:785
size_t getMachOFilesetEntryOffset() const
Definition: MachO.h:772
MachORebaseEntry encapsulates the current state in the decompression of rebasing opcodes.
Definition: MachO.h:171
LLVM_ABI int32_t segmentIndex() const
LLVM_ABI StringRef segmentName() const
LLVM_ABI bool operator==(const MachORebaseEntry &) const
LLVM_ABI uint64_t address() const
LLVM_ABI StringRef sectionName() const
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
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:83
This is a value type class that represents a single symbol in the list of symbols in the object file.
Definition: ObjectFile.h:170
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:662
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
@ BIND_SPECIAL_DYLIB_WEAK_LOOKUP
Definition: MachO.h:264
Swift5ReflectionSectionKind
Definition: Swift.h:14
Expected< const typename ELFT::Shdr * > getSection(typename ELFT::ShdrRange Sections, uint32_t Index)
Definition: ELF.h:539
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
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:188
@ 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:279
ChainedFixupTarget(int LibOrdinal, uint32_t NameOffset, StringRef Symbol, uint64_t Addend, bool WeakImport)
Definition: MachO.h:281
MachO::dyld_chained_starts_in_segment Header
Definition: MachO.h:312
std::vector< uint16_t > PageStarts
Definition: MachO.h:313
ChainedFixupsSegment(uint8_t SegIdx, uint32_t Offset, const MachO::dyld_chained_starts_in_segment &Header, std::vector< uint16_t > &&PageStarts)
Definition: MachO.h:304