1 //===- MachO.h - MachO object file implementation ---------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the MachOObjectFile class, which implement the ObjectFile
11 // interface for MachO files.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_OBJECT_MACHO_H
16 #define LLVM_OBJECT_MACHO_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/MachO.h"
27 /// DiceRef - This is a value type class that represents a single
28 /// data in code entry in the table in a Mach-O object file.
30 DataRefImpl DicePimpl;
31 const ObjectFile *OwningObject;
34 DiceRef() : OwningObject(nullptr) { }
36 DiceRef(DataRefImpl DiceP, const ObjectFile *Owner);
38 bool operator==(const DiceRef &Other) const;
39 bool operator<(const DiceRef &Other) const;
43 std::error_code getOffset(uint32_t &Result) const;
44 std::error_code getLength(uint16_t &Result) const;
45 std::error_code getKind(uint16_t &Result) const;
47 DataRefImpl getRawDataRefImpl() const;
48 const ObjectFile *getObjectFile() const;
50 typedef content_iterator<DiceRef> dice_iterator;
52 /// ExportEntry encapsulates the current-state-of-the-walk used when doing a
53 /// non-recursive walk of the trie data structure. This allows you to iterate
54 /// across all exported symbols using:
55 /// for (const llvm::object::ExportEntry &AnExport : Obj->exports()) {
59 ExportEntry(ArrayRef<uint8_t> Trie);
61 StringRef name() const;
62 uint64_t flags() const;
63 uint64_t address() const;
64 uint64_t other() const;
65 StringRef otherName() const;
66 uint32_t nodeOffset() const;
68 bool operator==(const ExportEntry &) const;
73 friend class MachOObjectFile;
76 uint64_t readULEB128(const uint8_t *&p);
77 void pushDownUntilBottom();
78 void pushNode(uint64_t Offset);
80 // Represents a node in the mach-o exports trie.
82 NodeState(const uint8_t *Ptr);
84 const uint8_t *Current;
88 const char *ImportName;
90 unsigned NextChildIndex;
91 unsigned ParentStringLength;
95 ArrayRef<uint8_t> Trie;
96 SmallString<256> CumulativeString;
97 SmallVector<NodeState, 16> Stack;
101 typedef content_iterator<ExportEntry> export_iterator;
103 /// MachORebaseEntry encapsulates the current state in the decompression of
104 /// rebasing opcodes. This allows you to iterate through the compressed table of
106 /// for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
108 class MachORebaseEntry {
110 MachORebaseEntry(ArrayRef<uint8_t> opcodes, bool is64Bit);
112 uint32_t segmentIndex() const;
113 uint64_t segmentOffset() const;
114 StringRef typeName() const;
116 bool operator==(const MachORebaseEntry &) const;
121 friend class MachOObjectFile;
124 uint64_t readULEB128();
126 ArrayRef<uint8_t> Opcodes;
128 uint64_t SegmentOffset;
129 uint32_t SegmentIndex;
130 uint64_t RemainingLoopCount;
131 uint64_t AdvanceAmount;
137 typedef content_iterator<MachORebaseEntry> rebase_iterator;
139 /// MachOBindEntry encapsulates the current state in the decompression of
140 /// binding opcodes. This allows you to iterate through the compressed table of
142 /// for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
144 class MachOBindEntry {
146 enum class Kind { Regular, Lazy, Weak };
148 MachOBindEntry(ArrayRef<uint8_t> Opcodes, bool is64Bit, MachOBindEntry::Kind);
150 uint32_t segmentIndex() const;
151 uint64_t segmentOffset() const;
152 StringRef typeName() const;
153 StringRef symbolName() const;
154 uint32_t flags() const;
155 int64_t addend() const;
158 bool operator==(const MachOBindEntry &) const;
163 friend class MachOObjectFile;
166 uint64_t readULEB128();
167 int64_t readSLEB128();
169 ArrayRef<uint8_t> Opcodes;
171 uint64_t SegmentOffset;
172 uint32_t SegmentIndex;
173 StringRef SymbolName;
177 uint64_t RemainingLoopCount;
178 uint64_t AdvanceAmount;
185 typedef content_iterator<MachOBindEntry> bind_iterator;
187 class MachOObjectFile : public ObjectFile {
189 struct LoadCommandInfo {
190 const char *Ptr; // Where in memory the load command is.
191 MachO::load_command C; // The command itself.
193 typedef SmallVector<LoadCommandInfo, 4> LoadCommandList;
194 typedef LoadCommandList::const_iterator load_command_iterator;
196 static Expected<std::unique_ptr<MachOObjectFile>>
197 create(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
198 uint32_t UniversalCputype = 0, uint32_t UniversalIndex = 0);
200 void moveSymbolNext(DataRefImpl &Symb) const override;
202 uint64_t getNValue(DataRefImpl Sym) const;
203 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
206 Error checkSymbolTable() const;
208 std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const;
209 unsigned getSectionType(SectionRef Sec) const;
211 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
212 uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
213 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
214 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
215 uint32_t getSymbolFlags(DataRefImpl Symb) const override;
216 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
217 unsigned getSymbolSectionID(SymbolRef Symb) const;
218 unsigned getSectionID(SectionRef Sec) const;
220 void moveSectionNext(DataRefImpl &Sec) const override;
221 std::error_code getSectionName(DataRefImpl Sec,
222 StringRef &Res) const override;
223 uint64_t getSectionAddress(DataRefImpl Sec) const override;
224 uint64_t getSectionSize(DataRefImpl Sec) const override;
225 std::error_code getSectionContents(DataRefImpl Sec,
226 StringRef &Res) const override;
227 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
228 bool isSectionCompressed(DataRefImpl Sec) const override;
229 bool isSectionText(DataRefImpl Sec) const override;
230 bool isSectionData(DataRefImpl Sec) const override;
231 bool isSectionBSS(DataRefImpl Sec) const override;
232 bool isSectionVirtual(DataRefImpl Sec) const override;
233 bool isSectionBitcode(DataRefImpl Sec) const override;
234 relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
235 relocation_iterator section_rel_end(DataRefImpl Sec) const override;
237 void moveRelocationNext(DataRefImpl &Rel) const override;
238 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
239 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
240 section_iterator getRelocationSection(DataRefImpl Rel) const;
241 uint64_t getRelocationType(DataRefImpl Rel) const override;
242 void getRelocationTypeName(DataRefImpl Rel,
243 SmallVectorImpl<char> &Result) const override;
244 uint8_t getRelocationLength(DataRefImpl Rel) const;
247 std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const;
249 section_iterator getRelocationRelocatedSection(relocation_iterator Rel) const;
251 // TODO: Would be useful to have an iterator based version
252 // of the load command interface too.
254 basic_symbol_iterator symbol_begin() const override;
255 basic_symbol_iterator symbol_end() const override;
258 basic_symbol_iterator getSymbolByIndex(unsigned Index) const;
259 uint64_t getSymbolIndex(DataRefImpl Symb) const;
261 section_iterator section_begin() const override;
262 section_iterator section_end() const override;
264 uint8_t getBytesInAddress() const override;
266 StringRef getFileFormatName() const override;
267 unsigned getArch() const override;
268 SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); }
269 Triple getArchTriple(const char **McpuDefault = nullptr) const;
271 relocation_iterator section_rel_begin(unsigned Index) const;
272 relocation_iterator section_rel_end(unsigned Index) const;
274 dice_iterator begin_dices() const;
275 dice_iterator end_dices() const;
277 load_command_iterator begin_load_commands() const;
278 load_command_iterator end_load_commands() const;
279 iterator_range<load_command_iterator> load_commands() const;
281 /// For use iterating over all exported symbols.
282 iterator_range<export_iterator> exports() const;
284 /// For use examining a trie not in a MachOObjectFile.
285 static iterator_range<export_iterator> exports(ArrayRef<uint8_t> Trie);
287 /// For use iterating over all rebase table entries.
288 iterator_range<rebase_iterator> rebaseTable() const;
290 /// For use examining rebase opcodes not in a MachOObjectFile.
291 static iterator_range<rebase_iterator> rebaseTable(ArrayRef<uint8_t> Opcodes,
294 /// For use iterating over all bind table entries.
295 iterator_range<bind_iterator> bindTable() const;
297 /// For use iterating over all lazy bind table entries.
298 iterator_range<bind_iterator> lazyBindTable() const;
300 /// For use iterating over all lazy bind table entries.
301 iterator_range<bind_iterator> weakBindTable() const;
303 /// For use examining bind opcodes not in a MachOObjectFile.
304 static iterator_range<bind_iterator> bindTable(ArrayRef<uint8_t> Opcodes,
306 MachOBindEntry::Kind);
309 // In a MachO file, sections have a segment name. This is used in the .o
310 // files. They have a single segment, but this field specifies which segment
311 // a section should be put in in the final object.
312 StringRef getSectionFinalSegmentName(DataRefImpl Sec) const;
314 // Names are stored as 16 bytes. These returns the raw 16 bytes without
315 // interpreting them as a C string.
316 ArrayRef<char> getSectionRawName(DataRefImpl Sec) const;
317 ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const;
319 // MachO specific Info about relocations.
320 bool isRelocationScattered(const MachO::any_relocation_info &RE) const;
321 unsigned getPlainRelocationSymbolNum(
322 const MachO::any_relocation_info &RE) const;
323 bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const;
324 bool getScatteredRelocationScattered(
325 const MachO::any_relocation_info &RE) const;
326 uint32_t getScatteredRelocationValue(
327 const MachO::any_relocation_info &RE) const;
328 uint32_t getScatteredRelocationType(
329 const MachO::any_relocation_info &RE) const;
330 unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const;
331 unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const;
332 unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const;
333 unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const;
334 SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const;
336 // MachO specific structures.
337 MachO::section getSection(DataRefImpl DRI) const;
338 MachO::section_64 getSection64(DataRefImpl DRI) const;
339 MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const;
340 MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const;
341 MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const;
342 MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const;
344 MachO::linkedit_data_command
345 getLinkeditDataLoadCommand(const LoadCommandInfo &L) const;
346 MachO::segment_command
347 getSegmentLoadCommand(const LoadCommandInfo &L) const;
348 MachO::segment_command_64
349 getSegment64LoadCommand(const LoadCommandInfo &L) const;
350 MachO::linker_option_command
351 getLinkerOptionLoadCommand(const LoadCommandInfo &L) const;
352 MachO::version_min_command
353 getVersionMinLoadCommand(const LoadCommandInfo &L) const;
355 getDylibIDLoadCommand(const LoadCommandInfo &L) const;
356 MachO::dyld_info_command
357 getDyldInfoLoadCommand(const LoadCommandInfo &L) const;
358 MachO::dylinker_command
359 getDylinkerCommand(const LoadCommandInfo &L) const;
361 getUuidCommand(const LoadCommandInfo &L) const;
363 getRpathCommand(const LoadCommandInfo &L) const;
364 MachO::source_version_command
365 getSourceVersionCommand(const LoadCommandInfo &L) const;
366 MachO::entry_point_command
367 getEntryPointCommand(const LoadCommandInfo &L) const;
368 MachO::encryption_info_command
369 getEncryptionInfoCommand(const LoadCommandInfo &L) const;
370 MachO::encryption_info_command_64
371 getEncryptionInfoCommand64(const LoadCommandInfo &L) const;
372 MachO::sub_framework_command
373 getSubFrameworkCommand(const LoadCommandInfo &L) const;
374 MachO::sub_umbrella_command
375 getSubUmbrellaCommand(const LoadCommandInfo &L) const;
376 MachO::sub_library_command
377 getSubLibraryCommand(const LoadCommandInfo &L) const;
378 MachO::sub_client_command
379 getSubClientCommand(const LoadCommandInfo &L) const;
380 MachO::routines_command
381 getRoutinesCommand(const LoadCommandInfo &L) const;
382 MachO::routines_command_64
383 getRoutinesCommand64(const LoadCommandInfo &L) const;
384 MachO::thread_command
385 getThreadCommand(const LoadCommandInfo &L) const;
387 MachO::any_relocation_info getRelocation(DataRefImpl Rel) const;
388 MachO::data_in_code_entry getDice(DataRefImpl Rel) const;
389 const MachO::mach_header &getHeader() const;
390 const MachO::mach_header_64 &getHeader64() const;
392 getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC,
393 unsigned Index) const;
394 MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset,
395 unsigned Index) const;
396 MachO::symtab_command getSymtabLoadCommand() const;
397 MachO::dysymtab_command getDysymtabLoadCommand() const;
398 MachO::linkedit_data_command getDataInCodeLoadCommand() const;
399 MachO::linkedit_data_command getLinkOptHintsLoadCommand() const;
400 ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const;
401 ArrayRef<uint8_t> getDyldInfoBindOpcodes() const;
402 ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const;
403 ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const;
404 ArrayRef<uint8_t> getDyldInfoExportsTrie() const;
405 ArrayRef<uint8_t> getUuid() const;
407 StringRef getStringTableData() const;
408 bool is64Bit() const;
409 void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
411 static StringRef guessLibraryShortName(StringRef Name, bool &isFramework,
414 static Triple::ArchType getArch(uint32_t CPUType);
415 static Triple getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
416 const char **McpuDefault = nullptr,
417 const char **ArchFlag = nullptr);
418 static bool isValidArch(StringRef ArchFlag);
419 static Triple getHostArch();
421 bool isRelocatableObject() const override;
423 bool hasPageZeroSegment() const { return HasPageZeroSegment; }
425 static bool classof(const Binary *v) {
430 getVersionMinMajor(MachO::version_min_command &C, bool SDK) {
431 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
432 return (VersionOrSDK >> 16) & 0xffff;
436 getVersionMinMinor(MachO::version_min_command &C, bool SDK) {
437 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
438 return (VersionOrSDK >> 8) & 0xff;
442 getVersionMinUpdate(MachO::version_min_command &C, bool SDK) {
443 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version;
444 return VersionOrSDK & 0xff;
449 MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits,
450 Error &Err, uint32_t UniversalCputype = 0,
451 uint32_t UniversalIndex = 0);
453 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
456 MachO::mach_header_64 Header64;
457 MachO::mach_header Header;
459 typedef SmallVector<const char*, 1> SectionList;
460 SectionList Sections;
461 typedef SmallVector<const char*, 1> LibraryList;
462 LibraryList Libraries;
463 LoadCommandList LoadCommands;
464 typedef SmallVector<StringRef, 1> LibraryShortName;
465 mutable LibraryShortName LibrariesShortNames;
466 const char *SymtabLoadCmd;
467 const char *DysymtabLoadCmd;
468 const char *DataInCodeLoadCmd;
469 const char *LinkOptHintsLoadCmd;
470 const char *DyldInfoLoadCmd;
471 const char *UuidLoadCmd;
472 bool HasPageZeroSegment;
476 inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner)
477 : DicePimpl(DiceP) , OwningObject(Owner) {}
479 inline bool DiceRef::operator==(const DiceRef &Other) const {
480 return DicePimpl == Other.DicePimpl;
483 inline bool DiceRef::operator<(const DiceRef &Other) const {
484 return DicePimpl < Other.DicePimpl;
487 inline void DiceRef::moveNext() {
488 const MachO::data_in_code_entry *P =
489 reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p);
490 DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1);
493 // Since a Mach-O data in code reference, a DiceRef, can only be created when
494 // the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for
495 // the methods that get the values of the fields of the reference.
497 inline std::error_code DiceRef::getOffset(uint32_t &Result) const {
498 const MachOObjectFile *MachOOF =
499 static_cast<const MachOObjectFile *>(OwningObject);
500 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
501 Result = Dice.offset;
502 return std::error_code();
505 inline std::error_code DiceRef::getLength(uint16_t &Result) const {
506 const MachOObjectFile *MachOOF =
507 static_cast<const MachOObjectFile *>(OwningObject);
508 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
509 Result = Dice.length;
510 return std::error_code();
513 inline std::error_code DiceRef::getKind(uint16_t &Result) const {
514 const MachOObjectFile *MachOOF =
515 static_cast<const MachOObjectFile *>(OwningObject);
516 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl);
518 return std::error_code();
521 inline DataRefImpl DiceRef::getRawDataRefImpl() const {
525 inline const ObjectFile *DiceRef::getObjectFile() const {