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);
475 if ((Entry.n_type & MachO::N_TYPE) == MachO::N_UNDF &&
477 Res = UnknownAddressOrSize;
481 MachO::nlist Entry = getSymbolTableEntry(Symb);
482 if ((Entry.n_type & MachO::N_TYPE) == MachO::N_UNDF &&
484 Res = UnknownAddressOrSize;
488 return object_error::success;
491 error_code MachOObjectFile::getSymbolAlignment(DataRefImpl DRI,
492 uint32_t &Result) const {
493 uint32_t flags = getSymbolFlags(DRI);
494 if (flags & SymbolRef::SF_Common) {
495 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
496 Result = 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
500 return object_error::success;
503 error_code MachOObjectFile::getSymbolSize(DataRefImpl DRI,
504 uint64_t &Result) const {
505 uint64_t BeginOffset;
506 uint64_t EndOffset = 0;
507 uint8_t SectionIndex;
509 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
511 getSymbolAddress(DRI, Value);
512 if (Value == UnknownAddressOrSize) {
513 Result = UnknownAddressOrSize;
514 return object_error::success;
519 SectionIndex = Entry.n_sect;
521 uint32_t flags = getSymbolFlags(DRI);
522 if (flags & SymbolRef::SF_Common)
525 Result = UnknownAddressOrSize;
526 return object_error::success;
528 // Unfortunately symbols are unsorted so we need to touch all
529 // symbols from load command
530 for (const SymbolRef &Symbol : symbols()) {
531 DataRefImpl DRI = Symbol.getRawDataRefImpl();
532 Entry = getSymbolTableEntryBase(this, DRI);
533 getSymbolAddress(DRI, Value);
534 if (Value == UnknownAddressOrSize)
536 if (Entry.n_sect == SectionIndex && Value > BeginOffset)
537 if (!EndOffset || Value < EndOffset)
543 Sec.d.a = SectionIndex-1;
544 getSectionSize(Sec, Size);
545 getSectionAddress(Sec, EndOffset);
548 Result = EndOffset - BeginOffset;
549 return object_error::success;
552 error_code MachOObjectFile::getSymbolType(DataRefImpl Symb,
553 SymbolRef::Type &Res) const {
554 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
555 uint8_t n_type = Entry.n_type;
557 Res = SymbolRef::ST_Other;
559 // If this is a STAB debugging symbol, we can do nothing more.
560 if (n_type & MachO::N_STAB) {
561 Res = SymbolRef::ST_Debug;
562 return object_error::success;
565 switch (n_type & MachO::N_TYPE) {
567 Res = SymbolRef::ST_Unknown;
570 Res = SymbolRef::ST_Function;
573 return object_error::success;
576 uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
577 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
579 uint8_t MachOType = Entry.n_type;
580 uint16_t MachOFlags = Entry.n_desc;
582 uint32_t Result = SymbolRef::SF_None;
584 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF)
585 Result |= SymbolRef::SF_Undefined;
587 if (MachOType & MachO::N_STAB)
588 Result |= SymbolRef::SF_FormatSpecific;
590 if (MachOType & MachO::N_EXT) {
591 Result |= SymbolRef::SF_Global;
592 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
594 getSymbolAddress(DRI, Value);
595 if (Value && Value != UnknownAddressOrSize)
596 Result |= SymbolRef::SF_Common;
600 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
601 Result |= SymbolRef::SF_Weak;
603 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
604 Result |= SymbolRef::SF_Absolute;
610 MachOObjectFile::getSymbolSection(DataRefImpl Symb,
611 section_iterator &Res) const {
612 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
613 uint8_t index = Entry.n_sect;
620 Res = section_iterator(SectionRef(DRI, this));
623 return object_error::success;
626 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
631 MachOObjectFile::getSectionName(DataRefImpl Sec, StringRef &Result) const {
632 ArrayRef<char> Raw = getSectionRawName(Sec);
633 Result = parseSegmentOrSectionName(Raw.data());
634 return object_error::success;
638 MachOObjectFile::getSectionAddress(DataRefImpl Sec, uint64_t &Res) const {
640 MachO::section_64 Sect = getSection64(Sec);
643 MachO::section Sect = getSection(Sec);
646 return object_error::success;
650 MachOObjectFile::getSectionSize(DataRefImpl Sec, uint64_t &Res) const {
652 MachO::section_64 Sect = getSection64(Sec);
655 MachO::section Sect = getSection(Sec);
659 return object_error::success;
663 MachOObjectFile::getSectionContents(DataRefImpl Sec, StringRef &Res) const {
668 MachO::section_64 Sect = getSection64(Sec);
669 Offset = Sect.offset;
672 MachO::section Sect = getSection(Sec);
673 Offset = Sect.offset;
677 Res = this->getData().substr(Offset, Size);
678 return object_error::success;
682 MachOObjectFile::getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const {
685 MachO::section_64 Sect = getSection64(Sec);
688 MachO::section Sect = getSection(Sec);
692 Res = uint64_t(1) << Align;
693 return object_error::success;
697 MachOObjectFile::isSectionText(DataRefImpl Sec, bool &Res) const {
698 uint32_t Flags = getSectionFlags(this, Sec);
699 Res = Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
700 return object_error::success;
703 error_code MachOObjectFile::isSectionData(DataRefImpl Sec, bool &Result) const {
704 uint32_t Flags = getSectionFlags(this, Sec);
705 unsigned SectionType = Flags & MachO::SECTION_TYPE;
706 Result = !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
707 !(SectionType == MachO::S_ZEROFILL ||
708 SectionType == MachO::S_GB_ZEROFILL);
709 return object_error::success;
712 error_code MachOObjectFile::isSectionBSS(DataRefImpl Sec, bool &Result) const {
713 uint32_t Flags = getSectionFlags(this, Sec);
714 unsigned SectionType = Flags & MachO::SECTION_TYPE;
715 Result = !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
716 (SectionType == MachO::S_ZEROFILL ||
717 SectionType == MachO::S_GB_ZEROFILL);
718 return object_error::success;
722 MachOObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
723 bool &Result) const {
724 // FIXME: Unimplemented.
726 return object_error::success;
729 error_code MachOObjectFile::isSectionVirtual(DataRefImpl Sec,
730 bool &Result) const {
731 // FIXME: Unimplemented.
733 return object_error::success;
737 MachOObjectFile::isSectionZeroInit(DataRefImpl Sec, bool &Res) const {
738 uint32_t Flags = getSectionFlags(this, Sec);
739 unsigned SectionType = Flags & MachO::SECTION_TYPE;
740 Res = SectionType == MachO::S_ZEROFILL ||
741 SectionType == MachO::S_GB_ZEROFILL;
742 return object_error::success;
745 error_code MachOObjectFile::isSectionReadOnlyData(DataRefImpl Sec,
746 bool &Result) const {
747 // Consider using the code from isSectionText to look for __const sections.
748 // Alternately, emit S_ATTR_PURE_INSTRUCTIONS and/or S_ATTR_SOME_INSTRUCTIONS
749 // to use section attributes to distinguish code from data.
751 // FIXME: Unimplemented.
753 return object_error::success;
757 MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
758 bool &Result) const {
760 this->getSymbolType(Symb, ST);
761 if (ST == SymbolRef::ST_Unknown) {
763 return object_error::success;
766 uint64_t SectBegin, SectEnd;
767 getSectionAddress(Sec, SectBegin);
768 getSectionSize(Sec, SectEnd);
769 SectEnd += SectBegin;
772 getSymbolAddress(Symb, SymAddr);
773 Result = (SymAddr >= SectBegin) && (SymAddr < SectEnd);
775 return object_error::success;
778 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
782 return relocation_iterator(RelocationRef(Ret, this));
786 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
789 MachO::section_64 Sect = getSection64(Sec);
792 MachO::section Sect = getSection(Sec);
799 return relocation_iterator(RelocationRef(Ret, this));
802 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
807 MachOObjectFile::getRelocationAddress(DataRefImpl Rel, uint64_t &Res) const {
809 getRelocationOffset(Rel, Offset);
814 getSectionAddress(Sec, SecAddress);
815 Res = SecAddress + Offset;
816 return object_error::success;
819 error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
820 uint64_t &Res) const {
821 assert(getHeader().filetype == MachO::MH_OBJECT &&
822 "Only implemented for MH_OBJECT");
823 MachO::any_relocation_info RE = getRelocation(Rel);
824 Res = getAnyRelocationAddress(RE);
825 return object_error::success;
829 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
830 MachO::any_relocation_info RE = getRelocation(Rel);
831 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
832 bool isExtern = getPlainRelocationExternal(RE);
836 MachO::symtab_command S = getSymtabLoadCommand();
837 unsigned SymbolTableEntrySize = is64Bit() ?
838 sizeof(MachO::nlist_64) :
839 sizeof(MachO::nlist);
840 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
842 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
843 return symbol_iterator(SymbolRef(Sym, this));
846 error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
847 uint64_t &Res) const {
848 MachO::any_relocation_info RE = getRelocation(Rel);
849 Res = getAnyRelocationType(RE);
850 return object_error::success;
854 MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
855 SmallVectorImpl<char> &Result) const {
858 getRelocationType(Rel, RType);
860 unsigned Arch = this->getArch();
864 static const char *const Table[] = {
865 "GENERIC_RELOC_VANILLA",
866 "GENERIC_RELOC_PAIR",
867 "GENERIC_RELOC_SECTDIFF",
868 "GENERIC_RELOC_PB_LA_PTR",
869 "GENERIC_RELOC_LOCAL_SECTDIFF",
870 "GENERIC_RELOC_TLV" };
878 case Triple::x86_64: {
879 static const char *const Table[] = {
880 "X86_64_RELOC_UNSIGNED",
881 "X86_64_RELOC_SIGNED",
882 "X86_64_RELOC_BRANCH",
883 "X86_64_RELOC_GOT_LOAD",
885 "X86_64_RELOC_SUBTRACTOR",
886 "X86_64_RELOC_SIGNED_1",
887 "X86_64_RELOC_SIGNED_2",
888 "X86_64_RELOC_SIGNED_4",
889 "X86_64_RELOC_TLV" };
898 static const char *const Table[] = {
901 "ARM_RELOC_SECTDIFF",
902 "ARM_RELOC_LOCAL_SECTDIFF",
903 "ARM_RELOC_PB_LA_PTR",
905 "ARM_THUMB_RELOC_BR22",
906 "ARM_THUMB_32BIT_BRANCH",
908 "ARM_RELOC_HALF_SECTDIFF" };
917 case Triple::aarch64: {
918 static const char *const Table[] = {
919 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
920 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
921 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
922 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
923 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
927 if (RType >= array_lengthof(Table))
934 static const char *const Table[] = {
943 "PPC_RELOC_SECTDIFF",
944 "PPC_RELOC_PB_LA_PTR",
945 "PPC_RELOC_HI16_SECTDIFF",
946 "PPC_RELOC_LO16_SECTDIFF",
947 "PPC_RELOC_HA16_SECTDIFF",
949 "PPC_RELOC_LO14_SECTDIFF",
950 "PPC_RELOC_LOCAL_SECTDIFF" };
958 case Triple::UnknownArch:
962 Result.append(res.begin(), res.end());
963 return object_error::success;
967 MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
968 SmallVectorImpl<char> &Result) const {
969 MachO::any_relocation_info RE = getRelocation(Rel);
971 unsigned Arch = this->getArch();
974 raw_string_ostream fmt(fmtbuf);
975 unsigned Type = this->getAnyRelocationType(RE);
976 bool IsPCRel = this->getAnyRelocationPCRel(RE);
978 // Determine any addends that should be displayed with the relocation.
979 // These require decoding the relocation type, which is triple-specific.
981 // X86_64 has entirely custom relocation types.
982 if (Arch == Triple::x86_64) {
983 bool isPCRel = getAnyRelocationPCRel(RE);
986 case MachO::X86_64_RELOC_GOT_LOAD:
987 case MachO::X86_64_RELOC_GOT: {
988 printRelocationTargetName(this, RE, fmt);
990 if (isPCRel) fmt << "PCREL";
993 case MachO::X86_64_RELOC_SUBTRACTOR: {
994 DataRefImpl RelNext = Rel;
995 moveRelocationNext(RelNext);
996 MachO::any_relocation_info RENext = getRelocation(RelNext);
998 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
999 // X86_64_RELOC_UNSIGNED.
1000 // NOTE: Scattered relocations don't exist on x86_64.
1001 unsigned RType = getAnyRelocationType(RENext);
1002 if (RType != MachO::X86_64_RELOC_UNSIGNED)
1003 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
1004 "X86_64_RELOC_SUBTRACTOR.");
1006 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
1007 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
1008 printRelocationTargetName(this, RENext, fmt);
1010 printRelocationTargetName(this, RE, fmt);
1013 case MachO::X86_64_RELOC_TLV:
1014 printRelocationTargetName(this, RE, fmt);
1016 if (isPCRel) fmt << "P";
1018 case MachO::X86_64_RELOC_SIGNED_1:
1019 printRelocationTargetName(this, RE, fmt);
1022 case MachO::X86_64_RELOC_SIGNED_2:
1023 printRelocationTargetName(this, RE, fmt);
1026 case MachO::X86_64_RELOC_SIGNED_4:
1027 printRelocationTargetName(this, RE, fmt);
1031 printRelocationTargetName(this, RE, fmt);
1034 // X86 and ARM share some relocation types in common.
1035 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
1036 Arch == Triple::ppc) {
1037 // Generic relocation types...
1039 case MachO::GENERIC_RELOC_PAIR: // prints no info
1040 return object_error::success;
1041 case MachO::GENERIC_RELOC_SECTDIFF: {
1042 DataRefImpl RelNext = Rel;
1043 moveRelocationNext(RelNext);
1044 MachO::any_relocation_info RENext = getRelocation(RelNext);
1046 // X86 sect diff's must be followed by a relocation of type
1047 // GENERIC_RELOC_PAIR.
1048 unsigned RType = getAnyRelocationType(RENext);
1050 if (RType != MachO::GENERIC_RELOC_PAIR)
1051 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1052 "GENERIC_RELOC_SECTDIFF.");
1054 printRelocationTargetName(this, RE, fmt);
1056 printRelocationTargetName(this, RENext, fmt);
1061 if (Arch == Triple::x86 || Arch == Triple::ppc) {
1063 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1064 DataRefImpl RelNext = Rel;
1065 moveRelocationNext(RelNext);
1066 MachO::any_relocation_info RENext = getRelocation(RelNext);
1068 // X86 sect diff's must be followed by a relocation of type
1069 // GENERIC_RELOC_PAIR.
1070 unsigned RType = getAnyRelocationType(RENext);
1071 if (RType != MachO::GENERIC_RELOC_PAIR)
1072 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1073 "GENERIC_RELOC_LOCAL_SECTDIFF.");
1075 printRelocationTargetName(this, RE, fmt);
1077 printRelocationTargetName(this, RENext, fmt);
1080 case MachO::GENERIC_RELOC_TLV: {
1081 printRelocationTargetName(this, RE, fmt);
1083 if (IsPCRel) fmt << "P";
1087 printRelocationTargetName(this, RE, fmt);
1089 } else { // ARM-specific relocations
1091 case MachO::ARM_RELOC_HALF:
1092 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1093 // Half relocations steal a bit from the length field to encode
1094 // whether this is an upper16 or a lower16 relocation.
1095 bool isUpper = getAnyRelocationLength(RE) >> 1;
1098 fmt << ":upper16:(";
1100 fmt << ":lower16:(";
1101 printRelocationTargetName(this, RE, fmt);
1103 DataRefImpl RelNext = Rel;
1104 moveRelocationNext(RelNext);
1105 MachO::any_relocation_info RENext = getRelocation(RelNext);
1107 // ARM half relocs must be followed by a relocation of type
1109 unsigned RType = getAnyRelocationType(RENext);
1110 if (RType != MachO::ARM_RELOC_PAIR)
1111 report_fatal_error("Expected ARM_RELOC_PAIR after "
1114 // NOTE: The half of the target virtual address is stashed in the
1115 // address field of the secondary relocation, but we can't reverse
1116 // engineer the constant offset from it without decoding the movw/movt
1117 // instruction to find the other half in its immediate field.
1119 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1120 // symbol/section pointer of the follow-on relocation.
1121 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1123 printRelocationTargetName(this, RENext, fmt);
1130 printRelocationTargetName(this, RE, fmt);
1135 printRelocationTargetName(this, RE, fmt);
1138 Result.append(fmtbuf.begin(), fmtbuf.end());
1139 return object_error::success;
1143 MachOObjectFile::getRelocationHidden(DataRefImpl Rel, bool &Result) const {
1144 unsigned Arch = getArch();
1146 getRelocationType(Rel, Type);
1150 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1151 // is always hidden.
1152 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1153 if (Type == MachO::GENERIC_RELOC_PAIR) Result = true;
1154 } else if (Arch == Triple::x86_64) {
1155 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1156 // an X86_64_RELOC_SUBTRACTOR.
1157 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1158 DataRefImpl RelPrev = Rel;
1161 getRelocationType(RelPrev, PrevType);
1162 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1167 return object_error::success;
1170 error_code MachOObjectFile::getLibraryNext(DataRefImpl LibData,
1171 LibraryRef &Res) const {
1172 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1175 error_code MachOObjectFile::getLibraryPath(DataRefImpl LibData,
1176 StringRef &Res) const {
1177 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1180 basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
1181 return getSymbolByIndex(0);
1184 basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
1187 return basic_symbol_iterator(SymbolRef(DRI, this));
1189 MachO::symtab_command Symtab = getSymtabLoadCommand();
1190 unsigned SymbolTableEntrySize = is64Bit() ?
1191 sizeof(MachO::nlist_64) :
1192 sizeof(MachO::nlist);
1193 unsigned Offset = Symtab.symoff +
1194 Symtab.nsyms * SymbolTableEntrySize;
1195 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1196 return basic_symbol_iterator(SymbolRef(DRI, this));
1199 basic_symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
1202 return basic_symbol_iterator(SymbolRef(DRI, this));
1204 MachO::symtab_command Symtab = getSymtabLoadCommand();
1205 assert(Index < Symtab.nsyms && "Requested symbol index is out of range.");
1206 unsigned SymbolTableEntrySize =
1207 is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
1208 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1209 DRI.p += Index * SymbolTableEntrySize;
1210 return basic_symbol_iterator(SymbolRef(DRI, this));
1213 section_iterator MachOObjectFile::section_begin() const {
1215 return section_iterator(SectionRef(DRI, this));
1218 section_iterator MachOObjectFile::section_end() const {
1220 DRI.d.a = Sections.size();
1221 return section_iterator(SectionRef(DRI, this));
1224 library_iterator MachOObjectFile::needed_library_begin() const {
1226 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1229 library_iterator MachOObjectFile::needed_library_end() const {
1231 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1234 uint8_t MachOObjectFile::getBytesInAddress() const {
1235 return is64Bit() ? 8 : 4;
1238 StringRef MachOObjectFile::getFileFormatName() const {
1239 unsigned CPUType = getCPUType(this);
1242 case llvm::MachO::CPU_TYPE_I386:
1243 return "Mach-O 32-bit i386";
1244 case llvm::MachO::CPU_TYPE_ARM:
1245 return "Mach-O arm";
1246 case llvm::MachO::CPU_TYPE_POWERPC:
1247 return "Mach-O 32-bit ppc";
1249 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64) == 0 &&
1250 "64-bit object file when we're not 64-bit?");
1251 return "Mach-O 32-bit unknown";
1255 // Make sure the cpu type has the correct mask.
1256 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64)
1257 == llvm::MachO::CPU_ARCH_ABI64 &&
1258 "32-bit object file when we're 64-bit?");
1261 case llvm::MachO::CPU_TYPE_X86_64:
1262 return "Mach-O 64-bit x86-64";
1263 case llvm::MachO::CPU_TYPE_ARM64:
1264 return "Mach-O arm64";
1265 case llvm::MachO::CPU_TYPE_POWERPC64:
1266 return "Mach-O 64-bit ppc64";
1268 return "Mach-O 64-bit unknown";
1272 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1274 case llvm::MachO::CPU_TYPE_I386:
1276 case llvm::MachO::CPU_TYPE_X86_64:
1277 return Triple::x86_64;
1278 case llvm::MachO::CPU_TYPE_ARM:
1280 case llvm::MachO::CPU_TYPE_ARM64:
1281 return Triple::arm64;
1282 case llvm::MachO::CPU_TYPE_POWERPC:
1284 case llvm::MachO::CPU_TYPE_POWERPC64:
1285 return Triple::ppc64;
1287 return Triple::UnknownArch;
1291 unsigned MachOObjectFile::getArch() const {
1292 return getArch(getCPUType(this));
1295 StringRef MachOObjectFile::getLoadName() const {
1297 report_fatal_error("get_load_name() unimplemented in MachOObjectFile");
1300 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
1303 return section_rel_begin(DRI);
1306 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
1309 return section_rel_end(DRI);
1312 dice_iterator MachOObjectFile::begin_dices() const {
1314 if (!DataInCodeLoadCmd)
1315 return dice_iterator(DiceRef(DRI, this));
1317 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1318 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
1319 return dice_iterator(DiceRef(DRI, this));
1322 dice_iterator MachOObjectFile::end_dices() const {
1324 if (!DataInCodeLoadCmd)
1325 return dice_iterator(DiceRef(DRI, this));
1327 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1328 unsigned Offset = DicLC.dataoff + DicLC.datasize;
1329 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1330 return dice_iterator(DiceRef(DRI, this));
1334 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1335 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1336 return parseSegmentOrSectionName(Raw.data());
1340 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
1341 const section_base *Base =
1342 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1343 return ArrayRef<char>(Base->sectname);
1347 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
1348 const section_base *Base =
1349 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1350 return ArrayRef<char>(Base->segname);
1354 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
1356 if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
1358 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
1361 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
1362 const MachO::any_relocation_info &RE) const {
1363 if (isLittleEndian())
1364 return RE.r_word1 & 0xffffff;
1365 return RE.r_word1 >> 8;
1368 bool MachOObjectFile::getPlainRelocationExternal(
1369 const MachO::any_relocation_info &RE) const {
1370 if (isLittleEndian())
1371 return (RE.r_word1 >> 27) & 1;
1372 return (RE.r_word1 >> 4) & 1;
1375 bool MachOObjectFile::getScatteredRelocationScattered(
1376 const MachO::any_relocation_info &RE) const {
1377 return RE.r_word0 >> 31;
1380 uint32_t MachOObjectFile::getScatteredRelocationValue(
1381 const MachO::any_relocation_info &RE) const {
1385 unsigned MachOObjectFile::getAnyRelocationAddress(
1386 const MachO::any_relocation_info &RE) const {
1387 if (isRelocationScattered(RE))
1388 return getScatteredRelocationAddress(RE);
1389 return getPlainRelocationAddress(RE);
1392 unsigned MachOObjectFile::getAnyRelocationPCRel(
1393 const MachO::any_relocation_info &RE) const {
1394 if (isRelocationScattered(RE))
1395 return getScatteredRelocationPCRel(this, RE);
1396 return getPlainRelocationPCRel(this, RE);
1399 unsigned MachOObjectFile::getAnyRelocationLength(
1400 const MachO::any_relocation_info &RE) const {
1401 if (isRelocationScattered(RE))
1402 return getScatteredRelocationLength(RE);
1403 return getPlainRelocationLength(this, RE);
1407 MachOObjectFile::getAnyRelocationType(
1408 const MachO::any_relocation_info &RE) const {
1409 if (isRelocationScattered(RE))
1410 return getScatteredRelocationType(RE);
1411 return getPlainRelocationType(this, RE);
1415 MachOObjectFile::getRelocationSection(
1416 const MachO::any_relocation_info &RE) const {
1417 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
1418 return *section_end();
1419 unsigned SecNum = getPlainRelocationSymbolNum(RE) - 1;
1422 return SectionRef(DRI, this);
1425 MachOObjectFile::LoadCommandInfo
1426 MachOObjectFile::getFirstLoadCommandInfo() const {
1427 MachOObjectFile::LoadCommandInfo Load;
1429 unsigned HeaderSize = is64Bit() ? sizeof(MachO::mach_header_64) :
1430 sizeof(MachO::mach_header);
1431 Load.Ptr = getPtr(this, HeaderSize);
1432 Load.C = getStruct<MachO::load_command>(this, Load.Ptr);
1436 MachOObjectFile::LoadCommandInfo
1437 MachOObjectFile::getNextLoadCommandInfo(const LoadCommandInfo &L) const {
1438 MachOObjectFile::LoadCommandInfo Next;
1439 Next.Ptr = L.Ptr + L.C.cmdsize;
1440 Next.C = getStruct<MachO::load_command>(this, Next.Ptr);
1444 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
1445 return getStruct<MachO::section>(this, Sections[DRI.d.a]);
1448 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
1449 return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
1452 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
1453 unsigned Index) const {
1454 const char *Sec = getSectionPtr(this, L, Index);
1455 return getStruct<MachO::section>(this, Sec);
1458 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
1459 unsigned Index) const {
1460 const char *Sec = getSectionPtr(this, L, Index);
1461 return getStruct<MachO::section_64>(this, Sec);
1465 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
1466 const char *P = reinterpret_cast<const char *>(DRI.p);
1467 return getStruct<MachO::nlist>(this, P);
1471 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
1472 const char *P = reinterpret_cast<const char *>(DRI.p);
1473 return getStruct<MachO::nlist_64>(this, P);
1476 MachO::linkedit_data_command
1477 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
1478 return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
1481 MachO::segment_command
1482 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
1483 return getStruct<MachO::segment_command>(this, L.Ptr);
1486 MachO::segment_command_64
1487 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
1488 return getStruct<MachO::segment_command_64>(this, L.Ptr);
1491 MachO::linker_options_command
1492 MachOObjectFile::getLinkerOptionsLoadCommand(const LoadCommandInfo &L) const {
1493 return getStruct<MachO::linker_options_command>(this, L.Ptr);
1496 MachO::version_min_command
1497 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
1498 return getStruct<MachO::version_min_command>(this, L.Ptr);
1501 MachO::any_relocation_info
1502 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
1507 MachO::section_64 Sect = getSection64(Sec);
1508 Offset = Sect.reloff;
1510 MachO::section Sect = getSection(Sec);
1511 Offset = Sect.reloff;
1514 auto P = reinterpret_cast<const MachO::any_relocation_info *>(
1515 getPtr(this, Offset)) + Rel.d.b;
1516 return getStruct<MachO::any_relocation_info>(
1517 this, reinterpret_cast<const char *>(P));
1520 MachO::data_in_code_entry
1521 MachOObjectFile::getDice(DataRefImpl Rel) const {
1522 const char *P = reinterpret_cast<const char *>(Rel.p);
1523 return getStruct<MachO::data_in_code_entry>(this, P);
1526 MachO::mach_header MachOObjectFile::getHeader() const {
1527 return getStruct<MachO::mach_header>(this, getPtr(this, 0));
1530 MachO::mach_header_64 MachOObjectFile::getHeader64() const {
1531 return getStruct<MachO::mach_header_64>(this, getPtr(this, 0));
1534 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
1535 const MachO::dysymtab_command &DLC,
1536 unsigned Index) const {
1537 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
1538 return getStruct<uint32_t>(this, getPtr(this, Offset));
1541 MachO::data_in_code_entry
1542 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
1543 unsigned Index) const {
1544 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
1545 return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
1548 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
1549 return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
1552 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
1553 return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
1556 MachO::linkedit_data_command
1557 MachOObjectFile::getDataInCodeLoadCommand() const {
1558 if (DataInCodeLoadCmd)
1559 return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
1561 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
1562 MachO::linkedit_data_command Cmd;
1563 Cmd.cmd = MachO::LC_DATA_IN_CODE;
1564 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
1570 StringRef MachOObjectFile::getStringTableData() const {
1571 MachO::symtab_command S = getSymtabLoadCommand();
1572 return getData().substr(S.stroff, S.strsize);
1575 bool MachOObjectFile::is64Bit() const {
1576 return getType() == getMachOType(false, true) ||
1577 getType() == getMachOType(true, true);
1580 void MachOObjectFile::ReadULEB128s(uint64_t Index,
1581 SmallVectorImpl<uint64_t> &Out) const {
1582 DataExtractor extractor(ObjectFile::getData(), true, 0);
1584 uint32_t offset = Index;
1586 while (uint64_t delta = extractor.getULEB128(&offset)) {
1588 Out.push_back(data);
1592 ErrorOr<ObjectFile *> ObjectFile::createMachOObjectFile(MemoryBuffer *Buffer,
1594 StringRef Magic = Buffer->getBuffer().slice(0, 4);
1596 std::unique_ptr<MachOObjectFile> Ret;
1597 if (Magic == "\xFE\xED\xFA\xCE")
1598 Ret.reset(new MachOObjectFile(Buffer, false, false, EC, BufferOwned));
1599 else if (Magic == "\xCE\xFA\xED\xFE")
1600 Ret.reset(new MachOObjectFile(Buffer, true, false, EC, BufferOwned));
1601 else if (Magic == "\xFE\xED\xFA\xCF")
1602 Ret.reset(new MachOObjectFile(Buffer, false, true, EC, BufferOwned));
1603 else if (Magic == "\xCF\xFA\xED\xFE")
1604 Ret.reset(new MachOObjectFile(Buffer, true, true, EC, BufferOwned));
1607 return object_error::parse_failed;
1612 return Ret.release();
1615 } // end namespace object
1616 } // end namespace llvm