1 //===- MachOObjectFile.cpp - Mach-O object file binding ---------*- 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 defines the MachOObjectFile class, which binds the MachOObject
11 // class to the generic ObjectFile wrapper.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Object/MachO.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Support/DataExtractor.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/Host.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/raw_ostream.h"
28 using namespace object;
31 using std::error_code;
48 static void SwapValue(T &Value) {
49 Value = sys::SwapByteOrder(Value);
53 static void SwapStruct(T &Value);
56 void SwapStruct(MachO::any_relocation_info &H) {
62 void SwapStruct(MachO::load_command &L) {
68 void SwapStruct(nlist_base &S) {
74 void SwapStruct(MachO::section &S) {
82 SwapValue(S.reserved1);
83 SwapValue(S.reserved2);
87 void SwapStruct(MachO::section_64 &S) {
95 SwapValue(S.reserved1);
96 SwapValue(S.reserved2);
97 SwapValue(S.reserved3);
101 void SwapStruct(MachO::nlist &S) {
104 SwapValue(S.n_value);
108 void SwapStruct(MachO::nlist_64 &S) {
111 SwapValue(S.n_value);
115 void SwapStruct(MachO::mach_header &H) {
117 SwapValue(H.cputype);
118 SwapValue(H.cpusubtype);
119 SwapValue(H.filetype);
121 SwapValue(H.sizeofcmds);
126 void SwapStruct(MachO::mach_header_64 &H) {
128 SwapValue(H.cputype);
129 SwapValue(H.cpusubtype);
130 SwapValue(H.filetype);
132 SwapValue(H.sizeofcmds);
134 SwapValue(H.reserved);
138 void SwapStruct(MachO::symtab_command &C) {
140 SwapValue(C.cmdsize);
144 SwapValue(C.strsize);
148 void SwapStruct(MachO::dysymtab_command &C) {
150 SwapValue(C.cmdsize);
151 SwapValue(C.ilocalsym);
152 SwapValue(C.nlocalsym);
153 SwapValue(C.iextdefsym);
154 SwapValue(C.nextdefsym);
155 SwapValue(C.iundefsym);
156 SwapValue(C.nundefsym);
159 SwapValue(C.modtaboff);
160 SwapValue(C.nmodtab);
161 SwapValue(C.extrefsymoff);
162 SwapValue(C.nextrefsyms);
163 SwapValue(C.indirectsymoff);
164 SwapValue(C.nindirectsyms);
165 SwapValue(C.extreloff);
166 SwapValue(C.nextrel);
167 SwapValue(C.locreloff);
168 SwapValue(C.nlocrel);
172 void SwapStruct(MachO::linkedit_data_command &C) {
174 SwapValue(C.cmdsize);
175 SwapValue(C.dataoff);
176 SwapValue(C.datasize);
180 void SwapStruct(MachO::segment_command &C) {
182 SwapValue(C.cmdsize);
185 SwapValue(C.fileoff);
186 SwapValue(C.filesize);
187 SwapValue(C.maxprot);
188 SwapValue(C.initprot);
194 void SwapStruct(MachO::segment_command_64 &C) {
196 SwapValue(C.cmdsize);
199 SwapValue(C.fileoff);
200 SwapValue(C.filesize);
201 SwapValue(C.maxprot);
202 SwapValue(C.initprot);
208 void SwapStruct(uint32_t &C) {
213 void SwapStruct(MachO::linker_options_command &C) {
215 SwapValue(C.cmdsize);
220 void SwapStruct(MachO::version_min_command&C) {
222 SwapValue(C.cmdsize);
223 SwapValue(C.version);
224 SwapValue(C.reserved);
228 void SwapStruct(MachO::dylib_command&C) {
230 SwapValue(C.cmdsize);
231 SwapValue(C.dylib.name);
232 SwapValue(C.dylib.timestamp);
233 SwapValue(C.dylib.current_version);
234 SwapValue(C.dylib.compatibility_version);
238 void SwapStruct(MachO::data_in_code_entry &C) {
245 T getStruct(const MachOObjectFile *O, const char *P) {
247 memcpy(&Cmd, P, sizeof(T));
248 if (O->isLittleEndian() != sys::IsLittleEndianHost)
254 getSegmentLoadCommandNumSections(const MachOObjectFile *O,
255 const MachOObjectFile::LoadCommandInfo &L) {
257 MachO::segment_command_64 S = O->getSegment64LoadCommand(L);
260 MachO::segment_command S = O->getSegmentLoadCommand(L);
265 getSectionPtr(const MachOObjectFile *O, MachOObjectFile::LoadCommandInfo L,
267 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
269 bool Is64 = O->is64Bit();
270 unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
271 sizeof(MachO::segment_command);
272 unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
273 sizeof(MachO::section);
275 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
276 return reinterpret_cast<const char*>(SectionAddr);
279 static const char *getPtr(const MachOObjectFile *O, size_t Offset) {
280 return O->getData().substr(Offset, 1).data();
284 getSymbolTableEntryBase(const MachOObjectFile *O, DataRefImpl DRI) {
285 const char *P = reinterpret_cast<const char *>(DRI.p);
286 return getStruct<nlist_base>(O, P);
289 static StringRef parseSegmentOrSectionName(const char *P) {
293 // Not null terminated, so this is a 16 char string.
294 return StringRef(P, 16);
297 // Helper to advance a section or symbol iterator multiple increments at a time.
299 static void advance(T &it, size_t Val) {
304 static unsigned getCPUType(const MachOObjectFile *O) {
305 return O->getHeader().cputype;
308 static void printRelocationTargetName(const MachOObjectFile *O,
309 const MachO::any_relocation_info &RE,
310 raw_string_ostream &fmt) {
311 bool IsScattered = O->isRelocationScattered(RE);
313 // Target of a scattered relocation is an address. In the interest of
314 // generating pretty output, scan through the symbol table looking for a
315 // symbol that aligns with that address. If we find one, print it.
316 // Otherwise, we just print the hex address of the target.
318 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
320 for (const SymbolRef &Symbol : O->symbols()) {
325 if ((ec = Symbol.getAddress(Addr)))
326 report_fatal_error(ec.message());
329 if ((ec = Symbol.getName(Name)))
330 report_fatal_error(ec.message());
335 // If we couldn't find a symbol that this relocation refers to, try
336 // to find a section beginning instead.
337 for (const SectionRef &Section : O->sections()) {
342 if ((ec = Section.getAddress(Addr)))
343 report_fatal_error(ec.message());
346 if ((ec = Section.getName(Name)))
347 report_fatal_error(ec.message());
352 fmt << format("0x%x", Val);
357 bool isExtern = O->getPlainRelocationExternal(RE);
358 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
361 symbol_iterator SI = O->symbol_begin();
365 section_iterator SI = O->section_begin();
366 // Adjust for the fact that sections are 1-indexed.
367 advance(SI, Val - 1);
375 getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
380 getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
381 return RE.r_word0 & 0xffffff;
384 static bool getPlainRelocationPCRel(const MachOObjectFile *O,
385 const MachO::any_relocation_info &RE) {
386 if (O->isLittleEndian())
387 return (RE.r_word1 >> 24) & 1;
388 return (RE.r_word1 >> 7) & 1;
392 getScatteredRelocationPCRel(const MachOObjectFile *O,
393 const MachO::any_relocation_info &RE) {
394 return (RE.r_word0 >> 30) & 1;
397 static unsigned getPlainRelocationLength(const MachOObjectFile *O,
398 const MachO::any_relocation_info &RE) {
399 if (O->isLittleEndian())
400 return (RE.r_word1 >> 25) & 3;
401 return (RE.r_word1 >> 5) & 3;
405 getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
406 return (RE.r_word0 >> 28) & 3;
409 static unsigned getPlainRelocationType(const MachOObjectFile *O,
410 const MachO::any_relocation_info &RE) {
411 if (O->isLittleEndian())
412 return RE.r_word1 >> 28;
413 return RE.r_word1 & 0xf;
417 getScatteredRelocationType(const MachO::any_relocation_info &RE) {
418 return (RE.r_word0 >> 24) & 0xf;
421 static uint32_t getSectionFlags(const MachOObjectFile *O,
424 MachO::section_64 Sect = O->getSection64(Sec);
427 MachO::section Sect = O->getSection(Sec);
431 MachOObjectFile::MachOObjectFile(MemoryBuffer *Object, bool IsLittleEndian,
432 bool Is64bits, std::error_code &EC,
434 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object, BufferOwned),
435 SymtabLoadCmd(nullptr), DysymtabLoadCmd(nullptr),
436 DataInCodeLoadCmd(nullptr) {
437 uint32_t LoadCommandCount = this->getHeader().ncmds;
438 MachO::LoadCommandType SegmentLoadType = is64Bit() ?
439 MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT;
441 MachOObjectFile::LoadCommandInfo Load = getFirstLoadCommandInfo();
442 for (unsigned I = 0; ; ++I) {
443 if (Load.C.cmd == MachO::LC_SYMTAB) {
444 assert(!SymtabLoadCmd && "Multiple symbol tables");
445 SymtabLoadCmd = Load.Ptr;
446 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
447 assert(!DysymtabLoadCmd && "Multiple dynamic symbol tables");
448 DysymtabLoadCmd = Load.Ptr;
449 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
450 assert(!DataInCodeLoadCmd && "Multiple data in code tables");
451 DataInCodeLoadCmd = Load.Ptr;
452 } else if (Load.C.cmd == SegmentLoadType) {
453 uint32_t NumSections = getSegmentLoadCommandNumSections(this, Load);
454 for (unsigned J = 0; J < NumSections; ++J) {
455 const char *Sec = getSectionPtr(this, Load, J);
456 Sections.push_back(Sec);
458 } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB ||
459 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
460 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
461 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
462 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
463 Libraries.push_back(Load.Ptr);
466 if (I == LoadCommandCount - 1)
469 Load = getNextLoadCommandInfo(Load);
473 void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
474 unsigned SymbolTableEntrySize = is64Bit() ?
475 sizeof(MachO::nlist_64) :
476 sizeof(MachO::nlist);
477 Symb.p += SymbolTableEntrySize;
480 std::error_code MachOObjectFile::getSymbolName(DataRefImpl Symb,
481 StringRef &Res) const {
482 StringRef StringTable = getStringTableData();
483 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
484 const char *Start = &StringTable.data()[Entry.n_strx];
485 Res = StringRef(Start);
486 return object_error::success;
489 // getIndirectName() returns the name of the alias'ed symbol who's string table
490 // index is in the n_value field.
491 std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
492 StringRef &Res) const {
493 StringRef StringTable = getStringTableData();
496 MachO::nlist_64 Entry = getSymbol64TableEntry(Symb);
497 NValue = Entry.n_value;
498 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
499 return object_error::parse_failed;
501 MachO::nlist Entry = getSymbolTableEntry(Symb);
502 NValue = Entry.n_value;
503 if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
504 return object_error::parse_failed;
506 if (NValue >= StringTable.size())
507 return object_error::parse_failed;
508 const char *Start = &StringTable.data()[NValue];
509 Res = StringRef(Start);
510 return object_error::success;
513 std::error_code MachOObjectFile::getSymbolAddress(DataRefImpl Symb,
514 uint64_t &Res) const {
516 MachO::nlist_64 Entry = getSymbol64TableEntry(Symb);
517 if ((Entry.n_type & MachO::N_TYPE) == MachO::N_UNDF &&
519 Res = UnknownAddressOrSize;
523 MachO::nlist Entry = getSymbolTableEntry(Symb);
524 if ((Entry.n_type & MachO::N_TYPE) == MachO::N_UNDF &&
526 Res = UnknownAddressOrSize;
530 return object_error::success;
533 std::error_code MachOObjectFile::getSymbolAlignment(DataRefImpl DRI,
534 uint32_t &Result) const {
535 uint32_t flags = getSymbolFlags(DRI);
536 if (flags & SymbolRef::SF_Common) {
537 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
538 Result = 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
542 return object_error::success;
545 std::error_code MachOObjectFile::getSymbolSize(DataRefImpl DRI,
546 uint64_t &Result) const {
547 uint64_t BeginOffset;
548 uint64_t EndOffset = 0;
549 uint8_t SectionIndex;
551 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
553 getSymbolAddress(DRI, Value);
554 if (Value == UnknownAddressOrSize) {
555 Result = UnknownAddressOrSize;
556 return object_error::success;
561 SectionIndex = Entry.n_sect;
563 uint32_t flags = getSymbolFlags(DRI);
564 if (flags & SymbolRef::SF_Common)
567 Result = UnknownAddressOrSize;
568 return object_error::success;
570 // Unfortunately symbols are unsorted so we need to touch all
571 // symbols from load command
572 for (const SymbolRef &Symbol : symbols()) {
573 DataRefImpl DRI = Symbol.getRawDataRefImpl();
574 Entry = getSymbolTableEntryBase(this, DRI);
575 getSymbolAddress(DRI, Value);
576 if (Value == UnknownAddressOrSize)
578 if (Entry.n_sect == SectionIndex && Value > BeginOffset)
579 if (!EndOffset || Value < EndOffset)
585 Sec.d.a = SectionIndex-1;
586 getSectionSize(Sec, Size);
587 getSectionAddress(Sec, EndOffset);
590 Result = EndOffset - BeginOffset;
591 return object_error::success;
594 std::error_code MachOObjectFile::getSymbolType(DataRefImpl Symb,
595 SymbolRef::Type &Res) const {
596 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
597 uint8_t n_type = Entry.n_type;
599 Res = SymbolRef::ST_Other;
601 // If this is a STAB debugging symbol, we can do nothing more.
602 if (n_type & MachO::N_STAB) {
603 Res = SymbolRef::ST_Debug;
604 return object_error::success;
607 switch (n_type & MachO::N_TYPE) {
609 Res = SymbolRef::ST_Unknown;
612 Res = SymbolRef::ST_Function;
615 return object_error::success;
618 uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
619 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
621 uint8_t MachOType = Entry.n_type;
622 uint16_t MachOFlags = Entry.n_desc;
624 uint32_t Result = SymbolRef::SF_None;
626 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF)
627 Result |= SymbolRef::SF_Undefined;
629 if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
630 Result |= SymbolRef::SF_Indirect;
632 if (MachOType & MachO::N_STAB)
633 Result |= SymbolRef::SF_FormatSpecific;
635 if (MachOType & MachO::N_EXT) {
636 Result |= SymbolRef::SF_Global;
637 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
639 getSymbolAddress(DRI, Value);
640 if (Value && Value != UnknownAddressOrSize)
641 Result |= SymbolRef::SF_Common;
645 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
646 Result |= SymbolRef::SF_Weak;
648 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
649 Result |= SymbolRef::SF_Absolute;
654 std::error_code MachOObjectFile::getSymbolSection(DataRefImpl Symb,
655 section_iterator &Res) const {
656 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
657 uint8_t index = Entry.n_sect;
664 Res = section_iterator(SectionRef(DRI, this));
667 return object_error::success;
670 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
674 std::error_code MachOObjectFile::getSectionName(DataRefImpl Sec,
675 StringRef &Result) const {
676 ArrayRef<char> Raw = getSectionRawName(Sec);
677 Result = parseSegmentOrSectionName(Raw.data());
678 return object_error::success;
681 std::error_code MachOObjectFile::getSectionAddress(DataRefImpl Sec,
682 uint64_t &Res) const {
684 MachO::section_64 Sect = getSection64(Sec);
687 MachO::section Sect = getSection(Sec);
690 return object_error::success;
693 std::error_code MachOObjectFile::getSectionSize(DataRefImpl Sec,
694 uint64_t &Res) const {
696 MachO::section_64 Sect = getSection64(Sec);
699 MachO::section Sect = getSection(Sec);
703 return object_error::success;
706 std::error_code MachOObjectFile::getSectionContents(DataRefImpl Sec,
707 StringRef &Res) const {
712 MachO::section_64 Sect = getSection64(Sec);
713 Offset = Sect.offset;
716 MachO::section Sect = getSection(Sec);
717 Offset = Sect.offset;
721 Res = this->getData().substr(Offset, Size);
722 return object_error::success;
725 std::error_code MachOObjectFile::getSectionAlignment(DataRefImpl Sec,
726 uint64_t &Res) const {
729 MachO::section_64 Sect = getSection64(Sec);
732 MachO::section Sect = getSection(Sec);
736 Res = uint64_t(1) << Align;
737 return object_error::success;
740 std::error_code MachOObjectFile::isSectionText(DataRefImpl Sec,
742 uint32_t Flags = getSectionFlags(this, Sec);
743 Res = Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
744 return object_error::success;
747 std::error_code MachOObjectFile::isSectionData(DataRefImpl Sec,
748 bool &Result) const {
749 uint32_t Flags = getSectionFlags(this, Sec);
750 unsigned SectionType = Flags & MachO::SECTION_TYPE;
751 Result = !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
752 !(SectionType == MachO::S_ZEROFILL ||
753 SectionType == MachO::S_GB_ZEROFILL);
754 return object_error::success;
757 std::error_code MachOObjectFile::isSectionBSS(DataRefImpl Sec,
758 bool &Result) const {
759 uint32_t Flags = getSectionFlags(this, Sec);
760 unsigned SectionType = Flags & MachO::SECTION_TYPE;
761 Result = !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
762 (SectionType == MachO::S_ZEROFILL ||
763 SectionType == MachO::S_GB_ZEROFILL);
764 return object_error::success;
768 MachOObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
769 bool &Result) const {
770 // FIXME: Unimplemented.
772 return object_error::success;
775 std::error_code MachOObjectFile::isSectionVirtual(DataRefImpl Sec,
776 bool &Result) const {
777 // FIXME: Unimplemented.
779 return object_error::success;
782 std::error_code MachOObjectFile::isSectionZeroInit(DataRefImpl Sec,
784 uint32_t Flags = getSectionFlags(this, Sec);
785 unsigned SectionType = Flags & MachO::SECTION_TYPE;
786 Res = SectionType == MachO::S_ZEROFILL ||
787 SectionType == MachO::S_GB_ZEROFILL;
788 return object_error::success;
791 std::error_code MachOObjectFile::isSectionReadOnlyData(DataRefImpl Sec,
792 bool &Result) const {
793 // Consider using the code from isSectionText to look for __const sections.
794 // Alternately, emit S_ATTR_PURE_INSTRUCTIONS and/or S_ATTR_SOME_INSTRUCTIONS
795 // to use section attributes to distinguish code from data.
797 // FIXME: Unimplemented.
799 return object_error::success;
802 std::error_code MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec,
804 bool &Result) const {
806 this->getSymbolType(Symb, ST);
807 if (ST == SymbolRef::ST_Unknown) {
809 return object_error::success;
812 uint64_t SectBegin, SectEnd;
813 getSectionAddress(Sec, SectBegin);
814 getSectionSize(Sec, SectEnd);
815 SectEnd += SectBegin;
818 getSymbolAddress(Symb, SymAddr);
819 Result = (SymAddr >= SectBegin) && (SymAddr < SectEnd);
821 return object_error::success;
824 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
828 return relocation_iterator(RelocationRef(Ret, this));
832 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
835 MachO::section_64 Sect = getSection64(Sec);
838 MachO::section Sect = getSection(Sec);
845 return relocation_iterator(RelocationRef(Ret, this));
848 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
852 std::error_code MachOObjectFile::getRelocationAddress(DataRefImpl Rel,
853 uint64_t &Res) const {
855 getRelocationOffset(Rel, Offset);
860 getSectionAddress(Sec, SecAddress);
861 Res = SecAddress + Offset;
862 return object_error::success;
865 std::error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
866 uint64_t &Res) const {
867 assert(getHeader().filetype == MachO::MH_OBJECT &&
868 "Only implemented for MH_OBJECT");
869 MachO::any_relocation_info RE = getRelocation(Rel);
870 Res = getAnyRelocationAddress(RE);
871 return object_error::success;
875 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
876 MachO::any_relocation_info RE = getRelocation(Rel);
877 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
878 bool isExtern = getPlainRelocationExternal(RE);
882 MachO::symtab_command S = getSymtabLoadCommand();
883 unsigned SymbolTableEntrySize = is64Bit() ?
884 sizeof(MachO::nlist_64) :
885 sizeof(MachO::nlist);
886 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
888 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
889 return symbol_iterator(SymbolRef(Sym, this));
892 std::error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
893 uint64_t &Res) const {
894 MachO::any_relocation_info RE = getRelocation(Rel);
895 Res = getAnyRelocationType(RE);
896 return object_error::success;
900 MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
901 SmallVectorImpl<char> &Result) const {
904 getRelocationType(Rel, RType);
906 unsigned Arch = this->getArch();
910 static const char *const Table[] = {
911 "GENERIC_RELOC_VANILLA",
912 "GENERIC_RELOC_PAIR",
913 "GENERIC_RELOC_SECTDIFF",
914 "GENERIC_RELOC_PB_LA_PTR",
915 "GENERIC_RELOC_LOCAL_SECTDIFF",
916 "GENERIC_RELOC_TLV" };
924 case Triple::x86_64: {
925 static const char *const Table[] = {
926 "X86_64_RELOC_UNSIGNED",
927 "X86_64_RELOC_SIGNED",
928 "X86_64_RELOC_BRANCH",
929 "X86_64_RELOC_GOT_LOAD",
931 "X86_64_RELOC_SUBTRACTOR",
932 "X86_64_RELOC_SIGNED_1",
933 "X86_64_RELOC_SIGNED_2",
934 "X86_64_RELOC_SIGNED_4",
935 "X86_64_RELOC_TLV" };
944 static const char *const Table[] = {
947 "ARM_RELOC_SECTDIFF",
948 "ARM_RELOC_LOCAL_SECTDIFF",
949 "ARM_RELOC_PB_LA_PTR",
951 "ARM_THUMB_RELOC_BR22",
952 "ARM_THUMB_32BIT_BRANCH",
954 "ARM_RELOC_HALF_SECTDIFF" };
963 case Triple::aarch64: {
964 static const char *const Table[] = {
965 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
966 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
967 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
968 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
969 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
973 if (RType >= array_lengthof(Table))
980 static const char *const Table[] = {
989 "PPC_RELOC_SECTDIFF",
990 "PPC_RELOC_PB_LA_PTR",
991 "PPC_RELOC_HI16_SECTDIFF",
992 "PPC_RELOC_LO16_SECTDIFF",
993 "PPC_RELOC_HA16_SECTDIFF",
995 "PPC_RELOC_LO14_SECTDIFF",
996 "PPC_RELOC_LOCAL_SECTDIFF" };
1004 case Triple::UnknownArch:
1008 Result.append(res.begin(), res.end());
1009 return object_error::success;
1013 MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
1014 SmallVectorImpl<char> &Result) const {
1015 MachO::any_relocation_info RE = getRelocation(Rel);
1017 unsigned Arch = this->getArch();
1020 raw_string_ostream fmt(fmtbuf);
1021 unsigned Type = this->getAnyRelocationType(RE);
1022 bool IsPCRel = this->getAnyRelocationPCRel(RE);
1024 // Determine any addends that should be displayed with the relocation.
1025 // These require decoding the relocation type, which is triple-specific.
1027 // X86_64 has entirely custom relocation types.
1028 if (Arch == Triple::x86_64) {
1029 bool isPCRel = getAnyRelocationPCRel(RE);
1032 case MachO::X86_64_RELOC_GOT_LOAD:
1033 case MachO::X86_64_RELOC_GOT: {
1034 printRelocationTargetName(this, RE, fmt);
1036 if (isPCRel) fmt << "PCREL";
1039 case MachO::X86_64_RELOC_SUBTRACTOR: {
1040 DataRefImpl RelNext = Rel;
1041 moveRelocationNext(RelNext);
1042 MachO::any_relocation_info RENext = getRelocation(RelNext);
1044 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
1045 // X86_64_RELOC_UNSIGNED.
1046 // NOTE: Scattered relocations don't exist on x86_64.
1047 unsigned RType = getAnyRelocationType(RENext);
1048 if (RType != MachO::X86_64_RELOC_UNSIGNED)
1049 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
1050 "X86_64_RELOC_SUBTRACTOR.");
1052 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
1053 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
1054 printRelocationTargetName(this, RENext, fmt);
1056 printRelocationTargetName(this, RE, fmt);
1059 case MachO::X86_64_RELOC_TLV:
1060 printRelocationTargetName(this, RE, fmt);
1062 if (isPCRel) fmt << "P";
1064 case MachO::X86_64_RELOC_SIGNED_1:
1065 printRelocationTargetName(this, RE, fmt);
1068 case MachO::X86_64_RELOC_SIGNED_2:
1069 printRelocationTargetName(this, RE, fmt);
1072 case MachO::X86_64_RELOC_SIGNED_4:
1073 printRelocationTargetName(this, RE, fmt);
1077 printRelocationTargetName(this, RE, fmt);
1080 // X86 and ARM share some relocation types in common.
1081 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
1082 Arch == Triple::ppc) {
1083 // Generic relocation types...
1085 case MachO::GENERIC_RELOC_PAIR: // prints no info
1086 return object_error::success;
1087 case MachO::GENERIC_RELOC_SECTDIFF: {
1088 DataRefImpl RelNext = Rel;
1089 moveRelocationNext(RelNext);
1090 MachO::any_relocation_info RENext = getRelocation(RelNext);
1092 // X86 sect diff's must be followed by a relocation of type
1093 // GENERIC_RELOC_PAIR.
1094 unsigned RType = getAnyRelocationType(RENext);
1096 if (RType != MachO::GENERIC_RELOC_PAIR)
1097 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1098 "GENERIC_RELOC_SECTDIFF.");
1100 printRelocationTargetName(this, RE, fmt);
1102 printRelocationTargetName(this, RENext, fmt);
1107 if (Arch == Triple::x86 || Arch == Triple::ppc) {
1109 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1110 DataRefImpl RelNext = Rel;
1111 moveRelocationNext(RelNext);
1112 MachO::any_relocation_info RENext = getRelocation(RelNext);
1114 // X86 sect diff's must be followed by a relocation of type
1115 // GENERIC_RELOC_PAIR.
1116 unsigned RType = getAnyRelocationType(RENext);
1117 if (RType != MachO::GENERIC_RELOC_PAIR)
1118 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1119 "GENERIC_RELOC_LOCAL_SECTDIFF.");
1121 printRelocationTargetName(this, RE, fmt);
1123 printRelocationTargetName(this, RENext, fmt);
1126 case MachO::GENERIC_RELOC_TLV: {
1127 printRelocationTargetName(this, RE, fmt);
1129 if (IsPCRel) fmt << "P";
1133 printRelocationTargetName(this, RE, fmt);
1135 } else { // ARM-specific relocations
1137 case MachO::ARM_RELOC_HALF:
1138 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1139 // Half relocations steal a bit from the length field to encode
1140 // whether this is an upper16 or a lower16 relocation.
1141 bool isUpper = getAnyRelocationLength(RE) >> 1;
1144 fmt << ":upper16:(";
1146 fmt << ":lower16:(";
1147 printRelocationTargetName(this, RE, fmt);
1149 DataRefImpl RelNext = Rel;
1150 moveRelocationNext(RelNext);
1151 MachO::any_relocation_info RENext = getRelocation(RelNext);
1153 // ARM half relocs must be followed by a relocation of type
1155 unsigned RType = getAnyRelocationType(RENext);
1156 if (RType != MachO::ARM_RELOC_PAIR)
1157 report_fatal_error("Expected ARM_RELOC_PAIR after "
1160 // NOTE: The half of the target virtual address is stashed in the
1161 // address field of the secondary relocation, but we can't reverse
1162 // engineer the constant offset from it without decoding the movw/movt
1163 // instruction to find the other half in its immediate field.
1165 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1166 // symbol/section pointer of the follow-on relocation.
1167 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1169 printRelocationTargetName(this, RENext, fmt);
1176 printRelocationTargetName(this, RE, fmt);
1181 printRelocationTargetName(this, RE, fmt);
1184 Result.append(fmtbuf.begin(), fmtbuf.end());
1185 return object_error::success;
1188 std::error_code MachOObjectFile::getRelocationHidden(DataRefImpl Rel,
1189 bool &Result) const {
1190 unsigned Arch = getArch();
1192 getRelocationType(Rel, Type);
1196 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1197 // is always hidden.
1198 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1199 if (Type == MachO::GENERIC_RELOC_PAIR) Result = true;
1200 } else if (Arch == Triple::x86_64) {
1201 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1202 // an X86_64_RELOC_SUBTRACTOR.
1203 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1204 DataRefImpl RelPrev = Rel;
1207 getRelocationType(RelPrev, PrevType);
1208 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1213 return object_error::success;
1216 std::error_code MachOObjectFile::getLibraryNext(DataRefImpl LibData,
1217 LibraryRef &Res) const {
1218 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1221 std::error_code MachOObjectFile::getLibraryPath(DataRefImpl LibData,
1222 StringRef &Res) const {
1223 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1227 // guessLibraryShortName() is passed a name of a dynamic library and returns a
1228 // guess on what the short name is. Then name is returned as a substring of the
1229 // StringRef Name passed in. The name of the dynamic library is recognized as
1230 // a framework if it has one of the two following forms:
1231 // Foo.framework/Versions/A/Foo
1232 // Foo.framework/Foo
1233 // Where A and Foo can be any string. And may contain a trailing suffix
1234 // starting with an underbar. If the Name is recognized as a framework then
1235 // isFramework is set to true else it is set to false. If the Name has a
1236 // suffix then Suffix is set to the substring in Name that contains the suffix
1237 // else it is set to a NULL StringRef.
1239 // The Name of the dynamic library is recognized as a library name if it has
1240 // one of the two following forms:
1243 // The library may have a suffix trailing the name Foo of the form:
1244 // libFoo_profile.A.dylib
1245 // libFoo_profile.dylib
1247 // The Name of the dynamic library is also recognized as a library name if it
1248 // has the following form:
1251 // If the Name of the dynamic library is none of the forms above then a NULL
1252 // StringRef is returned.
1254 StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
1256 StringRef &Suffix) {
1257 StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
1258 size_t a, b, c, d, Idx;
1260 isFramework = false;
1261 Suffix = StringRef();
1263 // Pull off the last component and make Foo point to it
1264 a = Name.rfind('/');
1265 if (a == Name.npos || a == 0)
1267 Foo = Name.slice(a+1, Name.npos);
1269 // Look for a suffix starting with a '_'
1270 Idx = Foo.rfind('_');
1271 if (Idx != Foo.npos && Foo.size() >= 2) {
1272 Suffix = Foo.slice(Idx, Foo.npos);
1273 Foo = Foo.slice(0, Idx);
1276 // First look for the form Foo.framework/Foo
1277 b = Name.rfind('/', a);
1282 F = Name.slice(Idx, Idx + Foo.size());
1283 DotFramework = Name.slice(Idx + Foo.size(),
1284 Idx + Foo.size() + sizeof(".framework/")-1);
1285 if (F == Foo && DotFramework == ".framework/") {
1290 // Next look for the form Foo.framework/Versions/A/Foo
1293 c = Name.rfind('/', b);
1294 if (c == Name.npos || c == 0)
1296 V = Name.slice(c+1, Name.npos);
1297 if (!V.startswith("Versions/"))
1299 d = Name.rfind('/', c);
1304 F = Name.slice(Idx, Idx + Foo.size());
1305 DotFramework = Name.slice(Idx + Foo.size(),
1306 Idx + Foo.size() + sizeof(".framework/")-1);
1307 if (F == Foo && DotFramework == ".framework/") {
1313 // pull off the suffix after the "." and make a point to it
1314 a = Name.rfind('.');
1315 if (a == Name.npos || a == 0)
1317 Dylib = Name.slice(a, Name.npos);
1318 if (Dylib != ".dylib")
1321 // First pull off the version letter for the form Foo.A.dylib if any.
1323 Dot = Name.slice(a-2, a-1);
1328 b = Name.rfind('/', a);
1333 // ignore any suffix after an underbar like Foo_profile.A.dylib
1334 Idx = Name.find('_', b);
1335 if (Idx != Name.npos && Idx != b) {
1336 Lib = Name.slice(b, Idx);
1337 Suffix = Name.slice(Idx, a);
1340 Lib = Name.slice(b, a);
1341 // There are incorrect library names of the form:
1342 // libATS.A_profile.dylib so check for these.
1343 if (Lib.size() >= 3) {
1344 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
1346 Lib = Lib.slice(0, Lib.size()-2);
1351 Qtx = Name.slice(a, Name.npos);
1354 b = Name.rfind('/', a);
1356 Lib = Name.slice(0, a);
1358 Lib = Name.slice(b+1, a);
1359 // There are library names of the form: QT.A.qtx so check for these.
1360 if (Lib.size() >= 3) {
1361 Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
1363 Lib = Lib.slice(0, Lib.size()-2);
1368 // getLibraryShortNameByIndex() is used to get the short name of the library
1369 // for an undefined symbol in a linked Mach-O binary that was linked with the
1370 // normal two-level namespace default (that is MH_TWOLEVEL in the header).
1371 // It is passed the index (0 - based) of the library as translated from
1372 // GET_LIBRARY_ORDINAL (1 - based).
1373 std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
1375 if (Index >= Libraries.size())
1376 return object_error::parse_failed;
1378 MachO::dylib_command D =
1379 getStruct<MachO::dylib_command>(this, Libraries[Index]);
1380 if (D.dylib.name >= D.cmdsize)
1381 return object_error::parse_failed;
1383 // If the cache of LibrariesShortNames is not built up do that first for
1384 // all the Libraries.
1385 if (LibrariesShortNames.size() == 0) {
1386 for (unsigned i = 0; i < Libraries.size(); i++) {
1387 MachO::dylib_command D =
1388 getStruct<MachO::dylib_command>(this, Libraries[i]);
1389 if (D.dylib.name >= D.cmdsize) {
1390 LibrariesShortNames.push_back(StringRef());
1393 char *P = (char *)(Libraries[i]) + D.dylib.name;
1394 StringRef Name = StringRef(P);
1397 StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
1398 if (shortName == StringRef())
1399 LibrariesShortNames.push_back(Name);
1401 LibrariesShortNames.push_back(shortName);
1405 Res = LibrariesShortNames[Index];
1406 return object_error::success;
1409 basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
1410 return getSymbolByIndex(0);
1413 basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
1416 return basic_symbol_iterator(SymbolRef(DRI, this));
1418 MachO::symtab_command Symtab = getSymtabLoadCommand();
1419 unsigned SymbolTableEntrySize = is64Bit() ?
1420 sizeof(MachO::nlist_64) :
1421 sizeof(MachO::nlist);
1422 unsigned Offset = Symtab.symoff +
1423 Symtab.nsyms * SymbolTableEntrySize;
1424 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1425 return basic_symbol_iterator(SymbolRef(DRI, this));
1428 basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
1431 return basic_symbol_iterator(SymbolRef(DRI, this));
1433 MachO::symtab_command Symtab = getSymtabLoadCommand();
1434 assert(Index < Symtab.nsyms && "Requested symbol index is out of range.");
1435 unsigned SymbolTableEntrySize =
1436 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
1437 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1438 DRI.p += Index * SymbolTableEntrySize;
1439 return basic_symbol_iterator(SymbolRef(DRI, this));
1442 section_iterator MachOObjectFile::section_begin() const {
1444 return section_iterator(SectionRef(DRI, this));
1447 section_iterator MachOObjectFile::section_end() const {
1449 DRI.d.a = Sections.size();
1450 return section_iterator(SectionRef(DRI, this));
1453 library_iterator MachOObjectFile::needed_library_begin() const {
1455 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1458 library_iterator MachOObjectFile::needed_library_end() const {
1460 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1463 uint8_t MachOObjectFile::getBytesInAddress() const {
1464 return is64Bit() ? 8 : 4;
1467 StringRef MachOObjectFile::getFileFormatName() const {
1468 unsigned CPUType = getCPUType(this);
1471 case llvm::MachO::CPU_TYPE_I386:
1472 return "Mach-O 32-bit i386";
1473 case llvm::MachO::CPU_TYPE_ARM:
1474 return "Mach-O arm";
1475 case llvm::MachO::CPU_TYPE_POWERPC:
1476 return "Mach-O 32-bit ppc";
1478 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64) == 0 &&
1479 "64-bit object file when we're not 64-bit?");
1480 return "Mach-O 32-bit unknown";
1484 // Make sure the cpu type has the correct mask.
1485 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64)
1486 == llvm::MachO::CPU_ARCH_ABI64 &&
1487 "32-bit object file when we're 64-bit?");
1490 case llvm::MachO::CPU_TYPE_X86_64:
1491 return "Mach-O 64-bit x86-64";
1492 case llvm::MachO::CPU_TYPE_ARM64:
1493 return "Mach-O arm64";
1494 case llvm::MachO::CPU_TYPE_POWERPC64:
1495 return "Mach-O 64-bit ppc64";
1497 return "Mach-O 64-bit unknown";
1501 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1503 case llvm::MachO::CPU_TYPE_I386:
1505 case llvm::MachO::CPU_TYPE_X86_64:
1506 return Triple::x86_64;
1507 case llvm::MachO::CPU_TYPE_ARM:
1509 case llvm::MachO::CPU_TYPE_ARM64:
1510 return Triple::arm64;
1511 case llvm::MachO::CPU_TYPE_POWERPC:
1513 case llvm::MachO::CPU_TYPE_POWERPC64:
1514 return Triple::ppc64;
1516 return Triple::UnknownArch;
1520 unsigned MachOObjectFile::getArch() const {
1521 return getArch(getCPUType(this));
1524 StringRef MachOObjectFile::getLoadName() const {
1526 report_fatal_error("get_load_name() unimplemented in MachOObjectFile");
1529 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
1532 return section_rel_begin(DRI);
1535 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
1538 return section_rel_end(DRI);
1541 dice_iterator MachOObjectFile::begin_dices() const {
1543 if (!DataInCodeLoadCmd)
1544 return dice_iterator(DiceRef(DRI, this));
1546 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1547 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
1548 return dice_iterator(DiceRef(DRI, this));
1551 dice_iterator MachOObjectFile::end_dices() const {
1553 if (!DataInCodeLoadCmd)
1554 return dice_iterator(DiceRef(DRI, this));
1556 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1557 unsigned Offset = DicLC.dataoff + DicLC.datasize;
1558 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1559 return dice_iterator(DiceRef(DRI, this));
1563 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1564 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1565 return parseSegmentOrSectionName(Raw.data());
1569 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
1570 const section_base *Base =
1571 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1572 return ArrayRef<char>(Base->sectname);
1576 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
1577 const section_base *Base =
1578 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1579 return ArrayRef<char>(Base->segname);
1583 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
1585 if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
1587 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
1590 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
1591 const MachO::any_relocation_info &RE) const {
1592 if (isLittleEndian())
1593 return RE.r_word1 & 0xffffff;
1594 return RE.r_word1 >> 8;
1597 bool MachOObjectFile::getPlainRelocationExternal(
1598 const MachO::any_relocation_info &RE) const {
1599 if (isLittleEndian())
1600 return (RE.r_word1 >> 27) & 1;
1601 return (RE.r_word1 >> 4) & 1;
1604 bool MachOObjectFile::getScatteredRelocationScattered(
1605 const MachO::any_relocation_info &RE) const {
1606 return RE.r_word0 >> 31;
1609 uint32_t MachOObjectFile::getScatteredRelocationValue(
1610 const MachO::any_relocation_info &RE) const {
1614 unsigned MachOObjectFile::getAnyRelocationAddress(
1615 const MachO::any_relocation_info &RE) const {
1616 if (isRelocationScattered(RE))
1617 return getScatteredRelocationAddress(RE);
1618 return getPlainRelocationAddress(RE);
1621 unsigned MachOObjectFile::getAnyRelocationPCRel(
1622 const MachO::any_relocation_info &RE) const {
1623 if (isRelocationScattered(RE))
1624 return getScatteredRelocationPCRel(this, RE);
1625 return getPlainRelocationPCRel(this, RE);
1628 unsigned MachOObjectFile::getAnyRelocationLength(
1629 const MachO::any_relocation_info &RE) const {
1630 if (isRelocationScattered(RE))
1631 return getScatteredRelocationLength(RE);
1632 return getPlainRelocationLength(this, RE);
1636 MachOObjectFile::getAnyRelocationType(
1637 const MachO::any_relocation_info &RE) const {
1638 if (isRelocationScattered(RE))
1639 return getScatteredRelocationType(RE);
1640 return getPlainRelocationType(this, RE);
1644 MachOObjectFile::getRelocationSection(
1645 const MachO::any_relocation_info &RE) const {
1646 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
1647 return *section_end();
1648 unsigned SecNum = getPlainRelocationSymbolNum(RE) - 1;
1651 return SectionRef(DRI, this);
1654 MachOObjectFile::LoadCommandInfo
1655 MachOObjectFile::getFirstLoadCommandInfo() const {
1656 MachOObjectFile::LoadCommandInfo Load;
1658 unsigned HeaderSize = is64Bit() ? sizeof(MachO::mach_header_64) :
1659 sizeof(MachO::mach_header);
1660 Load.Ptr = getPtr(this, HeaderSize);
1661 Load.C = getStruct<MachO::load_command>(this, Load.Ptr);
1665 MachOObjectFile::LoadCommandInfo
1666 MachOObjectFile::getNextLoadCommandInfo(const LoadCommandInfo &L) const {
1667 MachOObjectFile::LoadCommandInfo Next;
1668 Next.Ptr = L.Ptr + L.C.cmdsize;
1669 Next.C = getStruct<MachO::load_command>(this, Next.Ptr);
1673 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
1674 return getStruct<MachO::section>(this, Sections[DRI.d.a]);
1677 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
1678 return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
1681 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
1682 unsigned Index) const {
1683 const char *Sec = getSectionPtr(this, L, Index);
1684 return getStruct<MachO::section>(this, Sec);
1687 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
1688 unsigned Index) const {
1689 const char *Sec = getSectionPtr(this, L, Index);
1690 return getStruct<MachO::section_64>(this, Sec);
1694 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
1695 const char *P = reinterpret_cast<const char *>(DRI.p);
1696 return getStruct<MachO::nlist>(this, P);
1700 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
1701 const char *P = reinterpret_cast<const char *>(DRI.p);
1702 return getStruct<MachO::nlist_64>(this, P);
1705 MachO::linkedit_data_command
1706 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
1707 return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
1710 MachO::segment_command
1711 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
1712 return getStruct<MachO::segment_command>(this, L.Ptr);
1715 MachO::segment_command_64
1716 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
1717 return getStruct<MachO::segment_command_64>(this, L.Ptr);
1720 MachO::linker_options_command
1721 MachOObjectFile::getLinkerOptionsLoadCommand(const LoadCommandInfo &L) const {
1722 return getStruct<MachO::linker_options_command>(this, L.Ptr);
1725 MachO::version_min_command
1726 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
1727 return getStruct<MachO::version_min_command>(this, L.Ptr);
1730 MachO::any_relocation_info
1731 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
1736 MachO::section_64 Sect = getSection64(Sec);
1737 Offset = Sect.reloff;
1739 MachO::section Sect = getSection(Sec);
1740 Offset = Sect.reloff;
1743 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
1744 getPtr(this, Offset)) + Rel.d.b;
1745 return getStruct<MachO::any_relocation_info>(
1746 this, reinterpret_cast<const char *>(P));
1749 MachO::data_in_code_entry
1750 MachOObjectFile::getDice(DataRefImpl Rel) const {
1751 const char *P = reinterpret_cast<const char *>(Rel.p);
1752 return getStruct<MachO::data_in_code_entry>(this, P);
1755 MachO::mach_header MachOObjectFile::getHeader() const {
1756 return getStruct<MachO::mach_header>(this, getPtr(this, 0));
1759 MachO::mach_header_64 MachOObjectFile::getHeader64() const {
1760 return getStruct<MachO::mach_header_64>(this, getPtr(this, 0));
1763 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
1764 const MachO::dysymtab_command &DLC,
1765 unsigned Index) const {
1766 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
1767 return getStruct<uint32_t>(this, getPtr(this, Offset));
1770 MachO::data_in_code_entry
1771 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
1772 unsigned Index) const {
1773 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
1774 return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
1777 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
1778 return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
1781 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
1782 return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
1785 MachO::linkedit_data_command
1786 MachOObjectFile::getDataInCodeLoadCommand() const {
1787 if (DataInCodeLoadCmd)
1788 return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
1790 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
1791 MachO::linkedit_data_command Cmd;
1792 Cmd.cmd = MachO::LC_DATA_IN_CODE;
1793 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
1799 StringRef MachOObjectFile::getStringTableData() const {
1800 MachO::symtab_command S = getSymtabLoadCommand();
1801 return getData().substr(S.stroff, S.strsize);
1804 bool MachOObjectFile::is64Bit() const {
1805 return getType() == getMachOType(false, true) ||
1806 getType() == getMachOType(true, true);
1809 void MachOObjectFile::ReadULEB128s(uint64_t Index,
1810 SmallVectorImpl<uint64_t> &Out) const {
1811 DataExtractor extractor(ObjectFile::getData(), true, 0);
1813 uint32_t offset = Index;
1815 while (uint64_t delta = extractor.getULEB128(&offset)) {
1817 Out.push_back(data);
1821 ErrorOr<ObjectFile *> ObjectFile::createMachOObjectFile(MemoryBuffer *Buffer,
1823 StringRef Magic = Buffer->getBuffer().slice(0, 4);
1825 std::unique_ptr<MachOObjectFile> Ret;
1826 if (Magic == "\xFE\xED\xFA\xCE")
1827 Ret.reset(new MachOObjectFile(Buffer, false, false, EC, BufferOwned));
1828 else if (Magic == "\xCE\xFA\xED\xFE")
1829 Ret.reset(new MachOObjectFile(Buffer, true, false, EC, BufferOwned));
1830 else if (Magic == "\xFE\xED\xFA\xCF")
1831 Ret.reset(new MachOObjectFile(Buffer, false, true, EC, BufferOwned));
1832 else if (Magic == "\xCF\xFA\xED\xFE")
1833 Ret.reset(new MachOObjectFile(Buffer, true, true, EC, BufferOwned));
1836 return object_error::parse_failed;
1841 return Ret.release();
1844 } // end namespace object
1845 } // end namespace llvm