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(NULL), DysymtabLoadCmd(NULL), DataInCodeLoadCmd(NULL) {
424 uint32_t LoadCommandCount = this->getHeader().ncmds;
425 MachO::LoadCommandType SegmentLoadType = is64Bit() ?
426 MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT;
428 MachOObjectFile::LoadCommandInfo Load = getFirstLoadCommandInfo();
429 for (unsigned I = 0; ; ++I) {
430 if (Load.C.cmd == MachO::LC_SYMTAB) {
431 assert(!SymtabLoadCmd && "Multiple symbol tables");
432 SymtabLoadCmd = Load.Ptr;
433 } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
434 assert(!DysymtabLoadCmd && "Multiple dynamic symbol tables");
435 DysymtabLoadCmd = Load.Ptr;
436 } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
437 assert(!DataInCodeLoadCmd && "Multiple data in code tables");
438 DataInCodeLoadCmd = Load.Ptr;
439 } else if (Load.C.cmd == SegmentLoadType) {
440 uint32_t NumSections = getSegmentLoadCommandNumSections(this, Load);
441 for (unsigned J = 0; J < NumSections; ++J) {
442 const char *Sec = getSectionPtr(this, Load, J);
443 Sections.push_back(Sec);
447 if (I == LoadCommandCount - 1)
450 Load = getNextLoadCommandInfo(Load);
454 void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
455 unsigned SymbolTableEntrySize = is64Bit() ?
456 sizeof(MachO::nlist_64) :
457 sizeof(MachO::nlist);
458 Symb.p += SymbolTableEntrySize;
461 error_code MachOObjectFile::getSymbolName(DataRefImpl Symb,
462 StringRef &Res) const {
463 StringRef StringTable = getStringTableData();
464 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
465 const char *Start = &StringTable.data()[Entry.n_strx];
466 Res = StringRef(Start);
467 return object_error::success;
470 error_code MachOObjectFile::getSymbolAddress(DataRefImpl Symb,
471 uint64_t &Res) const {
473 MachO::nlist_64 Entry = getSymbol64TableEntry(Symb);
476 MachO::nlist Entry = getSymbolTableEntry(Symb);
479 return object_error::success;
482 error_code MachOObjectFile::getSymbolAlignment(DataRefImpl DRI,
483 uint32_t &Result) const {
484 uint32_t flags = getSymbolFlags(DRI);
485 if (flags & SymbolRef::SF_Common) {
486 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
487 Result = 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
491 return object_error::success;
494 error_code MachOObjectFile::getSymbolSize(DataRefImpl DRI,
495 uint64_t &Result) const {
496 uint64_t BeginOffset;
497 uint64_t EndOffset = 0;
498 uint8_t SectionIndex;
500 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
502 getSymbolAddress(DRI, Value);
506 SectionIndex = Entry.n_sect;
508 uint32_t flags = getSymbolFlags(DRI);
509 if (flags & SymbolRef::SF_Common)
512 Result = UnknownAddressOrSize;
513 return object_error::success;
515 // Unfortunately symbols are unsorted so we need to touch all
516 // symbols from load command
517 for (const SymbolRef &Symbol : symbols()) {
518 DataRefImpl DRI = Symbol.getRawDataRefImpl();
519 Entry = getSymbolTableEntryBase(this, DRI);
520 getSymbolAddress(DRI, Value);
521 if (Entry.n_sect == SectionIndex && Value > BeginOffset)
522 if (!EndOffset || Value < EndOffset)
528 Sec.d.a = SectionIndex-1;
529 getSectionSize(Sec, Size);
530 getSectionAddress(Sec, EndOffset);
533 Result = EndOffset - BeginOffset;
534 return object_error::success;
537 error_code MachOObjectFile::getSymbolType(DataRefImpl Symb,
538 SymbolRef::Type &Res) const {
539 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
540 uint8_t n_type = Entry.n_type;
542 Res = SymbolRef::ST_Other;
544 // If this is a STAB debugging symbol, we can do nothing more.
545 if (n_type & MachO::N_STAB) {
546 Res = SymbolRef::ST_Debug;
547 return object_error::success;
550 switch (n_type & MachO::N_TYPE) {
552 Res = SymbolRef::ST_Unknown;
555 Res = SymbolRef::ST_Function;
558 return object_error::success;
561 uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
562 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
564 uint8_t MachOType = Entry.n_type;
565 uint16_t MachOFlags = Entry.n_desc;
567 uint32_t Result = SymbolRef::SF_None;
569 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF)
570 Result |= SymbolRef::SF_Undefined;
572 if (MachOType & MachO::N_STAB)
573 Result |= SymbolRef::SF_FormatSpecific;
575 if (MachOType & MachO::N_EXT) {
576 Result |= SymbolRef::SF_Global;
577 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
579 getSymbolAddress(DRI, Value);
581 Result |= SymbolRef::SF_Common;
585 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
586 Result |= SymbolRef::SF_Weak;
588 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
589 Result |= SymbolRef::SF_Absolute;
595 MachOObjectFile::getSymbolSection(DataRefImpl Symb,
596 section_iterator &Res) const {
597 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
598 uint8_t index = Entry.n_sect;
605 Res = section_iterator(SectionRef(DRI, this));
608 return object_error::success;
611 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
616 MachOObjectFile::getSectionName(DataRefImpl Sec, StringRef &Result) const {
617 ArrayRef<char> Raw = getSectionRawName(Sec);
618 Result = parseSegmentOrSectionName(Raw.data());
619 return object_error::success;
623 MachOObjectFile::getSectionAddress(DataRefImpl Sec, uint64_t &Res) const {
625 MachO::section_64 Sect = getSection64(Sec);
628 MachO::section Sect = getSection(Sec);
631 return object_error::success;
635 MachOObjectFile::getSectionSize(DataRefImpl Sec, uint64_t &Res) const {
637 MachO::section_64 Sect = getSection64(Sec);
640 MachO::section Sect = getSection(Sec);
644 return object_error::success;
648 MachOObjectFile::getSectionContents(DataRefImpl Sec, StringRef &Res) const {
653 MachO::section_64 Sect = getSection64(Sec);
654 Offset = Sect.offset;
657 MachO::section Sect = getSection(Sec);
658 Offset = Sect.offset;
662 Res = this->getData().substr(Offset, Size);
663 return object_error::success;
667 MachOObjectFile::getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const {
670 MachO::section_64 Sect = getSection64(Sec);
673 MachO::section Sect = getSection(Sec);
677 Res = uint64_t(1) << Align;
678 return object_error::success;
682 MachOObjectFile::isSectionText(DataRefImpl Sec, bool &Res) const {
683 uint32_t Flags = getSectionFlags(this, Sec);
684 Res = Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
685 return object_error::success;
688 error_code MachOObjectFile::isSectionData(DataRefImpl DRI, bool &Result) const {
689 // FIXME: Unimplemented.
691 return object_error::success;
694 error_code MachOObjectFile::isSectionBSS(DataRefImpl DRI, bool &Result) const {
695 // FIXME: Unimplemented.
697 return object_error::success;
701 MachOObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
702 bool &Result) const {
703 // FIXME: Unimplemented.
705 return object_error::success;
708 error_code MachOObjectFile::isSectionVirtual(DataRefImpl Sec,
709 bool &Result) const {
710 // FIXME: Unimplemented.
712 return object_error::success;
716 MachOObjectFile::isSectionZeroInit(DataRefImpl Sec, bool &Res) const {
717 uint32_t Flags = getSectionFlags(this, Sec);
718 unsigned SectionType = Flags & MachO::SECTION_TYPE;
719 Res = SectionType == MachO::S_ZEROFILL ||
720 SectionType == MachO::S_GB_ZEROFILL;
721 return object_error::success;
724 error_code MachOObjectFile::isSectionReadOnlyData(DataRefImpl Sec,
725 bool &Result) const {
726 // Consider using the code from isSectionText to look for __const sections.
727 // Alternately, emit S_ATTR_PURE_INSTRUCTIONS and/or S_ATTR_SOME_INSTRUCTIONS
728 // to use section attributes to distinguish code from data.
730 // FIXME: Unimplemented.
732 return object_error::success;
736 MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
737 bool &Result) const {
739 this->getSymbolType(Symb, ST);
740 if (ST == SymbolRef::ST_Unknown) {
742 return object_error::success;
745 uint64_t SectBegin, SectEnd;
746 getSectionAddress(Sec, SectBegin);
747 getSectionSize(Sec, SectEnd);
748 SectEnd += SectBegin;
751 getSymbolAddress(Symb, SymAddr);
752 Result = (SymAddr >= SectBegin) && (SymAddr < SectEnd);
754 return object_error::success;
757 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
760 MachO::section_64 Sect = getSection64(Sec);
761 Offset = Sect.reloff;
763 MachO::section Sect = getSection(Sec);
764 Offset = Sect.reloff;
768 Ret.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
769 return relocation_iterator(RelocationRef(Ret, this));
773 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
777 MachO::section_64 Sect = getSection64(Sec);
778 Offset = Sect.reloff;
781 MachO::section Sect = getSection(Sec);
782 Offset = Sect.reloff;
786 const MachO::any_relocation_info *P =
787 reinterpret_cast<const MachO::any_relocation_info *>(getPtr(this, Offset));
790 Ret.p = reinterpret_cast<uintptr_t>(P + Num);
791 return relocation_iterator(RelocationRef(Ret, this));
794 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
795 const MachO::any_relocation_info *P =
796 reinterpret_cast<const MachO::any_relocation_info *>(Rel.p);
797 Rel.p = reinterpret_cast<uintptr_t>(P + 1);
801 MachOObjectFile::getRelocationAddress(DataRefImpl Rel, uint64_t &Res) const {
802 report_fatal_error("getRelocationAddress not implemented in MachOObjectFile");
805 error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
806 uint64_t &Res) const {
807 MachO::any_relocation_info RE = getRelocation(Rel);
808 Res = getAnyRelocationAddress(RE);
809 return object_error::success;
813 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
814 MachO::any_relocation_info RE = getRelocation(Rel);
815 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
816 bool isExtern = getPlainRelocationExternal(RE);
820 MachO::symtab_command S = getSymtabLoadCommand();
821 unsigned SymbolTableEntrySize = is64Bit() ?
822 sizeof(MachO::nlist_64) :
823 sizeof(MachO::nlist);
824 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
826 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
827 return symbol_iterator(SymbolRef(Sym, this));
830 error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
831 uint64_t &Res) const {
832 MachO::any_relocation_info RE = getRelocation(Rel);
833 Res = getAnyRelocationType(RE);
834 return object_error::success;
838 MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
839 SmallVectorImpl<char> &Result) const {
842 getRelocationType(Rel, RType);
844 unsigned Arch = this->getArch();
848 static const char *const Table[] = {
849 "GENERIC_RELOC_VANILLA",
850 "GENERIC_RELOC_PAIR",
851 "GENERIC_RELOC_SECTDIFF",
852 "GENERIC_RELOC_PB_LA_PTR",
853 "GENERIC_RELOC_LOCAL_SECTDIFF",
854 "GENERIC_RELOC_TLV" };
862 case Triple::x86_64: {
863 static const char *const Table[] = {
864 "X86_64_RELOC_UNSIGNED",
865 "X86_64_RELOC_SIGNED",
866 "X86_64_RELOC_BRANCH",
867 "X86_64_RELOC_GOT_LOAD",
869 "X86_64_RELOC_SUBTRACTOR",
870 "X86_64_RELOC_SIGNED_1",
871 "X86_64_RELOC_SIGNED_2",
872 "X86_64_RELOC_SIGNED_4",
873 "X86_64_RELOC_TLV" };
882 static const char *const Table[] = {
885 "ARM_RELOC_SECTDIFF",
886 "ARM_RELOC_LOCAL_SECTDIFF",
887 "ARM_RELOC_PB_LA_PTR",
889 "ARM_THUMB_RELOC_BR22",
890 "ARM_THUMB_32BIT_BRANCH",
892 "ARM_RELOC_HALF_SECTDIFF" };
901 case Triple::aarch64: {
902 static const char *const Table[] = {
903 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
904 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
905 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
906 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
907 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
911 if (RType >= array_lengthof(Table))
918 static const char *const Table[] = {
927 "PPC_RELOC_SECTDIFF",
928 "PPC_RELOC_PB_LA_PTR",
929 "PPC_RELOC_HI16_SECTDIFF",
930 "PPC_RELOC_LO16_SECTDIFF",
931 "PPC_RELOC_HA16_SECTDIFF",
933 "PPC_RELOC_LO14_SECTDIFF",
934 "PPC_RELOC_LOCAL_SECTDIFF" };
942 case Triple::UnknownArch:
946 Result.append(res.begin(), res.end());
947 return object_error::success;
951 MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
952 SmallVectorImpl<char> &Result) const {
953 MachO::any_relocation_info RE = getRelocation(Rel);
955 unsigned Arch = this->getArch();
958 raw_string_ostream fmt(fmtbuf);
959 unsigned Type = this->getAnyRelocationType(RE);
960 bool IsPCRel = this->getAnyRelocationPCRel(RE);
962 // Determine any addends that should be displayed with the relocation.
963 // These require decoding the relocation type, which is triple-specific.
965 // X86_64 has entirely custom relocation types.
966 if (Arch == Triple::x86_64) {
967 bool isPCRel = getAnyRelocationPCRel(RE);
970 case MachO::X86_64_RELOC_GOT_LOAD:
971 case MachO::X86_64_RELOC_GOT: {
972 printRelocationTargetName(this, RE, fmt);
974 if (isPCRel) fmt << "PCREL";
977 case MachO::X86_64_RELOC_SUBTRACTOR: {
978 DataRefImpl RelNext = Rel;
979 moveRelocationNext(RelNext);
980 MachO::any_relocation_info RENext = getRelocation(RelNext);
982 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
983 // X86_64_RELOC_UNSIGNED.
984 // NOTE: Scattered relocations don't exist on x86_64.
985 unsigned RType = getAnyRelocationType(RENext);
986 if (RType != MachO::X86_64_RELOC_UNSIGNED)
987 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
988 "X86_64_RELOC_SUBTRACTOR.");
990 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
991 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
992 printRelocationTargetName(this, RENext, fmt);
994 printRelocationTargetName(this, RE, fmt);
997 case MachO::X86_64_RELOC_TLV:
998 printRelocationTargetName(this, RE, fmt);
1000 if (isPCRel) fmt << "P";
1002 case MachO::X86_64_RELOC_SIGNED_1:
1003 printRelocationTargetName(this, RE, fmt);
1006 case MachO::X86_64_RELOC_SIGNED_2:
1007 printRelocationTargetName(this, RE, fmt);
1010 case MachO::X86_64_RELOC_SIGNED_4:
1011 printRelocationTargetName(this, RE, fmt);
1015 printRelocationTargetName(this, RE, fmt);
1018 // X86 and ARM share some relocation types in common.
1019 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
1020 Arch == Triple::ppc) {
1021 // Generic relocation types...
1023 case MachO::GENERIC_RELOC_PAIR: // prints no info
1024 return object_error::success;
1025 case MachO::GENERIC_RELOC_SECTDIFF: {
1026 DataRefImpl RelNext = Rel;
1027 moveRelocationNext(RelNext);
1028 MachO::any_relocation_info RENext = getRelocation(RelNext);
1030 // X86 sect diff's must be followed by a relocation of type
1031 // GENERIC_RELOC_PAIR.
1032 unsigned RType = getAnyRelocationType(RENext);
1034 if (RType != MachO::GENERIC_RELOC_PAIR)
1035 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1036 "GENERIC_RELOC_SECTDIFF.");
1038 printRelocationTargetName(this, RE, fmt);
1040 printRelocationTargetName(this, RENext, fmt);
1045 if (Arch == Triple::x86 || Arch == Triple::ppc) {
1047 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1048 DataRefImpl RelNext = Rel;
1049 moveRelocationNext(RelNext);
1050 MachO::any_relocation_info RENext = getRelocation(RelNext);
1052 // X86 sect diff's must be followed by a relocation of type
1053 // GENERIC_RELOC_PAIR.
1054 unsigned RType = getAnyRelocationType(RENext);
1055 if (RType != MachO::GENERIC_RELOC_PAIR)
1056 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1057 "GENERIC_RELOC_LOCAL_SECTDIFF.");
1059 printRelocationTargetName(this, RE, fmt);
1061 printRelocationTargetName(this, RENext, fmt);
1064 case MachO::GENERIC_RELOC_TLV: {
1065 printRelocationTargetName(this, RE, fmt);
1067 if (IsPCRel) fmt << "P";
1071 printRelocationTargetName(this, RE, fmt);
1073 } else { // ARM-specific relocations
1075 case MachO::ARM_RELOC_HALF:
1076 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1077 // Half relocations steal a bit from the length field to encode
1078 // whether this is an upper16 or a lower16 relocation.
1079 bool isUpper = getAnyRelocationLength(RE) >> 1;
1082 fmt << ":upper16:(";
1084 fmt << ":lower16:(";
1085 printRelocationTargetName(this, RE, fmt);
1087 DataRefImpl RelNext = Rel;
1088 moveRelocationNext(RelNext);
1089 MachO::any_relocation_info RENext = getRelocation(RelNext);
1091 // ARM half relocs must be followed by a relocation of type
1093 unsigned RType = getAnyRelocationType(RENext);
1094 if (RType != MachO::ARM_RELOC_PAIR)
1095 report_fatal_error("Expected ARM_RELOC_PAIR after "
1098 // NOTE: The half of the target virtual address is stashed in the
1099 // address field of the secondary relocation, but we can't reverse
1100 // engineer the constant offset from it without decoding the movw/movt
1101 // instruction to find the other half in its immediate field.
1103 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1104 // symbol/section pointer of the follow-on relocation.
1105 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1107 printRelocationTargetName(this, RENext, fmt);
1114 printRelocationTargetName(this, RE, fmt);
1119 printRelocationTargetName(this, RE, fmt);
1122 Result.append(fmtbuf.begin(), fmtbuf.end());
1123 return object_error::success;
1127 MachOObjectFile::getRelocationHidden(DataRefImpl Rel, bool &Result) const {
1128 unsigned Arch = getArch();
1130 getRelocationType(Rel, Type);
1134 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1135 // is always hidden.
1136 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1137 if (Type == MachO::GENERIC_RELOC_PAIR) Result = true;
1138 } else if (Arch == Triple::x86_64) {
1139 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1140 // an X86_64_RELOC_SUBTRACTOR.
1141 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1142 DataRefImpl RelPrev = Rel;
1145 getRelocationType(RelPrev, PrevType);
1146 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1151 return object_error::success;
1154 error_code MachOObjectFile::getLibraryNext(DataRefImpl LibData,
1155 LibraryRef &Res) const {
1156 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1159 error_code MachOObjectFile::getLibraryPath(DataRefImpl LibData,
1160 StringRef &Res) const {
1161 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1164 basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
1167 return basic_symbol_iterator(SymbolRef(DRI, this));
1169 MachO::symtab_command Symtab = getSymtabLoadCommand();
1170 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1171 return basic_symbol_iterator(SymbolRef(DRI, this));
1174 basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
1177 return basic_symbol_iterator(SymbolRef(DRI, this));
1179 MachO::symtab_command Symtab = getSymtabLoadCommand();
1180 unsigned SymbolTableEntrySize = is64Bit() ?
1181 sizeof(MachO::nlist_64) :
1182 sizeof(MachO::nlist);
1183 unsigned Offset = Symtab.symoff +
1184 Symtab.nsyms * SymbolTableEntrySize;
1185 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1186 return basic_symbol_iterator(SymbolRef(DRI, this));
1189 section_iterator MachOObjectFile::section_begin() const {
1191 return section_iterator(SectionRef(DRI, this));
1194 section_iterator MachOObjectFile::section_end() const {
1196 DRI.d.a = Sections.size();
1197 return section_iterator(SectionRef(DRI, this));
1200 library_iterator MachOObjectFile::needed_library_begin() const {
1202 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1205 library_iterator MachOObjectFile::needed_library_end() const {
1207 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1210 uint8_t MachOObjectFile::getBytesInAddress() const {
1211 return is64Bit() ? 8 : 4;
1214 StringRef MachOObjectFile::getFileFormatName() const {
1215 unsigned CPUType = getCPUType(this);
1218 case llvm::MachO::CPU_TYPE_I386:
1219 return "Mach-O 32-bit i386";
1220 case llvm::MachO::CPU_TYPE_ARM:
1221 return "Mach-O arm";
1222 case llvm::MachO::CPU_TYPE_POWERPC:
1223 return "Mach-O 32-bit ppc";
1225 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64) == 0 &&
1226 "64-bit object file when we're not 64-bit?");
1227 return "Mach-O 32-bit unknown";
1231 // Make sure the cpu type has the correct mask.
1232 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64)
1233 == llvm::MachO::CPU_ARCH_ABI64 &&
1234 "32-bit object file when we're 64-bit?");
1237 case llvm::MachO::CPU_TYPE_X86_64:
1238 return "Mach-O 64-bit x86-64";
1239 case llvm::MachO::CPU_TYPE_ARM64:
1240 return "Mach-O arm64";
1241 case llvm::MachO::CPU_TYPE_POWERPC64:
1242 return "Mach-O 64-bit ppc64";
1244 return "Mach-O 64-bit unknown";
1248 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1250 case llvm::MachO::CPU_TYPE_I386:
1252 case llvm::MachO::CPU_TYPE_X86_64:
1253 return Triple::x86_64;
1254 case llvm::MachO::CPU_TYPE_ARM:
1256 case llvm::MachO::CPU_TYPE_ARM64:
1257 return Triple::arm64;
1258 case llvm::MachO::CPU_TYPE_POWERPC:
1260 case llvm::MachO::CPU_TYPE_POWERPC64:
1261 return Triple::ppc64;
1263 return Triple::UnknownArch;
1267 unsigned MachOObjectFile::getArch() const {
1268 return getArch(getCPUType(this));
1271 StringRef MachOObjectFile::getLoadName() const {
1273 report_fatal_error("get_load_name() unimplemented in MachOObjectFile");
1276 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
1279 return section_rel_begin(DRI);
1282 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
1285 return section_rel_end(DRI);
1288 dice_iterator MachOObjectFile::begin_dices() const {
1290 if (!DataInCodeLoadCmd)
1291 return dice_iterator(DiceRef(DRI, this));
1293 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1294 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
1295 return dice_iterator(DiceRef(DRI, this));
1298 dice_iterator MachOObjectFile::end_dices() const {
1300 if (!DataInCodeLoadCmd)
1301 return dice_iterator(DiceRef(DRI, this));
1303 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1304 unsigned Offset = DicLC.dataoff + DicLC.datasize;
1305 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1306 return dice_iterator(DiceRef(DRI, this));
1310 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1311 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1312 return parseSegmentOrSectionName(Raw.data());
1316 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
1317 const section_base *Base =
1318 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1319 return ArrayRef<char>(Base->sectname);
1323 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
1324 const section_base *Base =
1325 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1326 return ArrayRef<char>(Base->segname);
1330 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
1332 if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
1334 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
1337 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
1338 const MachO::any_relocation_info &RE) const {
1339 if (isLittleEndian())
1340 return RE.r_word1 & 0xffffff;
1341 return RE.r_word1 >> 8;
1344 bool MachOObjectFile::getPlainRelocationExternal(
1345 const MachO::any_relocation_info &RE) const {
1346 if (isLittleEndian())
1347 return (RE.r_word1 >> 27) & 1;
1348 return (RE.r_word1 >> 4) & 1;
1351 bool MachOObjectFile::getScatteredRelocationScattered(
1352 const MachO::any_relocation_info &RE) const {
1353 return RE.r_word0 >> 31;
1356 uint32_t MachOObjectFile::getScatteredRelocationValue(
1357 const MachO::any_relocation_info &RE) const {
1361 unsigned MachOObjectFile::getAnyRelocationAddress(
1362 const MachO::any_relocation_info &RE) const {
1363 if (isRelocationScattered(RE))
1364 return getScatteredRelocationAddress(RE);
1365 return getPlainRelocationAddress(RE);
1368 unsigned MachOObjectFile::getAnyRelocationPCRel(
1369 const MachO::any_relocation_info &RE) const {
1370 if (isRelocationScattered(RE))
1371 return getScatteredRelocationPCRel(this, RE);
1372 return getPlainRelocationPCRel(this, RE);
1375 unsigned MachOObjectFile::getAnyRelocationLength(
1376 const MachO::any_relocation_info &RE) const {
1377 if (isRelocationScattered(RE))
1378 return getScatteredRelocationLength(RE);
1379 return getPlainRelocationLength(this, RE);
1383 MachOObjectFile::getAnyRelocationType(
1384 const MachO::any_relocation_info &RE) const {
1385 if (isRelocationScattered(RE))
1386 return getScatteredRelocationType(RE);
1387 return getPlainRelocationType(this, RE);
1391 MachOObjectFile::getRelocationSection(
1392 const MachO::any_relocation_info &RE) const {
1393 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
1394 return *section_end();
1395 unsigned SecNum = getPlainRelocationSymbolNum(RE) - 1;
1398 return SectionRef(DRI, this);
1401 MachOObjectFile::LoadCommandInfo
1402 MachOObjectFile::getFirstLoadCommandInfo() const {
1403 MachOObjectFile::LoadCommandInfo Load;
1405 unsigned HeaderSize = is64Bit() ? sizeof(MachO::mach_header_64) :
1406 sizeof(MachO::mach_header);
1407 Load.Ptr = getPtr(this, HeaderSize);
1408 Load.C = getStruct<MachO::load_command>(this, Load.Ptr);
1412 MachOObjectFile::LoadCommandInfo
1413 MachOObjectFile::getNextLoadCommandInfo(const LoadCommandInfo &L) const {
1414 MachOObjectFile::LoadCommandInfo Next;
1415 Next.Ptr = L.Ptr + L.C.cmdsize;
1416 Next.C = getStruct<MachO::load_command>(this, Next.Ptr);
1420 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
1421 return getStruct<MachO::section>(this, Sections[DRI.d.a]);
1424 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
1425 return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
1428 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
1429 unsigned Index) const {
1430 const char *Sec = getSectionPtr(this, L, Index);
1431 return getStruct<MachO::section>(this, Sec);
1434 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
1435 unsigned Index) const {
1436 const char *Sec = getSectionPtr(this, L, Index);
1437 return getStruct<MachO::section_64>(this, Sec);
1441 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
1442 const char *P = reinterpret_cast<const char *>(DRI.p);
1443 return getStruct<MachO::nlist>(this, P);
1447 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
1448 const char *P = reinterpret_cast<const char *>(DRI.p);
1449 return getStruct<MachO::nlist_64>(this, P);
1452 MachO::linkedit_data_command
1453 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
1454 return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
1457 MachO::segment_command
1458 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
1459 return getStruct<MachO::segment_command>(this, L.Ptr);
1462 MachO::segment_command_64
1463 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
1464 return getStruct<MachO::segment_command_64>(this, L.Ptr);
1467 MachO::linker_options_command
1468 MachOObjectFile::getLinkerOptionsLoadCommand(const LoadCommandInfo &L) const {
1469 return getStruct<MachO::linker_options_command>(this, L.Ptr);
1472 MachO::version_min_command
1473 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
1474 return getStruct<MachO::version_min_command>(this, L.Ptr);
1477 MachO::any_relocation_info
1478 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
1479 const char *P = reinterpret_cast<const char *>(Rel.p);
1480 return getStruct<MachO::any_relocation_info>(this, P);
1483 MachO::data_in_code_entry
1484 MachOObjectFile::getDice(DataRefImpl Rel) const {
1485 const char *P = reinterpret_cast<const char *>(Rel.p);
1486 return getStruct<MachO::data_in_code_entry>(this, P);
1489 MachO::mach_header MachOObjectFile::getHeader() const {
1490 return getStruct<MachO::mach_header>(this, getPtr(this, 0));
1493 MachO::mach_header_64 MachOObjectFile::getHeader64() const {
1494 return getStruct<MachO::mach_header_64>(this, getPtr(this, 0));
1497 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
1498 const MachO::dysymtab_command &DLC,
1499 unsigned Index) const {
1500 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
1501 return getStruct<uint32_t>(this, getPtr(this, Offset));
1504 MachO::data_in_code_entry
1505 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
1506 unsigned Index) const {
1507 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
1508 return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
1511 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
1512 return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
1515 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
1516 return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
1519 MachO::linkedit_data_command
1520 MachOObjectFile::getDataInCodeLoadCommand() const {
1521 if (DataInCodeLoadCmd)
1522 return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
1524 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
1525 MachO::linkedit_data_command Cmd;
1526 Cmd.cmd = MachO::LC_DATA_IN_CODE;
1527 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
1533 StringRef MachOObjectFile::getStringTableData() const {
1534 MachO::symtab_command S = getSymtabLoadCommand();
1535 return getData().substr(S.stroff, S.strsize);
1538 bool MachOObjectFile::is64Bit() const {
1539 return getType() == getMachOType(false, true) ||
1540 getType() == getMachOType(true, true);
1543 void MachOObjectFile::ReadULEB128s(uint64_t Index,
1544 SmallVectorImpl<uint64_t> &Out) const {
1545 DataExtractor extractor(ObjectFile::getData(), true, 0);
1547 uint32_t offset = Index;
1549 while (uint64_t delta = extractor.getULEB128(&offset)) {
1551 Out.push_back(data);
1555 ErrorOr<ObjectFile *> ObjectFile::createMachOObjectFile(MemoryBuffer *Buffer,
1557 StringRef Magic = Buffer->getBuffer().slice(0, 4);
1559 std::unique_ptr<MachOObjectFile> Ret;
1560 if (Magic == "\xFE\xED\xFA\xCE")
1561 Ret.reset(new MachOObjectFile(Buffer, false, false, EC, BufferOwned));
1562 else if (Magic == "\xCE\xFA\xED\xFE")
1563 Ret.reset(new MachOObjectFile(Buffer, true, false, EC, BufferOwned));
1564 else if (Magic == "\xFE\xED\xFA\xCF")
1565 Ret.reset(new MachOObjectFile(Buffer, false, true, EC, BufferOwned));
1566 else if (Magic == "\xCF\xFA\xED\xFE")
1567 Ret.reset(new MachOObjectFile(Buffer, true, true, EC, BufferOwned));
1570 return object_error::parse_failed;
1575 return Ret.release();
1578 } // end namespace object
1579 } // end namespace llvm