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;
46 static void SwapValue(T &Value) {
47 Value = sys::SwapByteOrder(Value);
51 static void SwapStruct(T &Value);
54 void SwapStruct(MachO::any_relocation_info &H) {
60 void SwapStruct(MachO::load_command &L) {
66 void SwapStruct(nlist_base &S) {
72 void SwapStruct(MachO::section &S) {
80 SwapValue(S.reserved1);
81 SwapValue(S.reserved2);
85 void SwapStruct(MachO::section_64 &S) {
93 SwapValue(S.reserved1);
94 SwapValue(S.reserved2);
95 SwapValue(S.reserved3);
99 void SwapStruct(MachO::nlist &S) {
102 SwapValue(S.n_value);
106 void SwapStruct(MachO::nlist_64 &S) {
109 SwapValue(S.n_value);
113 void SwapStruct(MachO::mach_header &H) {
115 SwapValue(H.cputype);
116 SwapValue(H.cpusubtype);
117 SwapValue(H.filetype);
119 SwapValue(H.sizeofcmds);
124 void SwapStruct(MachO::mach_header_64 &H) {
126 SwapValue(H.cputype);
127 SwapValue(H.cpusubtype);
128 SwapValue(H.filetype);
130 SwapValue(H.sizeofcmds);
132 SwapValue(H.reserved);
136 void SwapStruct(MachO::symtab_command &C) {
138 SwapValue(C.cmdsize);
142 SwapValue(C.strsize);
146 void SwapStruct(MachO::dysymtab_command &C) {
148 SwapValue(C.cmdsize);
149 SwapValue(C.ilocalsym);
150 SwapValue(C.nlocalsym);
151 SwapValue(C.iextdefsym);
152 SwapValue(C.nextdefsym);
153 SwapValue(C.iundefsym);
154 SwapValue(C.nundefsym);
157 SwapValue(C.modtaboff);
158 SwapValue(C.nmodtab);
159 SwapValue(C.extrefsymoff);
160 SwapValue(C.nextrefsyms);
161 SwapValue(C.indirectsymoff);
162 SwapValue(C.nindirectsyms);
163 SwapValue(C.extreloff);
164 SwapValue(C.nextrel);
165 SwapValue(C.locreloff);
166 SwapValue(C.nlocrel);
170 void SwapStruct(MachO::linkedit_data_command &C) {
172 SwapValue(C.cmdsize);
173 SwapValue(C.dataoff);
174 SwapValue(C.datasize);
178 void SwapStruct(MachO::segment_command &C) {
180 SwapValue(C.cmdsize);
183 SwapValue(C.fileoff);
184 SwapValue(C.filesize);
185 SwapValue(C.maxprot);
186 SwapValue(C.initprot);
192 void SwapStruct(MachO::segment_command_64 &C) {
194 SwapValue(C.cmdsize);
197 SwapValue(C.fileoff);
198 SwapValue(C.filesize);
199 SwapValue(C.maxprot);
200 SwapValue(C.initprot);
206 void SwapStruct(uint32_t &C) {
211 void SwapStruct(MachO::linker_options_command &C) {
213 SwapValue(C.cmdsize);
218 void SwapStruct(MachO::version_min_command&C) {
220 SwapValue(C.cmdsize);
221 SwapValue(C.version);
222 SwapValue(C.reserved);
226 void SwapStruct(MachO::data_in_code_entry &C) {
233 T getStruct(const MachOObjectFile *O, const char *P) {
235 memcpy(&Cmd, P, sizeof(T));
236 if (O->isLittleEndian() != sys::IsLittleEndianHost)
242 getSegmentLoadCommandNumSections(const MachOObjectFile *O,
243 const MachOObjectFile::LoadCommandInfo &L) {
245 MachO::segment_command_64 S = O->getSegment64LoadCommand(L);
248 MachO::segment_command S = O->getSegmentLoadCommand(L);
253 getSectionPtr(const MachOObjectFile *O, MachOObjectFile::LoadCommandInfo L,
255 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
257 bool Is64 = O->is64Bit();
258 unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
259 sizeof(MachO::segment_command);
260 unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
261 sizeof(MachO::section);
263 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
264 return reinterpret_cast<const char*>(SectionAddr);
267 static const char *getPtr(const MachOObjectFile *O, size_t Offset) {
268 return O->getData().substr(Offset, 1).data();
272 getSymbolTableEntryBase(const MachOObjectFile *O, DataRefImpl DRI) {
273 const char *P = reinterpret_cast<const char *>(DRI.p);
274 return getStruct<nlist_base>(O, P);
277 static StringRef parseSegmentOrSectionName(const char *P) {
281 // Not null terminated, so this is a 16 char string.
282 return StringRef(P, 16);
285 // Helper to advance a section or symbol iterator multiple increments at a time.
287 static void advance(T &it, size_t Val) {
292 static unsigned getCPUType(const MachOObjectFile *O) {
293 return O->getHeader().cputype;
296 static void printRelocationTargetName(const MachOObjectFile *O,
297 const MachO::any_relocation_info &RE,
298 raw_string_ostream &fmt) {
299 bool IsScattered = O->isRelocationScattered(RE);
301 // Target of a scattered relocation is an address. In the interest of
302 // generating pretty output, scan through the symbol table looking for a
303 // symbol that aligns with that address. If we find one, print it.
304 // Otherwise, we just print the hex address of the target.
306 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
308 for (const SymbolRef &Symbol : O->symbols()) {
313 if ((ec = Symbol.getAddress(Addr)))
314 report_fatal_error(ec.message());
317 if ((ec = Symbol.getName(Name)))
318 report_fatal_error(ec.message());
323 // If we couldn't find a symbol that this relocation refers to, try
324 // to find a section beginning instead.
325 for (const SectionRef &Section : O->sections()) {
330 if ((ec = Section.getAddress(Addr)))
331 report_fatal_error(ec.message());
334 if ((ec = Section.getName(Name)))
335 report_fatal_error(ec.message());
340 fmt << format("0x%x", Val);
345 bool isExtern = O->getPlainRelocationExternal(RE);
346 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
349 symbol_iterator SI = O->symbol_begin();
353 section_iterator SI = O->section_begin();
354 // Adjust for the fact that sections are 1-indexed.
355 advance(SI, Val - 1);
363 getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
368 getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
369 return RE.r_word0 & 0xffffff;
372 static bool getPlainRelocationPCRel(const MachOObjectFile *O,
373 const MachO::any_relocation_info &RE) {
374 if (O->isLittleEndian())
375 return (RE.r_word1 >> 24) & 1;
376 return (RE.r_word1 >> 7) & 1;
380 getScatteredRelocationPCRel(const MachOObjectFile *O,
381 const MachO::any_relocation_info &RE) {
382 return (RE.r_word0 >> 30) & 1;
385 static unsigned getPlainRelocationLength(const MachOObjectFile *O,
386 const MachO::any_relocation_info &RE) {
387 if (O->isLittleEndian())
388 return (RE.r_word1 >> 25) & 3;
389 return (RE.r_word1 >> 5) & 3;
393 getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
394 return (RE.r_word0 >> 28) & 3;
397 static unsigned getPlainRelocationType(const MachOObjectFile *O,
398 const MachO::any_relocation_info &RE) {
399 if (O->isLittleEndian())
400 return RE.r_word1 >> 28;
401 return RE.r_word1 & 0xf;
405 getScatteredRelocationType(const MachO::any_relocation_info &RE) {
406 return (RE.r_word0 >> 24) & 0xf;
409 static uint32_t getSectionFlags(const MachOObjectFile *O,
412 MachO::section_64 Sect = O->getSection64(Sec);
415 MachO::section Sect = O->getSection(Sec);
419 MachOObjectFile::MachOObjectFile(MemoryBuffer *Object, bool IsLittleEndian,
420 bool Is64bits, error_code &EC,
422 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object, BufferOwned),
423 SymtabLoadCmd(nullptr), DysymtabLoadCmd(nullptr),
424 DataInCodeLoadCmd(nullptr) {
425 uint32_t LoadCommandCount = this->getHeader().ncmds;
426 MachO::LoadCommandType SegmentLoadType = is64Bit() ?
427 MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT;
429 MachOObjectFile::LoadCommandInfo Load = getFirstLoadCommandInfo();
430 for (unsigned I = 0; ; ++I) {
431 if (Load.C.cmd == MachO::LC_SYMTAB) {
432 assert(!SymtabLoadCmd && "Multiple symbol tables");
433 SymtabLoadCmd = Load.Ptr;
434 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
435 assert(!DysymtabLoadCmd && "Multiple dynamic symbol tables");
436 DysymtabLoadCmd = Load.Ptr;
437 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
438 assert(!DataInCodeLoadCmd && "Multiple data in code tables");
439 DataInCodeLoadCmd = Load.Ptr;
440 } else if (Load.C.cmd == SegmentLoadType) {
441 uint32_t NumSections = getSegmentLoadCommandNumSections(this, Load);
442 for (unsigned J = 0; J < NumSections; ++J) {
443 const char *Sec = getSectionPtr(this, Load, J);
444 Sections.push_back(Sec);
448 if (I == LoadCommandCount - 1)
451 Load = getNextLoadCommandInfo(Load);
455 void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
456 unsigned SymbolTableEntrySize = is64Bit() ?
457 sizeof(MachO::nlist_64) :
458 sizeof(MachO::nlist);
459 Symb.p += SymbolTableEntrySize;
462 error_code MachOObjectFile::getSymbolName(DataRefImpl Symb,
463 StringRef &Res) const {
464 StringRef StringTable = getStringTableData();
465 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
466 const char *Start = &StringTable.data()[Entry.n_strx];
467 Res = StringRef(Start);
468 return object_error::success;
471 error_code MachOObjectFile::getSymbolAddress(DataRefImpl Symb,
472 uint64_t &Res) const {
474 MachO::nlist_64 Entry = getSymbol64TableEntry(Symb);
477 MachO::nlist Entry = getSymbolTableEntry(Symb);
480 return object_error::success;
483 error_code MachOObjectFile::getSymbolAlignment(DataRefImpl DRI,
484 uint32_t &Result) const {
485 uint32_t flags = getSymbolFlags(DRI);
486 if (flags & SymbolRef::SF_Common) {
487 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
488 Result = 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
492 return object_error::success;
495 error_code MachOObjectFile::getSymbolSize(DataRefImpl DRI,
496 uint64_t &Result) const {
497 uint64_t BeginOffset;
498 uint64_t EndOffset = 0;
499 uint8_t SectionIndex;
501 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
503 getSymbolAddress(DRI, Value);
507 SectionIndex = Entry.n_sect;
509 uint32_t flags = getSymbolFlags(DRI);
510 if (flags & SymbolRef::SF_Common)
513 Result = UnknownAddressOrSize;
514 return object_error::success;
516 // Unfortunately symbols are unsorted so we need to touch all
517 // symbols from load command
518 for (const SymbolRef &Symbol : symbols()) {
519 DataRefImpl DRI = Symbol.getRawDataRefImpl();
520 Entry = getSymbolTableEntryBase(this, DRI);
521 getSymbolAddress(DRI, Value);
522 if (Entry.n_sect == SectionIndex && Value > BeginOffset)
523 if (!EndOffset || Value < EndOffset)
529 Sec.d.a = SectionIndex-1;
530 getSectionSize(Sec, Size);
531 getSectionAddress(Sec, EndOffset);
534 Result = EndOffset - BeginOffset;
535 return object_error::success;
538 error_code MachOObjectFile::getSymbolType(DataRefImpl Symb,
539 SymbolRef::Type &Res) const {
540 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
541 uint8_t n_type = Entry.n_type;
543 Res = SymbolRef::ST_Other;
545 // If this is a STAB debugging symbol, we can do nothing more.
546 if (n_type & MachO::N_STAB) {
547 Res = SymbolRef::ST_Debug;
548 return object_error::success;
551 switch (n_type & MachO::N_TYPE) {
553 Res = SymbolRef::ST_Unknown;
556 Res = SymbolRef::ST_Function;
559 return object_error::success;
562 uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
563 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
565 uint8_t MachOType = Entry.n_type;
566 uint16_t MachOFlags = Entry.n_desc;
568 uint32_t Result = SymbolRef::SF_None;
570 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF)
571 Result |= SymbolRef::SF_Undefined;
573 if (MachOType & MachO::N_STAB)
574 Result |= SymbolRef::SF_FormatSpecific;
576 if (MachOType & MachO::N_EXT) {
577 Result |= SymbolRef::SF_Global;
578 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
580 getSymbolAddress(DRI, Value);
582 Result |= SymbolRef::SF_Common;
586 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
587 Result |= SymbolRef::SF_Weak;
589 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
590 Result |= SymbolRef::SF_Absolute;
596 MachOObjectFile::getSymbolSection(DataRefImpl Symb,
597 section_iterator &Res) const {
598 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
599 uint8_t index = Entry.n_sect;
606 Res = section_iterator(SectionRef(DRI, this));
609 return object_error::success;
612 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
617 MachOObjectFile::getSectionName(DataRefImpl Sec, StringRef &Result) const {
618 ArrayRef<char> Raw = getSectionRawName(Sec);
619 Result = parseSegmentOrSectionName(Raw.data());
620 return object_error::success;
624 MachOObjectFile::getSectionAddress(DataRefImpl Sec, uint64_t &Res) const {
626 MachO::section_64 Sect = getSection64(Sec);
629 MachO::section Sect = getSection(Sec);
632 return object_error::success;
636 MachOObjectFile::getSectionSize(DataRefImpl Sec, uint64_t &Res) const {
638 MachO::section_64 Sect = getSection64(Sec);
641 MachO::section Sect = getSection(Sec);
645 return object_error::success;
649 MachOObjectFile::getSectionContents(DataRefImpl Sec, StringRef &Res) const {
654 MachO::section_64 Sect = getSection64(Sec);
655 Offset = Sect.offset;
658 MachO::section Sect = getSection(Sec);
659 Offset = Sect.offset;
663 Res = this->getData().substr(Offset, Size);
664 return object_error::success;
668 MachOObjectFile::getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const {
671 MachO::section_64 Sect = getSection64(Sec);
674 MachO::section Sect = getSection(Sec);
678 Res = uint64_t(1) << Align;
679 return object_error::success;
683 MachOObjectFile::isSectionText(DataRefImpl Sec, bool &Res) const {
684 uint32_t Flags = getSectionFlags(this, Sec);
685 Res = Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
686 return object_error::success;
689 error_code MachOObjectFile::isSectionData(DataRefImpl DRI, bool &Result) const {
690 // FIXME: Unimplemented.
692 return object_error::success;
695 error_code MachOObjectFile::isSectionBSS(DataRefImpl DRI, bool &Result) const {
696 // FIXME: Unimplemented.
698 return object_error::success;
702 MachOObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
703 bool &Result) const {
704 // FIXME: Unimplemented.
706 return object_error::success;
709 error_code MachOObjectFile::isSectionVirtual(DataRefImpl Sec,
710 bool &Result) const {
711 // FIXME: Unimplemented.
713 return object_error::success;
717 MachOObjectFile::isSectionZeroInit(DataRefImpl Sec, bool &Res) const {
718 uint32_t Flags = getSectionFlags(this, Sec);
719 unsigned SectionType = Flags & MachO::SECTION_TYPE;
720 Res = SectionType == MachO::S_ZEROFILL ||
721 SectionType == MachO::S_GB_ZEROFILL;
722 return object_error::success;
725 error_code MachOObjectFile::isSectionReadOnlyData(DataRefImpl Sec,
726 bool &Result) const {
727 // Consider using the code from isSectionText to look for __const sections.
728 // Alternately, emit S_ATTR_PURE_INSTRUCTIONS and/or S_ATTR_SOME_INSTRUCTIONS
729 // to use section attributes to distinguish code from data.
731 // FIXME: Unimplemented.
733 return object_error::success;
737 MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
738 bool &Result) const {
740 this->getSymbolType(Symb, ST);
741 if (ST == SymbolRef::ST_Unknown) {
743 return object_error::success;
746 uint64_t SectBegin, SectEnd;
747 getSectionAddress(Sec, SectBegin);
748 getSectionSize(Sec, SectEnd);
749 SectEnd += SectBegin;
752 getSymbolAddress(Symb, SymAddr);
753 Result = (SymAddr >= SectBegin) && (SymAddr < SectEnd);
755 return object_error::success;
758 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
762 return relocation_iterator(RelocationRef(Ret, this));
766 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
769 MachO::section_64 Sect = getSection64(Sec);
772 MachO::section Sect = getSection(Sec);
779 return relocation_iterator(RelocationRef(Ret, this));
782 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
787 MachOObjectFile::getRelocationAddress(DataRefImpl Rel, uint64_t &Res) const {
789 getRelocationOffset(Rel, Offset);
794 getSectionAddress(Sec, SecAddress);
795 Res = SecAddress + Offset;
796 return object_error::success;
799 error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
800 uint64_t &Res) const {
801 assert(getHeader().filetype == MachO::MH_OBJECT &&
802 "Only implemented for MH_OBJECT");
803 MachO::any_relocation_info RE = getRelocation(Rel);
804 Res = getAnyRelocationAddress(RE);
805 return object_error::success;
809 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
810 MachO::any_relocation_info RE = getRelocation(Rel);
811 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
812 bool isExtern = getPlainRelocationExternal(RE);
816 MachO::symtab_command S = getSymtabLoadCommand();
817 unsigned SymbolTableEntrySize = is64Bit() ?
818 sizeof(MachO::nlist_64) :
819 sizeof(MachO::nlist);
820 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
822 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
823 return symbol_iterator(SymbolRef(Sym, this));
826 error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
827 uint64_t &Res) const {
828 MachO::any_relocation_info RE = getRelocation(Rel);
829 Res = getAnyRelocationType(RE);
830 return object_error::success;
834 MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
835 SmallVectorImpl<char> &Result) const {
838 getRelocationType(Rel, RType);
840 unsigned Arch = this->getArch();
844 static const char *const Table[] = {
845 "GENERIC_RELOC_VANILLA",
846 "GENERIC_RELOC_PAIR",
847 "GENERIC_RELOC_SECTDIFF",
848 "GENERIC_RELOC_PB_LA_PTR",
849 "GENERIC_RELOC_LOCAL_SECTDIFF",
850 "GENERIC_RELOC_TLV" };
858 case Triple::x86_64: {
859 static const char *const Table[] = {
860 "X86_64_RELOC_UNSIGNED",
861 "X86_64_RELOC_SIGNED",
862 "X86_64_RELOC_BRANCH",
863 "X86_64_RELOC_GOT_LOAD",
865 "X86_64_RELOC_SUBTRACTOR",
866 "X86_64_RELOC_SIGNED_1",
867 "X86_64_RELOC_SIGNED_2",
868 "X86_64_RELOC_SIGNED_4",
869 "X86_64_RELOC_TLV" };
878 static const char *const Table[] = {
881 "ARM_RELOC_SECTDIFF",
882 "ARM_RELOC_LOCAL_SECTDIFF",
883 "ARM_RELOC_PB_LA_PTR",
885 "ARM_THUMB_RELOC_BR22",
886 "ARM_THUMB_32BIT_BRANCH",
888 "ARM_RELOC_HALF_SECTDIFF" };
897 case Triple::aarch64: {
898 static const char *const Table[] = {
899 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
900 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
901 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
902 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
903 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
907 if (RType >= array_lengthof(Table))
914 static const char *const Table[] = {
923 "PPC_RELOC_SECTDIFF",
924 "PPC_RELOC_PB_LA_PTR",
925 "PPC_RELOC_HI16_SECTDIFF",
926 "PPC_RELOC_LO16_SECTDIFF",
927 "PPC_RELOC_HA16_SECTDIFF",
929 "PPC_RELOC_LO14_SECTDIFF",
930 "PPC_RELOC_LOCAL_SECTDIFF" };
938 case Triple::UnknownArch:
942 Result.append(res.begin(), res.end());
943 return object_error::success;
947 MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
948 SmallVectorImpl<char> &Result) const {
949 MachO::any_relocation_info RE = getRelocation(Rel);
951 unsigned Arch = this->getArch();
954 raw_string_ostream fmt(fmtbuf);
955 unsigned Type = this->getAnyRelocationType(RE);
956 bool IsPCRel = this->getAnyRelocationPCRel(RE);
958 // Determine any addends that should be displayed with the relocation.
959 // These require decoding the relocation type, which is triple-specific.
961 // X86_64 has entirely custom relocation types.
962 if (Arch == Triple::x86_64) {
963 bool isPCRel = getAnyRelocationPCRel(RE);
966 case MachO::X86_64_RELOC_GOT_LOAD:
967 case MachO::X86_64_RELOC_GOT: {
968 printRelocationTargetName(this, RE, fmt);
970 if (isPCRel) fmt << "PCREL";
973 case MachO::X86_64_RELOC_SUBTRACTOR: {
974 DataRefImpl RelNext = Rel;
975 moveRelocationNext(RelNext);
976 MachO::any_relocation_info RENext = getRelocation(RelNext);
978 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
979 // X86_64_RELOC_UNSIGNED.
980 // NOTE: Scattered relocations don't exist on x86_64.
981 unsigned RType = getAnyRelocationType(RENext);
982 if (RType != MachO::X86_64_RELOC_UNSIGNED)
983 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
984 "X86_64_RELOC_SUBTRACTOR.");
986 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
987 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
988 printRelocationTargetName(this, RENext, fmt);
990 printRelocationTargetName(this, RE, fmt);
993 case MachO::X86_64_RELOC_TLV:
994 printRelocationTargetName(this, RE, fmt);
996 if (isPCRel) fmt << "P";
998 case MachO::X86_64_RELOC_SIGNED_1:
999 printRelocationTargetName(this, RE, fmt);
1002 case MachO::X86_64_RELOC_SIGNED_2:
1003 printRelocationTargetName(this, RE, fmt);
1006 case MachO::X86_64_RELOC_SIGNED_4:
1007 printRelocationTargetName(this, RE, fmt);
1011 printRelocationTargetName(this, RE, fmt);
1014 // X86 and ARM share some relocation types in common.
1015 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
1016 Arch == Triple::ppc) {
1017 // Generic relocation types...
1019 case MachO::GENERIC_RELOC_PAIR: // prints no info
1020 return object_error::success;
1021 case MachO::GENERIC_RELOC_SECTDIFF: {
1022 DataRefImpl RelNext = Rel;
1023 moveRelocationNext(RelNext);
1024 MachO::any_relocation_info RENext = getRelocation(RelNext);
1026 // X86 sect diff's must be followed by a relocation of type
1027 // GENERIC_RELOC_PAIR.
1028 unsigned RType = getAnyRelocationType(RENext);
1030 if (RType != MachO::GENERIC_RELOC_PAIR)
1031 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1032 "GENERIC_RELOC_SECTDIFF.");
1034 printRelocationTargetName(this, RE, fmt);
1036 printRelocationTargetName(this, RENext, fmt);
1041 if (Arch == Triple::x86 || Arch == Triple::ppc) {
1043 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1044 DataRefImpl RelNext = Rel;
1045 moveRelocationNext(RelNext);
1046 MachO::any_relocation_info RENext = getRelocation(RelNext);
1048 // X86 sect diff's must be followed by a relocation of type
1049 // GENERIC_RELOC_PAIR.
1050 unsigned RType = getAnyRelocationType(RENext);
1051 if (RType != MachO::GENERIC_RELOC_PAIR)
1052 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1053 "GENERIC_RELOC_LOCAL_SECTDIFF.");
1055 printRelocationTargetName(this, RE, fmt);
1057 printRelocationTargetName(this, RENext, fmt);
1060 case MachO::GENERIC_RELOC_TLV: {
1061 printRelocationTargetName(this, RE, fmt);
1063 if (IsPCRel) fmt << "P";
1067 printRelocationTargetName(this, RE, fmt);
1069 } else { // ARM-specific relocations
1071 case MachO::ARM_RELOC_HALF:
1072 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1073 // Half relocations steal a bit from the length field to encode
1074 // whether this is an upper16 or a lower16 relocation.
1075 bool isUpper = getAnyRelocationLength(RE) >> 1;
1078 fmt << ":upper16:(";
1080 fmt << ":lower16:(";
1081 printRelocationTargetName(this, RE, fmt);
1083 DataRefImpl RelNext = Rel;
1084 moveRelocationNext(RelNext);
1085 MachO::any_relocation_info RENext = getRelocation(RelNext);
1087 // ARM half relocs must be followed by a relocation of type
1089 unsigned RType = getAnyRelocationType(RENext);
1090 if (RType != MachO::ARM_RELOC_PAIR)
1091 report_fatal_error("Expected ARM_RELOC_PAIR after "
1094 // NOTE: The half of the target virtual address is stashed in the
1095 // address field of the secondary relocation, but we can't reverse
1096 // engineer the constant offset from it without decoding the movw/movt
1097 // instruction to find the other half in its immediate field.
1099 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1100 // symbol/section pointer of the follow-on relocation.
1101 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1103 printRelocationTargetName(this, RENext, fmt);
1110 printRelocationTargetName(this, RE, fmt);
1115 printRelocationTargetName(this, RE, fmt);
1118 Result.append(fmtbuf.begin(), fmtbuf.end());
1119 return object_error::success;
1123 MachOObjectFile::getRelocationHidden(DataRefImpl Rel, bool &Result) const {
1124 unsigned Arch = getArch();
1126 getRelocationType(Rel, Type);
1130 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1131 // is always hidden.
1132 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1133 if (Type == MachO::GENERIC_RELOC_PAIR) Result = true;
1134 } else if (Arch == Triple::x86_64) {
1135 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1136 // an X86_64_RELOC_SUBTRACTOR.
1137 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1138 DataRefImpl RelPrev = Rel;
1141 getRelocationType(RelPrev, PrevType);
1142 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1147 return object_error::success;
1150 error_code MachOObjectFile::getLibraryNext(DataRefImpl LibData,
1151 LibraryRef &Res) const {
1152 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1155 error_code MachOObjectFile::getLibraryPath(DataRefImpl LibData,
1156 StringRef &Res) const {
1157 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1160 basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
1161 return getSymbolByIndex(0);
1164 basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
1167 return basic_symbol_iterator(SymbolRef(DRI, this));
1169 MachO::symtab_command Symtab = getSymtabLoadCommand();
1170 unsigned SymbolTableEntrySize = is64Bit() ?
1171 sizeof(MachO::nlist_64) :
1172 sizeof(MachO::nlist);
1173 unsigned Offset = Symtab.symoff +
1174 Symtab.nsyms * SymbolTableEntrySize;
1175 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1176 return basic_symbol_iterator(SymbolRef(DRI, this));
1179 basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
1182 return basic_symbol_iterator(SymbolRef(DRI, this));
1184 MachO::symtab_command Symtab = getSymtabLoadCommand();
1185 assert(Index < Symtab.nsyms && "Requested symbol index is out of range.");
1186 unsigned SymbolTableEntrySize =
1187 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
1188 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1189 DRI.p += Index * SymbolTableEntrySize;
1190 return basic_symbol_iterator(SymbolRef(DRI, this));
1193 section_iterator MachOObjectFile::section_begin() const {
1195 return section_iterator(SectionRef(DRI, this));
1198 section_iterator MachOObjectFile::section_end() const {
1200 DRI.d.a = Sections.size();
1201 return section_iterator(SectionRef(DRI, this));
1204 library_iterator MachOObjectFile::needed_library_begin() const {
1206 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1209 library_iterator MachOObjectFile::needed_library_end() const {
1211 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1214 uint8_t MachOObjectFile::getBytesInAddress() const {
1215 return is64Bit() ? 8 : 4;
1218 StringRef MachOObjectFile::getFileFormatName() const {
1219 unsigned CPUType = getCPUType(this);
1222 case llvm::MachO::CPU_TYPE_I386:
1223 return "Mach-O 32-bit i386";
1224 case llvm::MachO::CPU_TYPE_ARM:
1225 return "Mach-O arm";
1226 case llvm::MachO::CPU_TYPE_POWERPC:
1227 return "Mach-O 32-bit ppc";
1229 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64) == 0 &&
1230 "64-bit object file when we're not 64-bit?");
1231 return "Mach-O 32-bit unknown";
1235 // Make sure the cpu type has the correct mask.
1236 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64)
1237 == llvm::MachO::CPU_ARCH_ABI64 &&
1238 "32-bit object file when we're 64-bit?");
1241 case llvm::MachO::CPU_TYPE_X86_64:
1242 return "Mach-O 64-bit x86-64";
1243 case llvm::MachO::CPU_TYPE_ARM64:
1244 return "Mach-O arm64";
1245 case llvm::MachO::CPU_TYPE_POWERPC64:
1246 return "Mach-O 64-bit ppc64";
1248 return "Mach-O 64-bit unknown";
1252 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1254 case llvm::MachO::CPU_TYPE_I386:
1256 case llvm::MachO::CPU_TYPE_X86_64:
1257 return Triple::x86_64;
1258 case llvm::MachO::CPU_TYPE_ARM:
1260 case llvm::MachO::CPU_TYPE_ARM64:
1261 return Triple::arm64;
1262 case llvm::MachO::CPU_TYPE_POWERPC:
1264 case llvm::MachO::CPU_TYPE_POWERPC64:
1265 return Triple::ppc64;
1267 return Triple::UnknownArch;
1271 unsigned MachOObjectFile::getArch() const {
1272 return getArch(getCPUType(this));
1275 StringRef MachOObjectFile::getLoadName() const {
1277 report_fatal_error("get_load_name() unimplemented in MachOObjectFile");
1280 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
1283 return section_rel_begin(DRI);
1286 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
1289 return section_rel_end(DRI);
1292 dice_iterator MachOObjectFile::begin_dices() const {
1294 if (!DataInCodeLoadCmd)
1295 return dice_iterator(DiceRef(DRI, this));
1297 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1298 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
1299 return dice_iterator(DiceRef(DRI, this));
1302 dice_iterator MachOObjectFile::end_dices() const {
1304 if (!DataInCodeLoadCmd)
1305 return dice_iterator(DiceRef(DRI, this));
1307 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1308 unsigned Offset = DicLC.dataoff + DicLC.datasize;
1309 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1310 return dice_iterator(DiceRef(DRI, this));
1314 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1315 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1316 return parseSegmentOrSectionName(Raw.data());
1320 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
1321 const section_base *Base =
1322 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1323 return ArrayRef<char>(Base->sectname);
1327 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
1328 const section_base *Base =
1329 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1330 return ArrayRef<char>(Base->segname);
1334 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
1336 if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
1338 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
1341 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
1342 const MachO::any_relocation_info &RE) const {
1343 if (isLittleEndian())
1344 return RE.r_word1 & 0xffffff;
1345 return RE.r_word1 >> 8;
1348 bool MachOObjectFile::getPlainRelocationExternal(
1349 const MachO::any_relocation_info &RE) const {
1350 if (isLittleEndian())
1351 return (RE.r_word1 >> 27) & 1;
1352 return (RE.r_word1 >> 4) & 1;
1355 bool MachOObjectFile::getScatteredRelocationScattered(
1356 const MachO::any_relocation_info &RE) const {
1357 return RE.r_word0 >> 31;
1360 uint32_t MachOObjectFile::getScatteredRelocationValue(
1361 const MachO::any_relocation_info &RE) const {
1365 unsigned MachOObjectFile::getAnyRelocationAddress(
1366 const MachO::any_relocation_info &RE) const {
1367 if (isRelocationScattered(RE))
1368 return getScatteredRelocationAddress(RE);
1369 return getPlainRelocationAddress(RE);
1372 unsigned MachOObjectFile::getAnyRelocationPCRel(
1373 const MachO::any_relocation_info &RE) const {
1374 if (isRelocationScattered(RE))
1375 return getScatteredRelocationPCRel(this, RE);
1376 return getPlainRelocationPCRel(this, RE);
1379 unsigned MachOObjectFile::getAnyRelocationLength(
1380 const MachO::any_relocation_info &RE) const {
1381 if (isRelocationScattered(RE))
1382 return getScatteredRelocationLength(RE);
1383 return getPlainRelocationLength(this, RE);
1387 MachOObjectFile::getAnyRelocationType(
1388 const MachO::any_relocation_info &RE) const {
1389 if (isRelocationScattered(RE))
1390 return getScatteredRelocationType(RE);
1391 return getPlainRelocationType(this, RE);
1395 MachOObjectFile::getRelocationSection(
1396 const MachO::any_relocation_info &RE) const {
1397 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
1398 return *section_end();
1399 unsigned SecNum = getPlainRelocationSymbolNum(RE) - 1;
1402 return SectionRef(DRI, this);
1405 MachOObjectFile::LoadCommandInfo
1406 MachOObjectFile::getFirstLoadCommandInfo() const {
1407 MachOObjectFile::LoadCommandInfo Load;
1409 unsigned HeaderSize = is64Bit() ? sizeof(MachO::mach_header_64) :
1410 sizeof(MachO::mach_header);
1411 Load.Ptr = getPtr(this, HeaderSize);
1412 Load.C = getStruct<MachO::load_command>(this, Load.Ptr);
1416 MachOObjectFile::LoadCommandInfo
1417 MachOObjectFile::getNextLoadCommandInfo(const LoadCommandInfo &L) const {
1418 MachOObjectFile::LoadCommandInfo Next;
1419 Next.Ptr = L.Ptr + L.C.cmdsize;
1420 Next.C = getStruct<MachO::load_command>(this, Next.Ptr);
1424 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
1425 return getStruct<MachO::section>(this, Sections[DRI.d.a]);
1428 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
1429 return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
1432 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
1433 unsigned Index) const {
1434 const char *Sec = getSectionPtr(this, L, Index);
1435 return getStruct<MachO::section>(this, Sec);
1438 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
1439 unsigned Index) const {
1440 const char *Sec = getSectionPtr(this, L, Index);
1441 return getStruct<MachO::section_64>(this, Sec);
1445 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
1446 const char *P = reinterpret_cast<const char *>(DRI.p);
1447 return getStruct<MachO::nlist>(this, P);
1451 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
1452 const char *P = reinterpret_cast<const char *>(DRI.p);
1453 return getStruct<MachO::nlist_64>(this, P);
1456 MachO::linkedit_data_command
1457 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
1458 return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
1461 MachO::segment_command
1462 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
1463 return getStruct<MachO::segment_command>(this, L.Ptr);
1466 MachO::segment_command_64
1467 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
1468 return getStruct<MachO::segment_command_64>(this, L.Ptr);
1471 MachO::linker_options_command
1472 MachOObjectFile::getLinkerOptionsLoadCommand(const LoadCommandInfo &L) const {
1473 return getStruct<MachO::linker_options_command>(this, L.Ptr);
1476 MachO::version_min_command
1477 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
1478 return getStruct<MachO::version_min_command>(this, L.Ptr);
1481 MachO::any_relocation_info
1482 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
1487 MachO::section_64 Sect = getSection64(Sec);
1488 Offset = Sect.reloff;
1490 MachO::section Sect = getSection(Sec);
1491 Offset = Sect.reloff;
1494 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
1495 getPtr(this, Offset)) + Rel.d.b;
1496 return getStruct<MachO::any_relocation_info>(
1497 this, reinterpret_cast<const char *>(P));
1500 MachO::data_in_code_entry
1501 MachOObjectFile::getDice(DataRefImpl Rel) const {
1502 const char *P = reinterpret_cast<const char *>(Rel.p);
1503 return getStruct<MachO::data_in_code_entry>(this, P);
1506 MachO::mach_header MachOObjectFile::getHeader() const {
1507 return getStruct<MachO::mach_header>(this, getPtr(this, 0));
1510 MachO::mach_header_64 MachOObjectFile::getHeader64() const {
1511 return getStruct<MachO::mach_header_64>(this, getPtr(this, 0));
1514 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
1515 const MachO::dysymtab_command &DLC,
1516 unsigned Index) const {
1517 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
1518 return getStruct<uint32_t>(this, getPtr(this, Offset));
1521 MachO::data_in_code_entry
1522 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
1523 unsigned Index) const {
1524 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
1525 return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
1528 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
1529 return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
1532 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
1533 return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
1536 MachO::linkedit_data_command
1537 MachOObjectFile::getDataInCodeLoadCommand() const {
1538 if (DataInCodeLoadCmd)
1539 return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
1541 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
1542 MachO::linkedit_data_command Cmd;
1543 Cmd.cmd = MachO::LC_DATA_IN_CODE;
1544 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
1550 StringRef MachOObjectFile::getStringTableData() const {
1551 MachO::symtab_command S = getSymtabLoadCommand();
1552 return getData().substr(S.stroff, S.strsize);
1555 bool MachOObjectFile::is64Bit() const {
1556 return getType() == getMachOType(false, true) ||
1557 getType() == getMachOType(true, true);
1560 void MachOObjectFile::ReadULEB128s(uint64_t Index,
1561 SmallVectorImpl<uint64_t> &Out) const {
1562 DataExtractor extractor(ObjectFile::getData(), true, 0);
1564 uint32_t offset = Index;
1566 while (uint64_t delta = extractor.getULEB128(&offset)) {
1568 Out.push_back(data);
1572 ErrorOr<ObjectFile *> ObjectFile::createMachOObjectFile(MemoryBuffer *Buffer,
1574 StringRef Magic = Buffer->getBuffer().slice(0, 4);
1576 std::unique_ptr<MachOObjectFile> Ret;
1577 if (Magic == "\xFE\xED\xFA\xCE")
1578 Ret.reset(new MachOObjectFile(Buffer, false, false, EC, BufferOwned));
1579 else if (Magic == "\xCE\xFA\xED\xFE")
1580 Ret.reset(new MachOObjectFile(Buffer, true, false, EC, BufferOwned));
1581 else if (Magic == "\xFE\xED\xFA\xCF")
1582 Ret.reset(new MachOObjectFile(Buffer, false, true, EC, BufferOwned));
1583 else if (Magic == "\xCF\xFA\xED\xFE")
1584 Ret.reset(new MachOObjectFile(Buffer, true, true, EC, BufferOwned));
1587 return object_error::parse_failed;
1592 return Ret.release();
1595 } // end namespace object
1596 } // end namespace llvm