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;
483 MachOObjectFile::getSymbolFileOffset(DataRefImpl Symb,
484 uint64_t &Res) const {
485 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
486 getSymbolAddress(Symb, Res);
490 SecRel.d.a = Entry.n_sect-1;
492 MachO::section_64 Sec = getSection64(SecRel);
493 Delta = Sec.offset - Sec.addr;
495 MachO::section Sec = getSection(SecRel);
496 Delta = Sec.offset - Sec.addr;
502 return object_error::success;
505 error_code MachOObjectFile::getSymbolAlignment(DataRefImpl DRI,
506 uint32_t &Result) const {
507 uint32_t flags = getSymbolFlags(DRI);
508 if (flags & SymbolRef::SF_Common) {
509 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
510 Result = 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
514 return object_error::success;
517 error_code MachOObjectFile::getSymbolSize(DataRefImpl DRI,
518 uint64_t &Result) const {
519 uint64_t BeginOffset;
520 uint64_t EndOffset = 0;
521 uint8_t SectionIndex;
523 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
525 getSymbolAddress(DRI, Value);
529 SectionIndex = Entry.n_sect;
531 uint32_t flags = getSymbolFlags(DRI);
532 if (flags & SymbolRef::SF_Common)
535 Result = UnknownAddressOrSize;
536 return object_error::success;
538 // Unfortunately symbols are unsorted so we need to touch all
539 // symbols from load command
540 for (const SymbolRef &Symbol : symbols()) {
541 DataRefImpl DRI = Symbol.getRawDataRefImpl();
542 Entry = getSymbolTableEntryBase(this, DRI);
543 getSymbolAddress(DRI, Value);
544 if (Entry.n_sect == SectionIndex && Value > BeginOffset)
545 if (!EndOffset || Value < EndOffset)
551 Sec.d.a = SectionIndex-1;
552 getSectionSize(Sec, Size);
553 getSectionAddress(Sec, EndOffset);
556 Result = EndOffset - BeginOffset;
557 return object_error::success;
560 error_code MachOObjectFile::getSymbolType(DataRefImpl Symb,
561 SymbolRef::Type &Res) const {
562 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
563 uint8_t n_type = Entry.n_type;
565 Res = SymbolRef::ST_Other;
567 // If this is a STAB debugging symbol, we can do nothing more.
568 if (n_type & MachO::N_STAB) {
569 Res = SymbolRef::ST_Debug;
570 return object_error::success;
573 switch (n_type & MachO::N_TYPE) {
575 Res = SymbolRef::ST_Unknown;
578 Res = SymbolRef::ST_Function;
581 return object_error::success;
584 uint32_t MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
585 nlist_base Entry = getSymbolTableEntryBase(this, DRI);
587 uint8_t MachOType = Entry.n_type;
588 uint16_t MachOFlags = Entry.n_desc;
590 uint32_t Result = SymbolRef::SF_None;
592 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF)
593 Result |= SymbolRef::SF_Undefined;
595 if (MachOType & MachO::N_STAB)
596 Result |= SymbolRef::SF_FormatSpecific;
598 if (MachOType & MachO::N_EXT) {
599 Result |= SymbolRef::SF_Global;
600 if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
602 getSymbolAddress(DRI, Value);
604 Result |= SymbolRef::SF_Common;
608 if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
609 Result |= SymbolRef::SF_Weak;
611 if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
612 Result |= SymbolRef::SF_Absolute;
618 MachOObjectFile::getSymbolSection(DataRefImpl Symb,
619 section_iterator &Res) const {
620 nlist_base Entry = getSymbolTableEntryBase(this, Symb);
621 uint8_t index = Entry.n_sect;
628 Res = section_iterator(SectionRef(DRI, this));
631 return object_error::success;
634 error_code MachOObjectFile::getSymbolValue(DataRefImpl Symb,
635 uint64_t &Val) const {
636 report_fatal_error("getSymbolValue unimplemented in MachOObjectFile");
639 void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
644 MachOObjectFile::getSectionName(DataRefImpl Sec, StringRef &Result) const {
645 ArrayRef<char> Raw = getSectionRawName(Sec);
646 Result = parseSegmentOrSectionName(Raw.data());
647 return object_error::success;
651 MachOObjectFile::getSectionAddress(DataRefImpl Sec, uint64_t &Res) const {
653 MachO::section_64 Sect = getSection64(Sec);
656 MachO::section Sect = getSection(Sec);
659 return object_error::success;
663 MachOObjectFile::getSectionSize(DataRefImpl Sec, uint64_t &Res) const {
665 MachO::section_64 Sect = getSection64(Sec);
668 MachO::section Sect = getSection(Sec);
672 return object_error::success;
676 MachOObjectFile::getSectionContents(DataRefImpl Sec, StringRef &Res) const {
681 MachO::section_64 Sect = getSection64(Sec);
682 Offset = Sect.offset;
685 MachO::section Sect = getSection(Sec);
686 Offset = Sect.offset;
690 Res = this->getData().substr(Offset, Size);
691 return object_error::success;
695 MachOObjectFile::getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const {
698 MachO::section_64 Sect = getSection64(Sec);
701 MachO::section Sect = getSection(Sec);
705 Res = uint64_t(1) << Align;
706 return object_error::success;
710 MachOObjectFile::isSectionText(DataRefImpl Sec, bool &Res) const {
711 uint32_t Flags = getSectionFlags(this, Sec);
712 Res = Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
713 return object_error::success;
716 error_code MachOObjectFile::isSectionData(DataRefImpl DRI, bool &Result) const {
717 // FIXME: Unimplemented.
719 return object_error::success;
722 error_code MachOObjectFile::isSectionBSS(DataRefImpl DRI, bool &Result) const {
723 // FIXME: Unimplemented.
725 return object_error::success;
729 MachOObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
730 bool &Result) const {
731 // FIXME: Unimplemented.
733 return object_error::success;
736 error_code MachOObjectFile::isSectionVirtual(DataRefImpl Sec,
737 bool &Result) const {
738 // FIXME: Unimplemented.
740 return object_error::success;
744 MachOObjectFile::isSectionZeroInit(DataRefImpl Sec, bool &Res) const {
745 uint32_t Flags = getSectionFlags(this, Sec);
746 unsigned SectionType = Flags & MachO::SECTION_TYPE;
747 Res = SectionType == MachO::S_ZEROFILL ||
748 SectionType == MachO::S_GB_ZEROFILL;
749 return object_error::success;
752 error_code MachOObjectFile::isSectionReadOnlyData(DataRefImpl Sec,
753 bool &Result) const {
754 // Consider using the code from isSectionText to look for __const sections.
755 // Alternately, emit S_ATTR_PURE_INSTRUCTIONS and/or S_ATTR_SOME_INSTRUCTIONS
756 // to use section attributes to distinguish code from data.
758 // FIXME: Unimplemented.
760 return object_error::success;
764 MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
765 bool &Result) const {
767 this->getSymbolType(Symb, ST);
768 if (ST == SymbolRef::ST_Unknown) {
770 return object_error::success;
773 uint64_t SectBegin, SectEnd;
774 getSectionAddress(Sec, SectBegin);
775 getSectionSize(Sec, SectEnd);
776 SectEnd += SectBegin;
779 getSymbolAddress(Symb, SymAddr);
780 Result = (SymAddr >= SectBegin) && (SymAddr < SectEnd);
782 return object_error::success;
785 relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
788 MachO::section_64 Sect = getSection64(Sec);
789 Offset = Sect.reloff;
791 MachO::section Sect = getSection(Sec);
792 Offset = Sect.reloff;
796 Ret.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
797 return relocation_iterator(RelocationRef(Ret, this));
801 MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
805 MachO::section_64 Sect = getSection64(Sec);
806 Offset = Sect.reloff;
809 MachO::section Sect = getSection(Sec);
810 Offset = Sect.reloff;
814 const MachO::any_relocation_info *P =
815 reinterpret_cast<const MachO::any_relocation_info *>(getPtr(this, Offset));
818 Ret.p = reinterpret_cast<uintptr_t>(P + Num);
819 return relocation_iterator(RelocationRef(Ret, this));
822 bool MachOObjectFile::section_rel_empty(DataRefImpl Sec) const {
824 MachO::section_64 Sect = getSection64(Sec);
825 return Sect.nreloc == 0;
827 MachO::section Sect = getSection(Sec);
828 return Sect.nreloc == 0;
832 void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
833 const MachO::any_relocation_info *P =
834 reinterpret_cast<const MachO::any_relocation_info *>(Rel.p);
835 Rel.p = reinterpret_cast<uintptr_t>(P + 1);
839 MachOObjectFile::getRelocationAddress(DataRefImpl Rel, uint64_t &Res) const {
840 report_fatal_error("getRelocationAddress not implemented in MachOObjectFile");
843 error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
844 uint64_t &Res) const {
845 MachO::any_relocation_info RE = getRelocation(Rel);
846 Res = getAnyRelocationAddress(RE);
847 return object_error::success;
851 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
852 MachO::any_relocation_info RE = getRelocation(Rel);
853 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
854 bool isExtern = getPlainRelocationExternal(RE);
858 MachO::symtab_command S = getSymtabLoadCommand();
859 unsigned SymbolTableEntrySize = is64Bit() ?
860 sizeof(MachO::nlist_64) :
861 sizeof(MachO::nlist);
862 uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
864 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
865 return symbol_iterator(SymbolRef(Sym, this));
868 error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
869 uint64_t &Res) const {
870 MachO::any_relocation_info RE = getRelocation(Rel);
871 Res = getAnyRelocationType(RE);
872 return object_error::success;
876 MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
877 SmallVectorImpl<char> &Result) const {
880 getRelocationType(Rel, RType);
882 unsigned Arch = this->getArch();
886 static const char *const Table[] = {
887 "GENERIC_RELOC_VANILLA",
888 "GENERIC_RELOC_PAIR",
889 "GENERIC_RELOC_SECTDIFF",
890 "GENERIC_RELOC_PB_LA_PTR",
891 "GENERIC_RELOC_LOCAL_SECTDIFF",
892 "GENERIC_RELOC_TLV" };
900 case Triple::x86_64: {
901 static const char *const Table[] = {
902 "X86_64_RELOC_UNSIGNED",
903 "X86_64_RELOC_SIGNED",
904 "X86_64_RELOC_BRANCH",
905 "X86_64_RELOC_GOT_LOAD",
907 "X86_64_RELOC_SUBTRACTOR",
908 "X86_64_RELOC_SIGNED_1",
909 "X86_64_RELOC_SIGNED_2",
910 "X86_64_RELOC_SIGNED_4",
911 "X86_64_RELOC_TLV" };
920 static const char *const Table[] = {
923 "ARM_RELOC_SECTDIFF",
924 "ARM_RELOC_LOCAL_SECTDIFF",
925 "ARM_RELOC_PB_LA_PTR",
927 "ARM_THUMB_RELOC_BR22",
928 "ARM_THUMB_32BIT_BRANCH",
930 "ARM_RELOC_HALF_SECTDIFF" };
939 case Triple::aarch64: {
940 static const char *const Table[] = {
941 "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
942 "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
943 "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
944 "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
945 "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
949 if (RType >= array_lengthof(Table))
956 static const char *const Table[] = {
965 "PPC_RELOC_SECTDIFF",
966 "PPC_RELOC_PB_LA_PTR",
967 "PPC_RELOC_HI16_SECTDIFF",
968 "PPC_RELOC_LO16_SECTDIFF",
969 "PPC_RELOC_HA16_SECTDIFF",
971 "PPC_RELOC_LO14_SECTDIFF",
972 "PPC_RELOC_LOCAL_SECTDIFF" };
980 case Triple::UnknownArch:
984 Result.append(res.begin(), res.end());
985 return object_error::success;
989 MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
990 SmallVectorImpl<char> &Result) const {
991 MachO::any_relocation_info RE = getRelocation(Rel);
993 unsigned Arch = this->getArch();
996 raw_string_ostream fmt(fmtbuf);
997 unsigned Type = this->getAnyRelocationType(RE);
998 bool IsPCRel = this->getAnyRelocationPCRel(RE);
1000 // Determine any addends that should be displayed with the relocation.
1001 // These require decoding the relocation type, which is triple-specific.
1003 // X86_64 has entirely custom relocation types.
1004 if (Arch == Triple::x86_64) {
1005 bool isPCRel = getAnyRelocationPCRel(RE);
1008 case MachO::X86_64_RELOC_GOT_LOAD:
1009 case MachO::X86_64_RELOC_GOT: {
1010 printRelocationTargetName(this, RE, fmt);
1012 if (isPCRel) fmt << "PCREL";
1015 case MachO::X86_64_RELOC_SUBTRACTOR: {
1016 DataRefImpl RelNext = Rel;
1018 MachO::any_relocation_info RENext = getRelocation(RelNext);
1020 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
1021 // X86_64_RELOC_UNSIGNED.
1022 // NOTE: Scattered relocations don't exist on x86_64.
1023 unsigned RType = getAnyRelocationType(RENext);
1024 if (RType != MachO::X86_64_RELOC_UNSIGNED)
1025 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
1026 "X86_64_RELOC_SUBTRACTOR.");
1028 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
1029 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
1030 printRelocationTargetName(this, RENext, fmt);
1032 printRelocationTargetName(this, RE, fmt);
1035 case MachO::X86_64_RELOC_TLV:
1036 printRelocationTargetName(this, RE, fmt);
1038 if (isPCRel) fmt << "P";
1040 case MachO::X86_64_RELOC_SIGNED_1:
1041 printRelocationTargetName(this, RE, fmt);
1044 case MachO::X86_64_RELOC_SIGNED_2:
1045 printRelocationTargetName(this, RE, fmt);
1048 case MachO::X86_64_RELOC_SIGNED_4:
1049 printRelocationTargetName(this, RE, fmt);
1053 printRelocationTargetName(this, RE, fmt);
1056 // X86 and ARM share some relocation types in common.
1057 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
1058 Arch == Triple::ppc) {
1059 // Generic relocation types...
1061 case MachO::GENERIC_RELOC_PAIR: // prints no info
1062 return object_error::success;
1063 case MachO::GENERIC_RELOC_SECTDIFF: {
1064 DataRefImpl RelNext = Rel;
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);
1072 if (RType != MachO::GENERIC_RELOC_PAIR)
1073 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1074 "GENERIC_RELOC_SECTDIFF.");
1076 printRelocationTargetName(this, RE, fmt);
1078 printRelocationTargetName(this, RENext, fmt);
1083 if (Arch == Triple::x86 || Arch == Triple::ppc) {
1085 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1086 DataRefImpl RelNext = Rel;
1088 MachO::any_relocation_info RENext = getRelocation(RelNext);
1090 // X86 sect diff's must be followed by a relocation of type
1091 // GENERIC_RELOC_PAIR.
1092 unsigned RType = getAnyRelocationType(RENext);
1093 if (RType != MachO::GENERIC_RELOC_PAIR)
1094 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1095 "GENERIC_RELOC_LOCAL_SECTDIFF.");
1097 printRelocationTargetName(this, RE, fmt);
1099 printRelocationTargetName(this, RENext, fmt);
1102 case MachO::GENERIC_RELOC_TLV: {
1103 printRelocationTargetName(this, RE, fmt);
1105 if (IsPCRel) fmt << "P";
1109 printRelocationTargetName(this, RE, fmt);
1111 } else { // ARM-specific relocations
1113 case MachO::ARM_RELOC_HALF:
1114 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1115 // Half relocations steal a bit from the length field to encode
1116 // whether this is an upper16 or a lower16 relocation.
1117 bool isUpper = getAnyRelocationLength(RE) >> 1;
1120 fmt << ":upper16:(";
1122 fmt << ":lower16:(";
1123 printRelocationTargetName(this, RE, fmt);
1125 DataRefImpl RelNext = Rel;
1127 MachO::any_relocation_info RENext = getRelocation(RelNext);
1129 // ARM half relocs must be followed by a relocation of type
1131 unsigned RType = getAnyRelocationType(RENext);
1132 if (RType != MachO::ARM_RELOC_PAIR)
1133 report_fatal_error("Expected ARM_RELOC_PAIR after "
1136 // NOTE: The half of the target virtual address is stashed in the
1137 // address field of the secondary relocation, but we can't reverse
1138 // engineer the constant offset from it without decoding the movw/movt
1139 // instruction to find the other half in its immediate field.
1141 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1142 // symbol/section pointer of the follow-on relocation.
1143 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1145 printRelocationTargetName(this, RENext, fmt);
1152 printRelocationTargetName(this, RE, fmt);
1157 printRelocationTargetName(this, RE, fmt);
1160 Result.append(fmtbuf.begin(), fmtbuf.end());
1161 return object_error::success;
1165 MachOObjectFile::getRelocationHidden(DataRefImpl Rel, bool &Result) const {
1166 unsigned Arch = getArch();
1168 getRelocationType(Rel, Type);
1172 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1173 // is always hidden.
1174 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1175 if (Type == MachO::GENERIC_RELOC_PAIR) Result = true;
1176 } else if (Arch == Triple::x86_64) {
1177 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1178 // an X86_64_RELOC_SUBTRACTOR.
1179 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1180 DataRefImpl RelPrev = Rel;
1183 getRelocationType(RelPrev, PrevType);
1184 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1189 return object_error::success;
1192 error_code MachOObjectFile::getLibraryNext(DataRefImpl LibData,
1193 LibraryRef &Res) const {
1194 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1197 error_code MachOObjectFile::getLibraryPath(DataRefImpl LibData,
1198 StringRef &Res) const {
1199 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1202 basic_symbol_iterator MachOObjectFile::symbol_begin_impl() const {
1205 return basic_symbol_iterator(SymbolRef(DRI, this));
1207 MachO::symtab_command Symtab = getSymtabLoadCommand();
1208 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.symoff));
1209 return basic_symbol_iterator(SymbolRef(DRI, this));
1212 basic_symbol_iterator MachOObjectFile::symbol_end_impl() const {
1215 return basic_symbol_iterator(SymbolRef(DRI, this));
1217 MachO::symtab_command Symtab = getSymtabLoadCommand();
1218 unsigned SymbolTableEntrySize = is64Bit() ?
1219 sizeof(MachO::nlist_64) :
1220 sizeof(MachO::nlist);
1221 unsigned Offset = Symtab.symoff +
1222 Symtab.nsyms * SymbolTableEntrySize;
1223 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1224 return basic_symbol_iterator(SymbolRef(DRI, this));
1227 section_iterator MachOObjectFile::section_begin() const {
1229 return section_iterator(SectionRef(DRI, this));
1232 section_iterator MachOObjectFile::section_end() const {
1234 DRI.d.a = Sections.size();
1235 return section_iterator(SectionRef(DRI, this));
1238 library_iterator MachOObjectFile::needed_library_begin() const {
1240 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1243 library_iterator MachOObjectFile::needed_library_end() const {
1245 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1248 uint8_t MachOObjectFile::getBytesInAddress() const {
1249 return is64Bit() ? 8 : 4;
1252 StringRef MachOObjectFile::getFileFormatName() const {
1253 unsigned CPUType = getCPUType(this);
1256 case llvm::MachO::CPU_TYPE_I386:
1257 return "Mach-O 32-bit i386";
1258 case llvm::MachO::CPU_TYPE_ARM:
1259 return "Mach-O arm";
1260 case llvm::MachO::CPU_TYPE_POWERPC:
1261 return "Mach-O 32-bit ppc";
1263 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64) == 0 &&
1264 "64-bit object file when we're not 64-bit?");
1265 return "Mach-O 32-bit unknown";
1269 // Make sure the cpu type has the correct mask.
1270 assert((CPUType & llvm::MachO::CPU_ARCH_ABI64)
1271 == llvm::MachO::CPU_ARCH_ABI64 &&
1272 "32-bit object file when we're 64-bit?");
1275 case llvm::MachO::CPU_TYPE_X86_64:
1276 return "Mach-O 64-bit x86-64";
1277 case llvm::MachO::CPU_TYPE_ARM64:
1278 return "Mach-O arm64";
1279 case llvm::MachO::CPU_TYPE_POWERPC64:
1280 return "Mach-O 64-bit ppc64";
1282 return "Mach-O 64-bit unknown";
1286 Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType) {
1288 case llvm::MachO::CPU_TYPE_I386:
1290 case llvm::MachO::CPU_TYPE_X86_64:
1291 return Triple::x86_64;
1292 case llvm::MachO::CPU_TYPE_ARM:
1294 case llvm::MachO::CPU_TYPE_ARM64:
1295 return Triple::arm64;
1296 case llvm::MachO::CPU_TYPE_POWERPC:
1298 case llvm::MachO::CPU_TYPE_POWERPC64:
1299 return Triple::ppc64;
1301 return Triple::UnknownArch;
1305 unsigned MachOObjectFile::getArch() const {
1306 return getArch(getCPUType(this));
1309 StringRef MachOObjectFile::getLoadName() const {
1311 report_fatal_error("get_load_name() unimplemented in MachOObjectFile");
1314 relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
1317 return section_rel_begin(DRI);
1320 relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
1323 return section_rel_end(DRI);
1326 dice_iterator MachOObjectFile::begin_dices() const {
1328 if (!DataInCodeLoadCmd)
1329 return dice_iterator(DiceRef(DRI, this));
1331 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1332 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, DicLC.dataoff));
1333 return dice_iterator(DiceRef(DRI, this));
1336 dice_iterator MachOObjectFile::end_dices() const {
1338 if (!DataInCodeLoadCmd)
1339 return dice_iterator(DiceRef(DRI, this));
1341 MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
1342 unsigned Offset = DicLC.dataoff + DicLC.datasize;
1343 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1344 return dice_iterator(DiceRef(DRI, this));
1348 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1349 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1350 return parseSegmentOrSectionName(Raw.data());
1354 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
1355 const section_base *Base =
1356 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1357 return ArrayRef<char>(Base->sectname);
1361 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
1362 const section_base *Base =
1363 reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
1364 return ArrayRef<char>(Base->segname);
1368 MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
1370 if (getCPUType(this) == MachO::CPU_TYPE_X86_64)
1372 return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
1375 unsigned MachOObjectFile::getPlainRelocationSymbolNum(
1376 const MachO::any_relocation_info &RE) const {
1377 if (isLittleEndian())
1378 return RE.r_word1 & 0xffffff;
1379 return RE.r_word1 >> 8;
1382 bool MachOObjectFile::getPlainRelocationExternal(
1383 const MachO::any_relocation_info &RE) const {
1384 if (isLittleEndian())
1385 return (RE.r_word1 >> 27) & 1;
1386 return (RE.r_word1 >> 4) & 1;
1389 bool MachOObjectFile::getScatteredRelocationScattered(
1390 const MachO::any_relocation_info &RE) const {
1391 return RE.r_word0 >> 31;
1394 uint32_t MachOObjectFile::getScatteredRelocationValue(
1395 const MachO::any_relocation_info &RE) const {
1399 unsigned MachOObjectFile::getAnyRelocationAddress(
1400 const MachO::any_relocation_info &RE) const {
1401 if (isRelocationScattered(RE))
1402 return getScatteredRelocationAddress(RE);
1403 return getPlainRelocationAddress(RE);
1406 unsigned MachOObjectFile::getAnyRelocationPCRel(
1407 const MachO::any_relocation_info &RE) const {
1408 if (isRelocationScattered(RE))
1409 return getScatteredRelocationPCRel(this, RE);
1410 return getPlainRelocationPCRel(this, RE);
1413 unsigned MachOObjectFile::getAnyRelocationLength(
1414 const MachO::any_relocation_info &RE) const {
1415 if (isRelocationScattered(RE))
1416 return getScatteredRelocationLength(RE);
1417 return getPlainRelocationLength(this, RE);
1421 MachOObjectFile::getAnyRelocationType(
1422 const MachO::any_relocation_info &RE) const {
1423 if (isRelocationScattered(RE))
1424 return getScatteredRelocationType(RE);
1425 return getPlainRelocationType(this, RE);
1429 MachOObjectFile::getRelocationSection(
1430 const MachO::any_relocation_info &RE) const {
1431 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
1432 return *section_end();
1433 unsigned SecNum = getPlainRelocationSymbolNum(RE) - 1;
1436 return SectionRef(DRI, this);
1439 MachOObjectFile::LoadCommandInfo
1440 MachOObjectFile::getFirstLoadCommandInfo() const {
1441 MachOObjectFile::LoadCommandInfo Load;
1443 unsigned HeaderSize = is64Bit() ? sizeof(MachO::mach_header_64) :
1444 sizeof(MachO::mach_header);
1445 Load.Ptr = getPtr(this, HeaderSize);
1446 Load.C = getStruct<MachO::load_command>(this, Load.Ptr);
1450 MachOObjectFile::LoadCommandInfo
1451 MachOObjectFile::getNextLoadCommandInfo(const LoadCommandInfo &L) const {
1452 MachOObjectFile::LoadCommandInfo Next;
1453 Next.Ptr = L.Ptr + L.C.cmdsize;
1454 Next.C = getStruct<MachO::load_command>(this, Next.Ptr);
1458 MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
1459 return getStruct<MachO::section>(this, Sections[DRI.d.a]);
1462 MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
1463 return getStruct<MachO::section_64>(this, Sections[DRI.d.a]);
1466 MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
1467 unsigned Index) const {
1468 const char *Sec = getSectionPtr(this, L, Index);
1469 return getStruct<MachO::section>(this, Sec);
1472 MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
1473 unsigned Index) const {
1474 const char *Sec = getSectionPtr(this, L, Index);
1475 return getStruct<MachO::section_64>(this, Sec);
1479 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
1480 const char *P = reinterpret_cast<const char *>(DRI.p);
1481 return getStruct<MachO::nlist>(this, P);
1485 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
1486 const char *P = reinterpret_cast<const char *>(DRI.p);
1487 return getStruct<MachO::nlist_64>(this, P);
1490 MachO::linkedit_data_command
1491 MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
1492 return getStruct<MachO::linkedit_data_command>(this, L.Ptr);
1495 MachO::segment_command
1496 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
1497 return getStruct<MachO::segment_command>(this, L.Ptr);
1500 MachO::segment_command_64
1501 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
1502 return getStruct<MachO::segment_command_64>(this, L.Ptr);
1505 MachO::linker_options_command
1506 MachOObjectFile::getLinkerOptionsLoadCommand(const LoadCommandInfo &L) const {
1507 return getStruct<MachO::linker_options_command>(this, L.Ptr);
1510 MachO::version_min_command
1511 MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
1512 return getStruct<MachO::version_min_command>(this, L.Ptr);
1515 MachO::any_relocation_info
1516 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
1517 const char *P = reinterpret_cast<const char *>(Rel.p);
1518 return getStruct<MachO::any_relocation_info>(this, P);
1521 MachO::data_in_code_entry
1522 MachOObjectFile::getDice(DataRefImpl Rel) const {
1523 const char *P = reinterpret_cast<const char *>(Rel.p);
1524 return getStruct<MachO::data_in_code_entry>(this, P);
1527 MachO::mach_header MachOObjectFile::getHeader() const {
1528 return getStruct<MachO::mach_header>(this, getPtr(this, 0));
1531 MachO::mach_header_64 MachOObjectFile::getHeader64() const {
1532 return getStruct<MachO::mach_header_64>(this, getPtr(this, 0));
1535 uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
1536 const MachO::dysymtab_command &DLC,
1537 unsigned Index) const {
1538 uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
1539 return getStruct<uint32_t>(this, getPtr(this, Offset));
1542 MachO::data_in_code_entry
1543 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
1544 unsigned Index) const {
1545 uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
1546 return getStruct<MachO::data_in_code_entry>(this, getPtr(this, Offset));
1549 MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
1550 return getStruct<MachO::symtab_command>(this, SymtabLoadCmd);
1553 MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
1554 return getStruct<MachO::dysymtab_command>(this, DysymtabLoadCmd);
1557 MachO::linkedit_data_command
1558 MachOObjectFile::getDataInCodeLoadCommand() const {
1559 if (DataInCodeLoadCmd)
1560 return getStruct<MachO::linkedit_data_command>(this, DataInCodeLoadCmd);
1562 // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
1563 MachO::linkedit_data_command Cmd;
1564 Cmd.cmd = MachO::LC_DATA_IN_CODE;
1565 Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
1571 StringRef MachOObjectFile::getStringTableData() const {
1572 MachO::symtab_command S = getSymtabLoadCommand();
1573 return getData().substr(S.stroff, S.strsize);
1576 bool MachOObjectFile::is64Bit() const {
1577 return getType() == getMachOType(false, true) ||
1578 getType() == getMachOType(true, true);
1581 void MachOObjectFile::ReadULEB128s(uint64_t Index,
1582 SmallVectorImpl<uint64_t> &Out) const {
1583 DataExtractor extractor(ObjectFile::getData(), true, 0);
1585 uint32_t offset = Index;
1587 while (uint64_t delta = extractor.getULEB128(&offset)) {
1589 Out.push_back(data);
1593 ErrorOr<ObjectFile *> ObjectFile::createMachOObjectFile(MemoryBuffer *Buffer,
1595 StringRef Magic = Buffer->getBuffer().slice(0, 4);
1597 std::unique_ptr<MachOObjectFile> Ret;
1598 if (Magic == "\xFE\xED\xFA\xCE")
1599 Ret.reset(new MachOObjectFile(Buffer, false, false, EC, BufferOwned));
1600 else if (Magic == "\xCE\xFA\xED\xFE")
1601 Ret.reset(new MachOObjectFile(Buffer, true, false, EC, BufferOwned));
1602 else if (Magic == "\xFE\xED\xFA\xCF")
1603 Ret.reset(new MachOObjectFile(Buffer, false, true, EC, BufferOwned));
1604 else if (Magic == "\xCF\xFA\xED\xFE")
1605 Ret.reset(new MachOObjectFile(Buffer, true, true, EC, BufferOwned));
1608 return object_error::parse_failed;
1613 return Ret.release();
1616 } // end namespace object
1617 } // end namespace llvm