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/Triple.h"
17 #include "llvm/Object/MachOFormat.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"
27 using namespace object;
32 struct SymbolTableEntryBase {
45 static void SwapValue(T &Value) {
46 Value = sys::SwapByteOrder(Value);
50 static void SwapStruct(T &Value);
53 void SwapStruct(macho::RelocationEntry &H) {
59 void SwapStruct(macho::LoadCommand &L) {
65 void SwapStruct(SymbolTableEntryBase &S) {
66 SwapValue(S.StringIndex);
71 void SwapStruct(macho::Section &S) {
76 SwapValue(S.RelocationTableOffset);
77 SwapValue(S.NumRelocationTableEntries);
79 SwapValue(S.Reserved1);
80 SwapValue(S.Reserved2);
84 void SwapStruct(macho::Section64 &S) {
89 SwapValue(S.RelocationTableOffset);
90 SwapValue(S.NumRelocationTableEntries);
92 SwapValue(S.Reserved1);
93 SwapValue(S.Reserved2);
94 SwapValue(S.Reserved3);
98 void SwapStruct(macho::SymbolTableEntry &S) {
99 SwapValue(S.StringIndex);
105 void SwapStruct(macho::Symbol64TableEntry &S) {
106 SwapValue(S.StringIndex);
112 void SwapStruct(macho::Header &H) {
114 SwapValue(H.CPUType);
115 SwapValue(H.CPUSubtype);
116 SwapValue(H.FileType);
117 SwapValue(H.NumLoadCommands);
118 SwapValue(H.SizeOfLoadCommands);
123 void SwapStruct(macho::Header64Ext &E) {
124 SwapValue(E.Reserved);
128 void SwapStruct(macho::SymtabLoadCommand &C) {
131 SwapValue(C.SymbolTableOffset);
132 SwapValue(C.NumSymbolTableEntries);
133 SwapValue(C.StringTableOffset);
134 SwapValue(C.StringTableSize);
138 void SwapStruct(macho::DysymtabLoadCommand &C) {
141 SwapValue(C.LocalSymbolsIndex);
142 SwapValue(C.NumLocalSymbols);
143 SwapValue(C.ExternalSymbolsIndex);
144 SwapValue(C.NumExternalSymbols);
145 SwapValue(C.UndefinedSymbolsIndex);
146 SwapValue(C.NumUndefinedSymbols);
147 SwapValue(C.TOCOffset);
148 SwapValue(C.NumTOCEntries);
149 SwapValue(C.ModuleTableOffset);
150 SwapValue(C.NumModuleTableEntries);
151 SwapValue(C.ReferenceSymbolTableOffset);
152 SwapValue(C.NumReferencedSymbolTableEntries);
153 SwapValue(C.IndirectSymbolTableOffset);
154 SwapValue(C.NumIndirectSymbolTableEntries);
155 SwapValue(C.ExternalRelocationTableOffset);
156 SwapValue(C.NumExternalRelocationTableEntries);
157 SwapValue(C.LocalRelocationTableOffset);
158 SwapValue(C.NumLocalRelocationTableEntries);
162 void SwapStruct(macho::LinkeditDataLoadCommand &C) {
165 SwapValue(C.DataOffset);
166 SwapValue(C.DataSize);
170 void SwapStruct(macho::SegmentLoadCommand &C) {
173 SwapValue(C.VMAddress);
175 SwapValue(C.FileOffset);
176 SwapValue(C.FileSize);
177 SwapValue(C.MaxVMProtection);
178 SwapValue(C.InitialVMProtection);
179 SwapValue(C.NumSections);
184 void SwapStruct(macho::Segment64LoadCommand &C) {
187 SwapValue(C.VMAddress);
189 SwapValue(C.FileOffset);
190 SwapValue(C.FileSize);
191 SwapValue(C.MaxVMProtection);
192 SwapValue(C.InitialVMProtection);
193 SwapValue(C.NumSections);
198 void SwapStruct(macho::IndirectSymbolTableEntry &C) {
203 void SwapStruct(macho::LinkerOptionsLoadCommand &C) {
210 void SwapStruct(macho::DataInCodeTableEntry &C) {
217 T getStruct(const MachOObjectFile *O, const char *P) {
219 memcpy(&Cmd, P, sizeof(T));
220 if (O->isLittleEndian() != sys::IsLittleEndianHost)
226 getSegmentLoadCommandNumSections(const MachOObjectFile *O,
227 const MachOObjectFile::LoadCommandInfo &L) {
229 macho::Segment64LoadCommand S = O->getSegment64LoadCommand(L);
230 return S.NumSections;
232 macho::SegmentLoadCommand S = O->getSegmentLoadCommand(L);
233 return S.NumSections;
237 getSectionPtr(const MachOObjectFile *O, MachOObjectFile::LoadCommandInfo L,
239 uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
241 bool Is64 = O->is64Bit();
242 unsigned SegmentLoadSize = Is64 ? sizeof(macho::Segment64LoadCommand) :
243 sizeof(macho::SegmentLoadCommand);
244 unsigned SectionSize = Is64 ? sizeof(macho::Section64) :
245 sizeof(macho::Section);
247 uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
248 return reinterpret_cast<const char*>(SectionAddr);
251 static const char *getPtr(const MachOObjectFile *O, size_t Offset) {
252 return O->getData().substr(Offset, 1).data();
255 static SymbolTableEntryBase
256 getSymbolTableEntryBase(const MachOObjectFile *O, DataRefImpl DRI) {
257 const char *P = reinterpret_cast<const char *>(DRI.p);
258 return getStruct<SymbolTableEntryBase>(O, P);
261 static StringRef parseSegmentOrSectionName(const char *P) {
265 // Not null terminated, so this is a 16 char string.
266 return StringRef(P, 16);
269 // Helper to advance a section or symbol iterator multiple increments at a time.
271 static error_code advance(T &it, size_t Val) {
280 static void advanceTo(T &it, size_t Val) {
281 if (error_code ec = advance(it, Val))
282 report_fatal_error(ec.message());
285 static unsigned getCPUType(const MachOObjectFile *O) {
286 return O->getHeader().CPUType;
289 static void printRelocationTargetName(const MachOObjectFile *O,
290 const macho::RelocationEntry &RE,
291 raw_string_ostream &fmt) {
292 bool IsScattered = O->isRelocationScattered(RE);
294 // Target of a scattered relocation is an address. In the interest of
295 // generating pretty output, scan through the symbol table looking for a
296 // symbol that aligns with that address. If we find one, print it.
297 // Otherwise, we just print the hex address of the target.
299 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
302 for (symbol_iterator SI = O->begin_symbols(), SE = O->end_symbols();
303 SI != SE; SI.increment(ec)) {
304 if (ec) report_fatal_error(ec.message());
309 if ((ec = SI->getAddress(Addr)))
310 report_fatal_error(ec.message());
311 if (Addr != Val) continue;
312 if ((ec = SI->getName(Name)))
313 report_fatal_error(ec.message());
318 // If we couldn't find a symbol that this relocation refers to, try
319 // to find a section beginning instead.
320 for (section_iterator SI = O->begin_sections(), SE = O->end_sections();
321 SI != SE; SI.increment(ec)) {
322 if (ec) report_fatal_error(ec.message());
327 if ((ec = SI->getAddress(Addr)))
328 report_fatal_error(ec.message());
329 if (Addr != Val) continue;
330 if ((ec = SI->getName(Name)))
331 report_fatal_error(ec.message());
336 fmt << format("0x%x", Val);
341 bool isExtern = O->getPlainRelocationExternal(RE);
342 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
345 symbol_iterator SI = O->begin_symbols();
349 section_iterator SI = O->begin_sections();
350 // Adjust for the fact that sections are 1-indexed.
351 advanceTo(SI, Val - 1);
358 static uint32_t getPlainRelocationAddress(const macho::RelocationEntry &RE) {
363 getScatteredRelocationAddress(const macho::RelocationEntry &RE) {
364 return RE.Word0 & 0xffffff;
367 static bool getPlainRelocationPCRel(const MachOObjectFile *O,
368 const macho::RelocationEntry &RE) {
369 if (O->isLittleEndian())
370 return (RE.Word1 >> 24) & 1;
371 return (RE.Word1 >> 7) & 1;
375 getScatteredRelocationPCRel(const MachOObjectFile *O,
376 const macho::RelocationEntry &RE) {
377 return (RE.Word0 >> 30) & 1;
380 static unsigned getPlainRelocationLength(const MachOObjectFile *O,
381 const macho::RelocationEntry &RE) {
382 if (O->isLittleEndian())
383 return (RE.Word1 >> 25) & 3;
384 return (RE.Word1 >> 5) & 3;
388 getScatteredRelocationLength(const macho::RelocationEntry &RE) {
389 return (RE.Word0 >> 28) & 3;
392 static unsigned getPlainRelocationType(const MachOObjectFile *O,
393 const macho::RelocationEntry &RE) {
394 if (O->isLittleEndian())
395 return RE.Word1 >> 28;
396 return RE.Word1 & 0xf;
399 static unsigned getScatteredRelocationType(const macho::RelocationEntry &RE) {
400 return (RE.Word0 >> 24) & 0xf;
403 static uint32_t getSectionFlags(const MachOObjectFile *O,
406 macho::Section64 Sect = O->getSection64(Sec);
409 macho::Section Sect = O->getSection(Sec);
413 MachOObjectFile::MachOObjectFile(MemoryBuffer *Object,
414 bool IsLittleEndian, bool Is64bits,
416 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
417 SymtabLoadCmd(NULL), DysymtabLoadCmd(NULL) {
418 uint32_t LoadCommandCount = this->getHeader().NumLoadCommands;
419 macho::LoadCommandType SegmentLoadType = is64Bit() ?
420 macho::LCT_Segment64 : macho::LCT_Segment;
422 MachOObjectFile::LoadCommandInfo Load = getFirstLoadCommandInfo();
423 for (unsigned I = 0; ; ++I) {
424 if (Load.C.Type == macho::LCT_Symtab) {
425 assert(!SymtabLoadCmd && "Multiple symbol tables");
426 SymtabLoadCmd = Load.Ptr;
427 } else if (Load.C.Type == macho::LCT_Dysymtab) {
428 assert(!DysymtabLoadCmd && "Multiple dynamic symbol tables");
429 DysymtabLoadCmd = Load.Ptr;
430 } else if (Load.C.Type == SegmentLoadType) {
431 uint32_t NumSections = getSegmentLoadCommandNumSections(this, Load);
432 for (unsigned J = 0; J < NumSections; ++J) {
433 const char *Sec = getSectionPtr(this, Load, J);
434 Sections.push_back(Sec);
438 if (I == LoadCommandCount - 1)
441 Load = getNextLoadCommandInfo(Load);
445 error_code MachOObjectFile::getSymbolNext(DataRefImpl Symb,
446 SymbolRef &Res) const {
447 unsigned SymbolTableEntrySize = is64Bit() ?
448 sizeof(macho::Symbol64TableEntry) :
449 sizeof(macho::SymbolTableEntry);
450 Symb.p += SymbolTableEntrySize;
451 Res = SymbolRef(Symb, this);
452 return object_error::success;
455 error_code MachOObjectFile::getSymbolName(DataRefImpl Symb,
456 StringRef &Res) const {
457 StringRef StringTable = getStringTableData();
458 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
459 const char *Start = &StringTable.data()[Entry.StringIndex];
460 Res = StringRef(Start);
461 return object_error::success;
464 error_code MachOObjectFile::getSymbolAddress(DataRefImpl Symb,
465 uint64_t &Res) const {
467 macho::Symbol64TableEntry Entry = getSymbol64TableEntry(Symb);
470 macho::SymbolTableEntry Entry = getSymbolTableEntry(Symb);
473 return object_error::success;
477 MachOObjectFile::getSymbolFileOffset(DataRefImpl Symb,
478 uint64_t &Res) const {
479 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
480 getSymbolAddress(Symb, Res);
481 if (Entry.SectionIndex) {
484 SecRel.d.a = Entry.SectionIndex-1;
486 macho::Section64 Sec = getSection64(SecRel);
487 Delta = Sec.Offset - Sec.Address;
489 macho::Section Sec = getSection(SecRel);
490 Delta = Sec.Offset - Sec.Address;
496 return object_error::success;
499 error_code MachOObjectFile::getSymbolAlignment(DataRefImpl DRI,
500 uint32_t &Result) const {
502 this->getSymbolFlags(DRI, flags);
503 if (flags & SymbolRef::SF_Common) {
504 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, DRI);
505 Result = 1 << MachO::GET_COMM_ALIGN(Entry.Flags);
509 return object_error::success;
512 error_code MachOObjectFile::getSymbolSize(DataRefImpl DRI,
513 uint64_t &Result) const {
514 uint64_t BeginOffset;
515 uint64_t EndOffset = 0;
516 uint8_t SectionIndex;
518 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, DRI);
520 getSymbolAddress(DRI, Value);
524 SectionIndex = Entry.SectionIndex;
526 uint32_t flags = SymbolRef::SF_None;
527 this->getSymbolFlags(DRI, flags);
528 if (flags & SymbolRef::SF_Common)
531 Result = UnknownAddressOrSize;
532 return object_error::success;
534 // Unfortunately symbols are unsorted so we need to touch all
535 // symbols from load command
537 for (symbol_iterator I = begin_symbols(), E = end_symbols(); I != E;
539 DataRefImpl DRI = I->getRawDataRefImpl();
540 Entry = getSymbolTableEntryBase(this, DRI);
541 getSymbolAddress(DRI, Value);
542 if (Entry.SectionIndex == SectionIndex && Value > BeginOffset)
543 if (!EndOffset || Value < EndOffset)
549 Sec.d.a = SectionIndex-1;
550 getSectionSize(Sec, Size);
551 getSectionAddress(Sec, EndOffset);
554 Result = EndOffset - BeginOffset;
555 return object_error::success;
558 error_code MachOObjectFile::getSymbolType(DataRefImpl Symb,
559 SymbolRef::Type &Res) const {
560 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
561 uint8_t n_type = Entry.Type;
563 Res = SymbolRef::ST_Other;
565 // If this is a STAB debugging symbol, we can do nothing more.
566 if (n_type & MachO::NlistMaskStab) {
567 Res = SymbolRef::ST_Debug;
568 return object_error::success;
571 switch (n_type & MachO::NlistMaskType) {
572 case MachO::NListTypeUndefined :
573 Res = SymbolRef::ST_Unknown;
575 case MachO::NListTypeSection :
576 Res = SymbolRef::ST_Function;
579 return object_error::success;
582 error_code MachOObjectFile::getSymbolNMTypeChar(DataRefImpl Symb,
584 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
585 uint8_t Type = Entry.Type;
586 uint16_t Flags = Entry.Flags;
589 switch (Type & macho::STF_TypeMask) {
590 case macho::STT_Undefined:
593 case macho::STT_Absolute:
594 case macho::STT_Section:
602 if (Flags & (macho::STF_External | macho::STF_PrivateExtern))
603 Char = toupper(static_cast<unsigned char>(Char));
605 return object_error::success;
608 error_code MachOObjectFile::getSymbolFlags(DataRefImpl DRI,
609 uint32_t &Result) const {
610 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, DRI);
612 uint8_t MachOType = Entry.Type;
613 uint16_t MachOFlags = Entry.Flags;
615 // TODO: Correctly set SF_ThreadLocal
616 Result = SymbolRef::SF_None;
618 if ((MachOType & MachO::NlistMaskType) == MachO::NListTypeUndefined)
619 Result |= SymbolRef::SF_Undefined;
621 if (MachOFlags & macho::STF_StabsEntryMask)
622 Result |= SymbolRef::SF_FormatSpecific;
624 if (MachOType & MachO::NlistMaskExternal) {
625 Result |= SymbolRef::SF_Global;
626 if ((MachOType & MachO::NlistMaskType) == MachO::NListTypeUndefined) {
628 getSymbolAddress(DRI, Value);
630 Result |= SymbolRef::SF_Common;
634 if (MachOFlags & (MachO::NListDescWeakRef | MachO::NListDescWeakDef))
635 Result |= SymbolRef::SF_Weak;
637 if ((MachOType & MachO::NlistMaskType) == MachO::NListTypeAbsolute)
638 Result |= SymbolRef::SF_Absolute;
640 return object_error::success;
644 MachOObjectFile::getSymbolSection(DataRefImpl Symb,
645 section_iterator &Res) const {
646 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
647 uint8_t index = Entry.SectionIndex;
650 Res = end_sections();
654 Res = section_iterator(SectionRef(DRI, this));
657 return object_error::success;
660 error_code MachOObjectFile::getSymbolValue(DataRefImpl Symb,
661 uint64_t &Val) const {
662 report_fatal_error("getSymbolValue unimplemented in MachOObjectFile");
665 error_code MachOObjectFile::getSectionNext(DataRefImpl Sec,
666 SectionRef &Res) const {
668 Res = SectionRef(Sec, this);
669 return object_error::success;
673 MachOObjectFile::getSectionName(DataRefImpl Sec, StringRef &Result) const {
674 ArrayRef<char> Raw = getSectionRawName(Sec);
675 Result = parseSegmentOrSectionName(Raw.data());
676 return object_error::success;
680 MachOObjectFile::getSectionAddress(DataRefImpl Sec, uint64_t &Res) const {
682 macho::Section64 Sect = getSection64(Sec);
685 macho::Section Sect = getSection(Sec);
688 return object_error::success;
692 MachOObjectFile::getSectionSize(DataRefImpl Sec, uint64_t &Res) const {
694 macho::Section64 Sect = getSection64(Sec);
697 macho::Section Sect = getSection(Sec);
701 return object_error::success;
705 MachOObjectFile::getSectionContents(DataRefImpl Sec, StringRef &Res) const {
710 macho::Section64 Sect = getSection64(Sec);
711 Offset = Sect.Offset;
714 macho::Section Sect =getSection(Sec);
715 Offset = Sect.Offset;
719 Res = this->getData().substr(Offset, Size);
720 return object_error::success;
724 MachOObjectFile::getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const {
727 macho::Section64 Sect = getSection64(Sec);
730 macho::Section Sect = getSection(Sec);
734 Res = uint64_t(1) << Align;
735 return object_error::success;
739 MachOObjectFile::isSectionText(DataRefImpl Sec, bool &Res) const {
740 uint32_t Flags = getSectionFlags(this, Sec);
741 Res = Flags & macho::SF_PureInstructions;
742 return object_error::success;
745 error_code MachOObjectFile::isSectionData(DataRefImpl DRI, bool &Result) const {
746 // FIXME: Unimplemented.
748 return object_error::success;
751 error_code MachOObjectFile::isSectionBSS(DataRefImpl DRI, bool &Result) const {
752 // FIXME: Unimplemented.
754 return object_error::success;
758 MachOObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
759 bool &Result) const {
760 // FIXME: Unimplemented.
762 return object_error::success;
765 error_code MachOObjectFile::isSectionVirtual(DataRefImpl Sec,
766 bool &Result) const {
767 // FIXME: Unimplemented.
769 return object_error::success;
773 MachOObjectFile::isSectionZeroInit(DataRefImpl Sec, bool &Res) const {
774 uint32_t Flags = getSectionFlags(this, Sec);
775 unsigned SectionType = Flags & MachO::SectionFlagMaskSectionType;
776 Res = SectionType == MachO::SectionTypeZeroFill ||
777 SectionType == MachO::SectionTypeZeroFillLarge;
778 return object_error::success;
781 error_code MachOObjectFile::isSectionReadOnlyData(DataRefImpl Sec,
782 bool &Result) const {
783 // Consider using the code from isSectionText to look for __const sections.
784 // Alternately, emit S_ATTR_PURE_INSTRUCTIONS and/or S_ATTR_SOME_INSTRUCTIONS
785 // to use section attributes to distinguish code from data.
787 // FIXME: Unimplemented.
789 return object_error::success;
793 MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
794 bool &Result) const {
796 this->getSymbolType(Symb, ST);
797 if (ST == SymbolRef::ST_Unknown) {
799 return object_error::success;
802 uint64_t SectBegin, SectEnd;
803 getSectionAddress(Sec, SectBegin);
804 getSectionSize(Sec, SectEnd);
805 SectEnd += SectBegin;
808 getSymbolAddress(Symb, SymAddr);
809 Result = (SymAddr >= SectBegin) && (SymAddr < SectEnd);
811 return object_error::success;
814 relocation_iterator MachOObjectFile::getSectionRelBegin(DataRefImpl Sec) const {
817 macho::Section64 Sect = getSection64(Sec);
818 Offset = Sect.RelocationTableOffset;
820 macho::Section Sect = getSection(Sec);
821 Offset = Sect.RelocationTableOffset;
825 Ret.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
826 return relocation_iterator(RelocationRef(Ret, this));
830 MachOObjectFile::getSectionRelEnd(DataRefImpl Sec) const {
834 macho::Section64 Sect = getSection64(Sec);
835 Offset = Sect.RelocationTableOffset;
836 Num = Sect.NumRelocationTableEntries;
838 macho::Section Sect = getSection(Sec);
839 Offset = Sect.RelocationTableOffset;
840 Num = Sect.NumRelocationTableEntries;
843 const macho::RelocationEntry *P =
844 reinterpret_cast<const macho::RelocationEntry*>(getPtr(this, Offset));
847 Ret.p = reinterpret_cast<uintptr_t>(P + Num);
848 return relocation_iterator(RelocationRef(Ret, this));
851 error_code MachOObjectFile::getRelocationNext(DataRefImpl Rel,
852 RelocationRef &Res) const {
853 const macho::RelocationEntry *P =
854 reinterpret_cast<const macho::RelocationEntry *>(Rel.p);
855 Rel.p = reinterpret_cast<uintptr_t>(P + 1);
856 Res = RelocationRef(Rel, this);
857 return object_error::success;
861 MachOObjectFile::getRelocationAddress(DataRefImpl Rel, uint64_t &Res) const {
862 report_fatal_error("getRelocationAddress not implemented in MachOObjectFile");
865 error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
866 uint64_t &Res) const {
867 macho::RelocationEntry RE = getRelocation(Rel);
868 Res = getAnyRelocationAddress(RE);
869 return object_error::success;
873 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
874 macho::RelocationEntry RE = getRelocation(Rel);
875 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
876 bool isExtern = getPlainRelocationExternal(RE);
878 return end_symbols();
880 macho::SymtabLoadCommand S = getSymtabLoadCommand();
881 unsigned SymbolTableEntrySize = is64Bit() ?
882 sizeof(macho::Symbol64TableEntry) :
883 sizeof(macho::SymbolTableEntry);
884 uint64_t Offset = S.SymbolTableOffset + SymbolIdx * SymbolTableEntrySize;
886 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
887 return symbol_iterator(SymbolRef(Sym, this));
890 error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
891 uint64_t &Res) const {
892 macho::RelocationEntry RE = getRelocation(Rel);
893 Res = getAnyRelocationType(RE);
894 return object_error::success;
898 MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
899 SmallVectorImpl<char> &Result) const {
902 getRelocationType(Rel, RType);
904 unsigned Arch = this->getArch();
908 static const char *const Table[] = {
909 "GENERIC_RELOC_VANILLA",
910 "GENERIC_RELOC_PAIR",
911 "GENERIC_RELOC_SECTDIFF",
912 "GENERIC_RELOC_PB_LA_PTR",
913 "GENERIC_RELOC_LOCAL_SECTDIFF",
914 "GENERIC_RELOC_TLV" };
922 case Triple::x86_64: {
923 static const char *const Table[] = {
924 "X86_64_RELOC_UNSIGNED",
925 "X86_64_RELOC_SIGNED",
926 "X86_64_RELOC_BRANCH",
927 "X86_64_RELOC_GOT_LOAD",
929 "X86_64_RELOC_SUBTRACTOR",
930 "X86_64_RELOC_SIGNED_1",
931 "X86_64_RELOC_SIGNED_2",
932 "X86_64_RELOC_SIGNED_4",
933 "X86_64_RELOC_TLV" };
942 static const char *const Table[] = {
945 "ARM_RELOC_SECTDIFF",
946 "ARM_RELOC_LOCAL_SECTDIFF",
947 "ARM_RELOC_PB_LA_PTR",
949 "ARM_THUMB_RELOC_BR22",
950 "ARM_THUMB_32BIT_BRANCH",
952 "ARM_RELOC_HALF_SECTDIFF" };
961 static const char *const Table[] = {
970 "PPC_RELOC_SECTDIFF",
971 "PPC_RELOC_PB_LA_PTR",
972 "PPC_RELOC_HI16_SECTDIFF",
973 "PPC_RELOC_LO16_SECTDIFF",
974 "PPC_RELOC_HA16_SECTDIFF",
976 "PPC_RELOC_LO14_SECTDIFF",
977 "PPC_RELOC_LOCAL_SECTDIFF" };
982 case Triple::UnknownArch:
986 Result.append(res.begin(), res.end());
987 return object_error::success;
991 MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
992 SmallVectorImpl<char> &Result) const {
993 macho::RelocationEntry RE = getRelocation(Rel);
995 unsigned Arch = this->getArch();
998 raw_string_ostream fmt(fmtbuf);
999 unsigned Type = this->getAnyRelocationType(RE);
1000 bool IsPCRel = this->getAnyRelocationPCRel(RE);
1002 // Determine any addends that should be displayed with the relocation.
1003 // These require decoding the relocation type, which is triple-specific.
1005 // X86_64 has entirely custom relocation types.
1006 if (Arch == Triple::x86_64) {
1007 bool isPCRel = getAnyRelocationPCRel(RE);
1010 case macho::RIT_X86_64_GOTLoad: // X86_64_RELOC_GOT_LOAD
1011 case macho::RIT_X86_64_GOT: { // X86_64_RELOC_GOT
1012 printRelocationTargetName(this, RE, fmt);
1014 if (isPCRel) fmt << "PCREL";
1017 case macho::RIT_X86_64_Subtractor: { // X86_64_RELOC_SUBTRACTOR
1018 DataRefImpl RelNext = Rel;
1020 macho::RelocationEntry RENext = getRelocation(RelNext);
1022 // X86_64_SUBTRACTOR must be followed by a relocation of type
1023 // X86_64_RELOC_UNSIGNED.
1024 // NOTE: Scattered relocations don't exist on x86_64.
1025 unsigned RType = getAnyRelocationType(RENext);
1027 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
1028 "X86_64_RELOC_SUBTRACTOR.");
1030 // The X86_64_RELOC_UNSIGNED contains the minuend symbol,
1031 // X86_64_SUBTRACTOR contains to the subtrahend.
1032 printRelocationTargetName(this, RENext, fmt);
1034 printRelocationTargetName(this, RE, fmt);
1037 case macho::RIT_X86_64_TLV:
1038 printRelocationTargetName(this, RE, fmt);
1040 if (isPCRel) fmt << "P";
1042 case macho::RIT_X86_64_Signed1: // X86_64_RELOC_SIGNED1
1043 printRelocationTargetName(this, RE, fmt);
1046 case macho::RIT_X86_64_Signed2: // X86_64_RELOC_SIGNED2
1047 printRelocationTargetName(this, RE, fmt);
1050 case macho::RIT_X86_64_Signed4: // X86_64_RELOC_SIGNED4
1051 printRelocationTargetName(this, RE, fmt);
1055 printRelocationTargetName(this, RE, fmt);
1058 // X86 and ARM share some relocation types in common.
1059 } else if (Arch == Triple::x86 || Arch == Triple::arm) {
1060 // Generic relocation types...
1062 case macho::RIT_Pair: // GENERIC_RELOC_PAIR - prints no info
1063 return object_error::success;
1064 case macho::RIT_Difference: { // GENERIC_RELOC_SECTDIFF
1065 DataRefImpl RelNext = Rel;
1067 macho::RelocationEntry RENext = getRelocation(RelNext);
1069 // X86 sect diff's must be followed by a relocation of type
1070 // GENERIC_RELOC_PAIR.
1071 unsigned RType = getAnyRelocationType(RENext);
1074 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1075 "GENERIC_RELOC_SECTDIFF.");
1077 printRelocationTargetName(this, RE, fmt);
1079 printRelocationTargetName(this, RENext, fmt);
1084 if (Arch == Triple::x86) {
1085 // All X86 relocations that need special printing were already
1086 // handled in the generic code.
1088 case macho::RIT_Generic_LocalDifference:{// GENERIC_RELOC_LOCAL_SECTDIFF
1089 DataRefImpl RelNext = Rel;
1091 macho::RelocationEntry RENext = getRelocation(RelNext);
1093 // X86 sect diff's must be followed by a relocation of type
1094 // GENERIC_RELOC_PAIR.
1095 unsigned RType = getAnyRelocationType(RENext);
1097 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1098 "GENERIC_RELOC_LOCAL_SECTDIFF.");
1100 printRelocationTargetName(this, RE, fmt);
1102 printRelocationTargetName(this, RENext, fmt);
1105 case macho::RIT_Generic_TLV: {
1106 printRelocationTargetName(this, RE, fmt);
1108 if (IsPCRel) fmt << "P";
1112 printRelocationTargetName(this, RE, fmt);
1114 } else { // ARM-specific relocations
1116 case macho::RIT_ARM_Half: // ARM_RELOC_HALF
1117 case macho::RIT_ARM_HalfDifference: { // ARM_RELOC_HALF_SECTDIFF
1118 // Half relocations steal a bit from the length field to encode
1119 // whether this is an upper16 or a lower16 relocation.
1120 bool isUpper = getAnyRelocationLength(RE) >> 1;
1123 fmt << ":upper16:(";
1125 fmt << ":lower16:(";
1126 printRelocationTargetName(this, RE, fmt);
1128 DataRefImpl RelNext = Rel;
1130 macho::RelocationEntry RENext = getRelocation(RelNext);
1132 // ARM half relocs must be followed by a relocation of type
1134 unsigned RType = getAnyRelocationType(RENext);
1136 report_fatal_error("Expected ARM_RELOC_PAIR after "
1137 "GENERIC_RELOC_HALF");
1139 // NOTE: The half of the target virtual address is stashed in the
1140 // address field of the secondary relocation, but we can't reverse
1141 // engineer the constant offset from it without decoding the movw/movt
1142 // instruction to find the other half in its immediate field.
1144 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1145 // symbol/section pointer of the follow-on relocation.
1146 if (Type == macho::RIT_ARM_HalfDifference) {
1148 printRelocationTargetName(this, RENext, fmt);
1155 printRelocationTargetName(this, RE, fmt);
1160 printRelocationTargetName(this, RE, fmt);
1163 Result.append(fmtbuf.begin(), fmtbuf.end());
1164 return object_error::success;
1168 MachOObjectFile::getRelocationHidden(DataRefImpl Rel, bool &Result) const {
1169 unsigned Arch = getArch();
1171 getRelocationType(Rel, Type);
1175 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1176 // is always hidden.
1177 if (Arch == Triple::x86 || Arch == Triple::arm) {
1178 if (Type == macho::RIT_Pair) Result = true;
1179 } else if (Arch == Triple::x86_64) {
1180 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1181 // an X864_64_RELOC_SUBTRACTOR.
1182 if (Type == macho::RIT_X86_64_Unsigned && Rel.d.a > 0) {
1183 DataRefImpl RelPrev = Rel;
1186 getRelocationType(RelPrev, PrevType);
1187 if (PrevType == macho::RIT_X86_64_Subtractor)
1192 return object_error::success;
1195 error_code MachOObjectFile::getLibraryNext(DataRefImpl LibData,
1196 LibraryRef &Res) const {
1197 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1200 error_code MachOObjectFile::getLibraryPath(DataRefImpl LibData,
1201 StringRef &Res) const {
1202 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1205 symbol_iterator MachOObjectFile::begin_symbols() const {
1208 return symbol_iterator(SymbolRef(DRI, this));
1210 macho::SymtabLoadCommand Symtab = getSymtabLoadCommand();
1211 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.SymbolTableOffset));
1212 return symbol_iterator(SymbolRef(DRI, this));
1215 symbol_iterator MachOObjectFile::end_symbols() const {
1218 return symbol_iterator(SymbolRef(DRI, this));
1220 macho::SymtabLoadCommand Symtab = getSymtabLoadCommand();
1221 unsigned SymbolTableEntrySize = is64Bit() ?
1222 sizeof(macho::Symbol64TableEntry) :
1223 sizeof(macho::SymbolTableEntry);
1224 unsigned Offset = Symtab.SymbolTableOffset +
1225 Symtab.NumSymbolTableEntries * SymbolTableEntrySize;
1226 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1227 return symbol_iterator(SymbolRef(DRI, this));
1230 symbol_iterator MachOObjectFile::begin_dynamic_symbols() const {
1232 report_fatal_error("Dynamic symbols unimplemented in MachOObjectFile");
1235 symbol_iterator MachOObjectFile::end_dynamic_symbols() const {
1237 report_fatal_error("Dynamic symbols unimplemented in MachOObjectFile");
1240 section_iterator MachOObjectFile::begin_sections() const {
1242 return section_iterator(SectionRef(DRI, this));
1245 section_iterator MachOObjectFile::end_sections() const {
1247 DRI.d.a = Sections.size();
1248 return section_iterator(SectionRef(DRI, this));
1251 library_iterator MachOObjectFile::begin_libraries_needed() const {
1253 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1256 library_iterator MachOObjectFile::end_libraries_needed() const {
1258 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1261 uint8_t MachOObjectFile::getBytesInAddress() const {
1262 return is64Bit() ? 8 : 4;
1265 StringRef MachOObjectFile::getFileFormatName() const {
1266 unsigned CPUType = getCPUType(this);
1269 case llvm::MachO::CPUTypeI386:
1270 return "Mach-O 32-bit i386";
1271 case llvm::MachO::CPUTypeARM:
1272 return "Mach-O arm";
1273 case llvm::MachO::CPUTypePowerPC:
1274 return "Mach-O 32-bit ppc";
1276 assert((CPUType & llvm::MachO::CPUArchABI64) == 0 &&
1277 "64-bit object file when we're not 64-bit?");
1278 return "Mach-O 32-bit unknown";
1282 // Make sure the cpu type has the correct mask.
1283 assert((CPUType & llvm::MachO::CPUArchABI64)
1284 == llvm::MachO::CPUArchABI64 &&
1285 "32-bit object file when we're 64-bit?");
1288 case llvm::MachO::CPUTypeX86_64:
1289 return "Mach-O 64-bit x86-64";
1290 case llvm::MachO::CPUTypePowerPC64:
1291 return "Mach-O 64-bit ppc64";
1293 return "Mach-O 64-bit unknown";
1297 unsigned MachOObjectFile::getArch() const {
1298 switch (getCPUType(this)) {
1299 case llvm::MachO::CPUTypeI386:
1301 case llvm::MachO::CPUTypeX86_64:
1302 return Triple::x86_64;
1303 case llvm::MachO::CPUTypeARM:
1305 case llvm::MachO::CPUTypePowerPC:
1307 case llvm::MachO::CPUTypePowerPC64:
1308 return Triple::ppc64;
1310 return Triple::UnknownArch;
1314 StringRef MachOObjectFile::getLoadName() const {
1316 report_fatal_error("get_load_name() unimplemented in MachOObjectFile");
1319 relocation_iterator MachOObjectFile::getSectionRelBegin(unsigned Index) const {
1322 return getSectionRelBegin(DRI);
1325 relocation_iterator MachOObjectFile::getSectionRelEnd(unsigned Index) const {
1328 return getSectionRelEnd(DRI);
1332 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1333 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1334 return parseSegmentOrSectionName(Raw.data());
1338 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
1339 const SectionBase *Base =
1340 reinterpret_cast<const SectionBase*>(Sections[Sec.d.a]);
1341 return ArrayRef<char>(Base->Name);
1345 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
1346 const SectionBase *Base =
1347 reinterpret_cast<const SectionBase*>(Sections[Sec.d.a]);
1348 return ArrayRef<char>(Base->SegmentName);
1352 MachOObjectFile::isRelocationScattered(const macho::RelocationEntry &RE)
1354 if (getCPUType(this) == llvm::MachO::CPUTypeX86_64)
1356 return getPlainRelocationAddress(RE) & macho::RF_Scattered;
1359 unsigned MachOObjectFile::getPlainRelocationSymbolNum(const macho::RelocationEntry &RE) const {
1360 if (isLittleEndian())
1361 return RE.Word1 & 0xffffff;
1362 return RE.Word1 >> 8;
1365 bool MachOObjectFile::getPlainRelocationExternal(const macho::RelocationEntry &RE) const {
1366 if (isLittleEndian())
1367 return (RE.Word1 >> 27) & 1;
1368 return (RE.Word1 >> 4) & 1;
1372 MachOObjectFile::getScatteredRelocationScattered(const macho::RelocationEntry &RE) const {
1373 return RE.Word0 >> 31;
1377 MachOObjectFile::getScatteredRelocationValue(const macho::RelocationEntry &RE) const {
1382 MachOObjectFile::getAnyRelocationAddress(const macho::RelocationEntry &RE) const {
1383 if (isRelocationScattered(RE))
1384 return getScatteredRelocationAddress(RE);
1385 return getPlainRelocationAddress(RE);
1389 MachOObjectFile::getAnyRelocationPCRel(const macho::RelocationEntry &RE) const {
1390 if (isRelocationScattered(RE))
1391 return getScatteredRelocationPCRel(this, RE);
1392 return getPlainRelocationPCRel(this, RE);
1396 MachOObjectFile::getAnyRelocationLength(const macho::RelocationEntry &RE) const {
1397 if (isRelocationScattered(RE))
1398 return getScatteredRelocationLength(RE);
1399 return getPlainRelocationLength(this, RE);
1403 MachOObjectFile::getAnyRelocationType(const macho::RelocationEntry &RE) const {
1404 if (isRelocationScattered(RE))
1405 return getScatteredRelocationType(RE);
1406 return getPlainRelocationType(this, RE);
1410 MachOObjectFile::getRelocationSection(const macho::RelocationEntry &RE) const {
1411 if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
1412 return *end_sections();
1413 unsigned SecNum = getPlainRelocationSymbolNum(RE) - 1;
1416 return SectionRef(DRI, this);
1419 MachOObjectFile::LoadCommandInfo
1420 MachOObjectFile::getFirstLoadCommandInfo() const {
1421 MachOObjectFile::LoadCommandInfo Load;
1423 unsigned HeaderSize = is64Bit() ? macho::Header64Size : macho::Header32Size;
1424 Load.Ptr = getPtr(this, HeaderSize);
1425 Load.C = getStruct<macho::LoadCommand>(this, Load.Ptr);
1429 MachOObjectFile::LoadCommandInfo
1430 MachOObjectFile::getNextLoadCommandInfo(const LoadCommandInfo &L) const {
1431 MachOObjectFile::LoadCommandInfo Next;
1432 Next.Ptr = L.Ptr + L.C.Size;
1433 Next.C = getStruct<macho::LoadCommand>(this, Next.Ptr);
1437 macho::Section MachOObjectFile::getSection(DataRefImpl DRI) const {
1438 return getStruct<macho::Section>(this, Sections[DRI.d.a]);
1441 macho::Section64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
1442 return getStruct<macho::Section64>(this, Sections[DRI.d.a]);
1445 macho::Section MachOObjectFile::getSection(const LoadCommandInfo &L,
1446 unsigned Index) const {
1447 const char *Sec = getSectionPtr(this, L, Index);
1448 return getStruct<macho::Section>(this, Sec);
1451 macho::Section64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
1452 unsigned Index) const {
1453 const char *Sec = getSectionPtr(this, L, Index);
1454 return getStruct<macho::Section64>(this, Sec);
1457 macho::SymbolTableEntry
1458 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
1459 const char *P = reinterpret_cast<const char *>(DRI.p);
1460 return getStruct<macho::SymbolTableEntry>(this, P);
1463 macho::Symbol64TableEntry
1464 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
1465 const char *P = reinterpret_cast<const char *>(DRI.p);
1466 return getStruct<macho::Symbol64TableEntry>(this, P);
1469 macho::LinkeditDataLoadCommand
1470 MachOObjectFile::getLinkeditDataLoadCommand(const MachOObjectFile::LoadCommandInfo &L) const {
1471 return getStruct<macho::LinkeditDataLoadCommand>(this, L.Ptr);
1474 macho::SegmentLoadCommand
1475 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
1476 return getStruct<macho::SegmentLoadCommand>(this, L.Ptr);
1479 macho::Segment64LoadCommand
1480 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
1481 return getStruct<macho::Segment64LoadCommand>(this, L.Ptr);
1484 macho::LinkerOptionsLoadCommand
1485 MachOObjectFile::getLinkerOptionsLoadCommand(const LoadCommandInfo &L) const {
1486 return getStruct<macho::LinkerOptionsLoadCommand>(this, L.Ptr);
1489 macho::RelocationEntry
1490 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
1491 const char *P = reinterpret_cast<const char *>(Rel.p);
1492 return getStruct<macho::RelocationEntry>(this, P);
1495 macho::Header MachOObjectFile::getHeader() const {
1496 return getStruct<macho::Header>(this, getPtr(this, 0));
1499 macho::Header64Ext MachOObjectFile::getHeader64Ext() const {
1501 getStruct<macho::Header64Ext>(this, getPtr(this, sizeof(macho::Header)));
1504 macho::IndirectSymbolTableEntry MachOObjectFile::getIndirectSymbolTableEntry(
1505 const macho::DysymtabLoadCommand &DLC,
1506 unsigned Index) const {
1507 uint64_t Offset = DLC.IndirectSymbolTableOffset +
1508 Index * sizeof(macho::IndirectSymbolTableEntry);
1509 return getStruct<macho::IndirectSymbolTableEntry>(this, getPtr(this, Offset));
1512 macho::DataInCodeTableEntry
1513 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
1514 unsigned Index) const {
1515 uint64_t Offset = DataOffset + Index * sizeof(macho::DataInCodeTableEntry);
1516 return getStruct<macho::DataInCodeTableEntry>(this, getPtr(this, Offset));
1519 macho::SymtabLoadCommand MachOObjectFile::getSymtabLoadCommand() const {
1520 return getStruct<macho::SymtabLoadCommand>(this, SymtabLoadCmd);
1523 macho::DysymtabLoadCommand MachOObjectFile::getDysymtabLoadCommand() const {
1524 return getStruct<macho::DysymtabLoadCommand>(this, DysymtabLoadCmd);
1527 StringRef MachOObjectFile::getStringTableData() const {
1528 macho::SymtabLoadCommand S = getSymtabLoadCommand();
1529 return getData().substr(S.StringTableOffset, S.StringTableSize);
1532 bool MachOObjectFile::is64Bit() const {
1533 return getType() == getMachOType(false, true) ||
1534 getType() == getMachOType(true, true);
1537 void MachOObjectFile::ReadULEB128s(uint64_t Index,
1538 SmallVectorImpl<uint64_t> &Out) const {
1539 DataExtractor extractor(ObjectFile::getData(), true, 0);
1541 uint32_t offset = Index;
1543 while (uint64_t delta = extractor.getULEB128(&offset)) {
1545 Out.push_back(data);
1549 ObjectFile *ObjectFile::createMachOObjectFile(MemoryBuffer *Buffer) {
1550 StringRef Magic = Buffer->getBuffer().slice(0, 4);
1553 if (Magic == "\xFE\xED\xFA\xCE")
1554 Ret = new MachOObjectFile(Buffer, false, false, ec);
1555 else if (Magic == "\xCE\xFA\xED\xFE")
1556 Ret = new MachOObjectFile(Buffer, true, false, ec);
1557 else if (Magic == "\xFE\xED\xFA\xCF")
1558 Ret = new MachOObjectFile(Buffer, false, true, ec);
1559 else if (Magic == "\xCF\xFA\xED\xFE")
1560 Ret = new MachOObjectFile(Buffer, true, true, ec);
1569 } // end namespace object
1570 } // end namespace llvm