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->getAnyRelocationAddress(RE);
345 symbol_iterator SI = O->begin_symbols();
349 section_iterator SI = O->begin_sections();
357 static uint32_t getPlainRelocationAddress(const macho::RelocationEntry &RE) {
362 getScatteredRelocationAddress(const macho::RelocationEntry &RE) {
363 return RE.Word0 & 0xffffff;
366 static bool getPlainRelocationPCRel(const MachOObjectFile *O,
367 const macho::RelocationEntry &RE) {
368 if (O->isLittleEndian())
369 return (RE.Word1 >> 24) & 1;
370 return (RE.Word1 >> 7) & 1;
374 getScatteredRelocationPCRel(const MachOObjectFile *O,
375 const macho::RelocationEntry &RE) {
376 return (RE.Word0 >> 30) & 1;
379 static unsigned getPlainRelocationLength(const MachOObjectFile *O,
380 const macho::RelocationEntry &RE) {
381 if (O->isLittleEndian())
382 return (RE.Word1 >> 25) & 3;
383 return (RE.Word1 >> 5) & 3;
387 getScatteredRelocationLength(const macho::RelocationEntry &RE) {
388 return (RE.Word0 >> 28) & 3;
391 static unsigned getPlainRelocationType(const MachOObjectFile *O,
392 const macho::RelocationEntry &RE) {
393 if (O->isLittleEndian())
394 return RE.Word1 >> 28;
395 return RE.Word1 & 0xf;
398 static unsigned getScatteredRelocationType(const macho::RelocationEntry &RE) {
399 return (RE.Word0 >> 24) & 0xf;
402 static uint32_t getSectionFlags(const MachOObjectFile *O,
405 macho::Section64 Sect = O->getSection64(Sec);
408 macho::Section Sect = O->getSection(Sec);
412 MachOObjectFile::MachOObjectFile(MemoryBuffer *Object,
413 bool IsLittleEndian, bool Is64bits,
415 : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object),
416 SymtabLoadCmd(NULL), DysymtabLoadCmd(NULL) {
417 uint32_t LoadCommandCount = this->getHeader().NumLoadCommands;
418 macho::LoadCommandType SegmentLoadType = is64Bit() ?
419 macho::LCT_Segment64 : macho::LCT_Segment;
421 MachOObjectFile::LoadCommandInfo Load = getFirstLoadCommandInfo();
422 for (unsigned I = 0; ; ++I) {
423 if (Load.C.Type == macho::LCT_Symtab) {
424 assert(!SymtabLoadCmd && "Multiple symbol tables");
425 SymtabLoadCmd = Load.Ptr;
426 } else if (Load.C.Type == macho::LCT_Dysymtab) {
427 assert(!DysymtabLoadCmd && "Multiple dynamic symbol tables");
428 DysymtabLoadCmd = Load.Ptr;
429 } else if (Load.C.Type == SegmentLoadType) {
430 uint32_t NumSections = getSegmentLoadCommandNumSections(this, Load);
431 for (unsigned J = 0; J < NumSections; ++J) {
432 const char *Sec = getSectionPtr(this, Load, J);
433 Sections.push_back(Sec);
437 if (I == LoadCommandCount - 1)
440 Load = getNextLoadCommandInfo(Load);
444 error_code MachOObjectFile::getSymbolNext(DataRefImpl Symb,
445 SymbolRef &Res) const {
446 unsigned SymbolTableEntrySize = is64Bit() ?
447 sizeof(macho::Symbol64TableEntry) :
448 sizeof(macho::SymbolTableEntry);
449 Symb.p += SymbolTableEntrySize;
450 Res = SymbolRef(Symb, this);
451 return object_error::success;
454 error_code MachOObjectFile::getSymbolName(DataRefImpl Symb,
455 StringRef &Res) const {
456 StringRef StringTable = getStringTableData();
457 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
458 const char *Start = &StringTable.data()[Entry.StringIndex];
459 Res = StringRef(Start);
460 return object_error::success;
463 error_code MachOObjectFile::getSymbolAddress(DataRefImpl Symb,
464 uint64_t &Res) const {
466 macho::Symbol64TableEntry Entry = getSymbol64TableEntry(Symb);
469 macho::SymbolTableEntry Entry = getSymbolTableEntry(Symb);
472 return object_error::success;
476 MachOObjectFile::getSymbolFileOffset(DataRefImpl Symb,
477 uint64_t &Res) const {
478 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
479 getSymbolAddress(Symb, Res);
480 if (Entry.SectionIndex) {
483 SecRel.d.a = Entry.SectionIndex-1;
485 macho::Section64 Sec = getSection64(SecRel);
486 Delta = Sec.Offset - Sec.Address;
488 macho::Section Sec = getSection(SecRel);
489 Delta = Sec.Offset - Sec.Address;
495 return object_error::success;
498 error_code MachOObjectFile::getSymbolSize(DataRefImpl DRI,
499 uint64_t &Result) const {
500 uint64_t BeginOffset;
501 uint64_t EndOffset = 0;
502 uint8_t SectionIndex;
504 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, DRI);
506 getSymbolAddress(DRI, Value);
510 SectionIndex = Entry.SectionIndex;
512 uint32_t flags = SymbolRef::SF_None;
513 this->getSymbolFlags(DRI, flags);
514 if (flags & SymbolRef::SF_Common)
517 Result = UnknownAddressOrSize;
518 return object_error::success;
520 // Unfortunately symbols are unsorted so we need to touch all
521 // symbols from load command
523 for (symbol_iterator I = begin_symbols(), E = end_symbols(); I != E;
525 DataRefImpl DRI = I->getRawDataRefImpl();
526 Entry = getSymbolTableEntryBase(this, DRI);
527 getSymbolAddress(DRI, Value);
528 if (Entry.SectionIndex == SectionIndex && Value > BeginOffset)
529 if (!EndOffset || Value < EndOffset)
535 Sec.d.a = SectionIndex-1;
536 getSectionSize(Sec, Size);
537 getSectionAddress(Sec, EndOffset);
540 Result = EndOffset - BeginOffset;
541 return object_error::success;
544 error_code MachOObjectFile::getSymbolType(DataRefImpl Symb,
545 SymbolRef::Type &Res) const {
546 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
547 uint8_t n_type = Entry.Type;
549 Res = SymbolRef::ST_Other;
551 // If this is a STAB debugging symbol, we can do nothing more.
552 if (n_type & MachO::NlistMaskStab) {
553 Res = SymbolRef::ST_Debug;
554 return object_error::success;
557 switch (n_type & MachO::NlistMaskType) {
558 case MachO::NListTypeUndefined :
559 Res = SymbolRef::ST_Unknown;
561 case MachO::NListTypeSection :
562 Res = SymbolRef::ST_Function;
565 return object_error::success;
568 error_code MachOObjectFile::getSymbolNMTypeChar(DataRefImpl Symb,
570 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
571 uint8_t Type = Entry.Type;
572 uint16_t Flags = Entry.Flags;
575 switch (Type & macho::STF_TypeMask) {
576 case macho::STT_Undefined:
579 case macho::STT_Absolute:
580 case macho::STT_Section:
588 if (Flags & (macho::STF_External | macho::STF_PrivateExtern))
589 Char = toupper(static_cast<unsigned char>(Char));
591 return object_error::success;
594 error_code MachOObjectFile::getSymbolFlags(DataRefImpl DRI,
595 uint32_t &Result) const {
596 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, DRI);
598 uint8_t MachOType = Entry.Type;
599 uint16_t MachOFlags = Entry.Flags;
601 // TODO: Correctly set SF_ThreadLocal
602 Result = SymbolRef::SF_None;
604 if ((MachOType & MachO::NlistMaskType) == MachO::NListTypeUndefined)
605 Result |= SymbolRef::SF_Undefined;
607 if (MachOFlags & macho::STF_StabsEntryMask)
608 Result |= SymbolRef::SF_FormatSpecific;
610 if (MachOType & MachO::NlistMaskExternal) {
611 Result |= SymbolRef::SF_Global;
612 if ((MachOType & MachO::NlistMaskType) == MachO::NListTypeUndefined)
613 Result |= SymbolRef::SF_Common;
616 if (MachOFlags & (MachO::NListDescWeakRef | MachO::NListDescWeakDef))
617 Result |= SymbolRef::SF_Weak;
619 if ((MachOType & MachO::NlistMaskType) == MachO::NListTypeAbsolute)
620 Result |= SymbolRef::SF_Absolute;
622 return object_error::success;
626 MachOObjectFile::getSymbolSection(DataRefImpl Symb,
627 section_iterator &Res) const {
628 SymbolTableEntryBase Entry = getSymbolTableEntryBase(this, Symb);
629 uint8_t index = Entry.SectionIndex;
632 Res = end_sections();
636 Res = section_iterator(SectionRef(DRI, this));
639 return object_error::success;
642 error_code MachOObjectFile::getSymbolValue(DataRefImpl Symb,
643 uint64_t &Val) const {
644 report_fatal_error("getSymbolValue unimplemented in MachOObjectFile");
647 error_code MachOObjectFile::getSectionNext(DataRefImpl Sec,
648 SectionRef &Res) const {
650 Res = SectionRef(Sec, this);
651 return object_error::success;
655 MachOObjectFile::getSectionName(DataRefImpl Sec, StringRef &Result) const {
656 ArrayRef<char> Raw = getSectionRawName(Sec);
657 Result = parseSegmentOrSectionName(Raw.data());
658 return object_error::success;
662 MachOObjectFile::getSectionAddress(DataRefImpl Sec, uint64_t &Res) const {
664 macho::Section64 Sect = getSection64(Sec);
667 macho::Section Sect = getSection(Sec);
670 return object_error::success;
674 MachOObjectFile::getSectionSize(DataRefImpl Sec, uint64_t &Res) const {
676 macho::Section64 Sect = getSection64(Sec);
679 macho::Section Sect = getSection(Sec);
683 return object_error::success;
687 MachOObjectFile::getSectionContents(DataRefImpl Sec, StringRef &Res) const {
692 macho::Section64 Sect = getSection64(Sec);
693 Offset = Sect.Offset;
696 macho::Section Sect =getSection(Sec);
697 Offset = Sect.Offset;
701 Res = this->getData().substr(Offset, Size);
702 return object_error::success;
706 MachOObjectFile::getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const {
709 macho::Section64 Sect = getSection64(Sec);
712 macho::Section Sect = getSection(Sec);
716 Res = uint64_t(1) << Align;
717 return object_error::success;
721 MachOObjectFile::isSectionText(DataRefImpl Sec, bool &Res) const {
722 uint32_t Flags = getSectionFlags(this, Sec);
723 Res = Flags & macho::SF_PureInstructions;
724 return object_error::success;
727 error_code MachOObjectFile::isSectionData(DataRefImpl DRI, bool &Result) const {
728 // FIXME: Unimplemented.
730 return object_error::success;
733 error_code MachOObjectFile::isSectionBSS(DataRefImpl DRI, bool &Result) const {
734 // FIXME: Unimplemented.
736 return object_error::success;
740 MachOObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
741 bool &Result) const {
742 // FIXME: Unimplemented.
744 return object_error::success;
747 error_code MachOObjectFile::isSectionVirtual(DataRefImpl Sec,
748 bool &Result) const {
749 // FIXME: Unimplemented.
751 return object_error::success;
755 MachOObjectFile::isSectionZeroInit(DataRefImpl Sec, bool &Res) const {
756 uint32_t Flags = getSectionFlags(this, Sec);
757 unsigned SectionType = Flags & MachO::SectionFlagMaskSectionType;
758 Res = SectionType == MachO::SectionTypeZeroFill ||
759 SectionType == MachO::SectionTypeZeroFillLarge;
760 return object_error::success;
763 error_code MachOObjectFile::isSectionReadOnlyData(DataRefImpl Sec,
764 bool &Result) const {
765 // Consider using the code from isSectionText to look for __const sections.
766 // Alternately, emit S_ATTR_PURE_INSTRUCTIONS and/or S_ATTR_SOME_INSTRUCTIONS
767 // to use section attributes to distinguish code from data.
769 // FIXME: Unimplemented.
771 return object_error::success;
775 MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Symb,
776 bool &Result) const {
778 this->getSymbolType(Symb, ST);
779 if (ST == SymbolRef::ST_Unknown) {
781 return object_error::success;
784 uint64_t SectBegin, SectEnd;
785 getSectionAddress(Sec, SectBegin);
786 getSectionSize(Sec, SectEnd);
787 SectEnd += SectBegin;
790 getSymbolAddress(Symb, SymAddr);
791 Result = (SymAddr >= SectBegin) && (SymAddr < SectEnd);
793 return object_error::success;
796 relocation_iterator MachOObjectFile::getSectionRelBegin(DataRefImpl Sec) const {
799 macho::Section64 Sect = getSection64(Sec);
800 Offset = Sect.RelocationTableOffset;
802 macho::Section Sect = getSection(Sec);
803 Offset = Sect.RelocationTableOffset;
807 Ret.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
808 return relocation_iterator(RelocationRef(Ret, this));
812 MachOObjectFile::getSectionRelEnd(DataRefImpl Sec) const {
816 macho::Section64 Sect = getSection64(Sec);
817 Offset = Sect.RelocationTableOffset;
818 Num = Sect.NumRelocationTableEntries;
820 macho::Section Sect = getSection(Sec);
821 Offset = Sect.RelocationTableOffset;
822 Num = Sect.NumRelocationTableEntries;
825 const macho::RelocationEntry *P =
826 reinterpret_cast<const macho::RelocationEntry*>(getPtr(this, Offset));
829 Ret.p = reinterpret_cast<uintptr_t>(P + Num);
830 return relocation_iterator(RelocationRef(Ret, this));
833 error_code MachOObjectFile::getRelocationNext(DataRefImpl Rel,
834 RelocationRef &Res) const {
835 const macho::RelocationEntry *P =
836 reinterpret_cast<const macho::RelocationEntry *>(Rel.p);
837 Rel.p = reinterpret_cast<uintptr_t>(P + 1);
838 Res = RelocationRef(Rel, this);
839 return object_error::success;
843 MachOObjectFile::getRelocationAddress(DataRefImpl Rel, uint64_t &Res) const {
844 report_fatal_error("getRelocationAddress not implemented in MachOObjectFile");
847 error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
848 uint64_t &Res) const {
849 macho::RelocationEntry RE = getRelocation(Rel);
850 Res = getAnyRelocationAddress(RE);
851 return object_error::success;
855 MachOObjectFile::getRelocationSymbol(DataRefImpl Rel, SymbolRef &Res) const {
856 macho::RelocationEntry RE = getRelocation(Rel);
857 uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
858 bool isExtern = getPlainRelocationExternal(RE);
860 Res = *end_symbols();
861 return object_error::success;
864 macho::SymtabLoadCommand S = getSymtabLoadCommand();
865 unsigned SymbolTableEntrySize = is64Bit() ?
866 sizeof(macho::Symbol64TableEntry) :
867 sizeof(macho::SymbolTableEntry);
868 uint64_t Offset = S.SymbolTableOffset + SymbolIdx * SymbolTableEntrySize;
870 Sym.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
871 Res = SymbolRef(Sym, this);
872 return object_error::success;
875 error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
876 uint64_t &Res) const {
877 macho::RelocationEntry RE = getRelocation(Rel);
878 Res = getAnyRelocationType(RE);
879 return object_error::success;
883 MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
884 SmallVectorImpl<char> &Result) const {
887 getRelocationType(Rel, RType);
889 unsigned Arch = this->getArch();
893 static const char *const Table[] = {
894 "GENERIC_RELOC_VANILLA",
895 "GENERIC_RELOC_PAIR",
896 "GENERIC_RELOC_SECTDIFF",
897 "GENERIC_RELOC_PB_LA_PTR",
898 "GENERIC_RELOC_LOCAL_SECTDIFF",
899 "GENERIC_RELOC_TLV" };
907 case Triple::x86_64: {
908 static const char *const Table[] = {
909 "X86_64_RELOC_UNSIGNED",
910 "X86_64_RELOC_SIGNED",
911 "X86_64_RELOC_BRANCH",
912 "X86_64_RELOC_GOT_LOAD",
914 "X86_64_RELOC_SUBTRACTOR",
915 "X86_64_RELOC_SIGNED_1",
916 "X86_64_RELOC_SIGNED_2",
917 "X86_64_RELOC_SIGNED_4",
918 "X86_64_RELOC_TLV" };
927 static const char *const Table[] = {
930 "ARM_RELOC_SECTDIFF",
931 "ARM_RELOC_LOCAL_SECTDIFF",
932 "ARM_RELOC_PB_LA_PTR",
934 "ARM_THUMB_RELOC_BR22",
935 "ARM_THUMB_32BIT_BRANCH",
937 "ARM_RELOC_HALF_SECTDIFF" };
946 static const char *const Table[] = {
955 "PPC_RELOC_SECTDIFF",
956 "PPC_RELOC_PB_LA_PTR",
957 "PPC_RELOC_HI16_SECTDIFF",
958 "PPC_RELOC_LO16_SECTDIFF",
959 "PPC_RELOC_HA16_SECTDIFF",
961 "PPC_RELOC_LO14_SECTDIFF",
962 "PPC_RELOC_LOCAL_SECTDIFF" };
967 case Triple::UnknownArch:
971 Result.append(res.begin(), res.end());
972 return object_error::success;
975 error_code MachOObjectFile::getRelocationAdditionalInfo(DataRefImpl Rel,
976 int64_t &Res) const {
978 return object_error::success;
982 MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
983 SmallVectorImpl<char> &Result) const {
984 macho::RelocationEntry RE = getRelocation(Rel);
986 unsigned Arch = this->getArch();
989 raw_string_ostream fmt(fmtbuf);
990 unsigned Type = this->getAnyRelocationType(RE);
991 bool IsPCRel = this->getAnyRelocationPCRel(RE);
993 // Determine any addends that should be displayed with the relocation.
994 // These require decoding the relocation type, which is triple-specific.
996 // X86_64 has entirely custom relocation types.
997 if (Arch == Triple::x86_64) {
998 bool isPCRel = getAnyRelocationPCRel(RE);
1001 case macho::RIT_X86_64_GOTLoad: // X86_64_RELOC_GOT_LOAD
1002 case macho::RIT_X86_64_GOT: { // X86_64_RELOC_GOT
1003 printRelocationTargetName(this, RE, fmt);
1005 if (isPCRel) fmt << "PCREL";
1008 case macho::RIT_X86_64_Subtractor: { // X86_64_RELOC_SUBTRACTOR
1009 DataRefImpl RelNext = Rel;
1011 macho::RelocationEntry RENext = getRelocation(RelNext);
1013 // X86_64_SUBTRACTOR must be followed by a relocation of type
1014 // X86_64_RELOC_UNSIGNED.
1015 // NOTE: Scattered relocations don't exist on x86_64.
1016 unsigned RType = getAnyRelocationType(RENext);
1018 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
1019 "X86_64_RELOC_SUBTRACTOR.");
1021 // The X86_64_RELOC_UNSIGNED contains the minuend symbol,
1022 // X86_64_SUBTRACTOR contains to the subtrahend.
1023 printRelocationTargetName(this, RENext, fmt);
1025 printRelocationTargetName(this, RE, fmt);
1028 case macho::RIT_X86_64_TLV:
1029 printRelocationTargetName(this, RE, fmt);
1031 if (isPCRel) fmt << "P";
1033 case macho::RIT_X86_64_Signed1: // X86_64_RELOC_SIGNED1
1034 printRelocationTargetName(this, RE, fmt);
1037 case macho::RIT_X86_64_Signed2: // X86_64_RELOC_SIGNED2
1038 printRelocationTargetName(this, RE, fmt);
1041 case macho::RIT_X86_64_Signed4: // X86_64_RELOC_SIGNED4
1042 printRelocationTargetName(this, RE, fmt);
1046 printRelocationTargetName(this, RE, fmt);
1049 // X86 and ARM share some relocation types in common.
1050 } else if (Arch == Triple::x86 || Arch == Triple::arm) {
1051 // Generic relocation types...
1053 case macho::RIT_Pair: // GENERIC_RELOC_PAIR - prints no info
1054 return object_error::success;
1055 case macho::RIT_Difference: { // GENERIC_RELOC_SECTDIFF
1056 DataRefImpl RelNext = Rel;
1058 macho::RelocationEntry RENext = getRelocation(RelNext);
1060 // X86 sect diff's must be followed by a relocation of type
1061 // GENERIC_RELOC_PAIR.
1062 unsigned RType = getAnyRelocationType(RENext);
1065 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1066 "GENERIC_RELOC_SECTDIFF.");
1068 printRelocationTargetName(this, RE, fmt);
1070 printRelocationTargetName(this, RENext, fmt);
1075 if (Arch == Triple::x86) {
1076 // All X86 relocations that need special printing were already
1077 // handled in the generic code.
1079 case macho::RIT_Generic_LocalDifference:{// GENERIC_RELOC_LOCAL_SECTDIFF
1080 DataRefImpl RelNext = Rel;
1082 macho::RelocationEntry RENext = getRelocation(RelNext);
1084 // X86 sect diff's must be followed by a relocation of type
1085 // GENERIC_RELOC_PAIR.
1086 unsigned RType = getAnyRelocationType(RENext);
1088 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
1089 "GENERIC_RELOC_LOCAL_SECTDIFF.");
1091 printRelocationTargetName(this, RE, fmt);
1093 printRelocationTargetName(this, RENext, fmt);
1096 case macho::RIT_Generic_TLV: {
1097 printRelocationTargetName(this, RE, fmt);
1099 if (IsPCRel) fmt << "P";
1103 printRelocationTargetName(this, RE, fmt);
1105 } else { // ARM-specific relocations
1107 case macho::RIT_ARM_Half: // ARM_RELOC_HALF
1108 case macho::RIT_ARM_HalfDifference: { // ARM_RELOC_HALF_SECTDIFF
1109 // Half relocations steal a bit from the length field to encode
1110 // whether this is an upper16 or a lower16 relocation.
1111 bool isUpper = getAnyRelocationLength(RE) >> 1;
1114 fmt << ":upper16:(";
1116 fmt << ":lower16:(";
1117 printRelocationTargetName(this, RE, fmt);
1119 DataRefImpl RelNext = Rel;
1121 macho::RelocationEntry RENext = getRelocation(RelNext);
1123 // ARM half relocs must be followed by a relocation of type
1125 unsigned RType = getAnyRelocationType(RENext);
1127 report_fatal_error("Expected ARM_RELOC_PAIR after "
1128 "GENERIC_RELOC_HALF");
1130 // NOTE: The half of the target virtual address is stashed in the
1131 // address field of the secondary relocation, but we can't reverse
1132 // engineer the constant offset from it without decoding the movw/movt
1133 // instruction to find the other half in its immediate field.
1135 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1136 // symbol/section pointer of the follow-on relocation.
1137 if (Type == macho::RIT_ARM_HalfDifference) {
1139 printRelocationTargetName(this, RENext, fmt);
1146 printRelocationTargetName(this, RE, fmt);
1151 printRelocationTargetName(this, RE, fmt);
1154 Result.append(fmtbuf.begin(), fmtbuf.end());
1155 return object_error::success;
1159 MachOObjectFile::getRelocationHidden(DataRefImpl Rel, bool &Result) const {
1160 unsigned Arch = getArch();
1162 getRelocationType(Rel, Type);
1166 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1167 // is always hidden.
1168 if (Arch == Triple::x86 || Arch == Triple::arm) {
1169 if (Type == macho::RIT_Pair) Result = true;
1170 } else if (Arch == Triple::x86_64) {
1171 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1172 // an X864_64_RELOC_SUBTRACTOR.
1173 if (Type == macho::RIT_X86_64_Unsigned && Rel.d.a > 0) {
1174 DataRefImpl RelPrev = Rel;
1177 getRelocationType(RelPrev, PrevType);
1178 if (PrevType == macho::RIT_X86_64_Subtractor)
1183 return object_error::success;
1186 error_code MachOObjectFile::getLibraryNext(DataRefImpl LibData,
1187 LibraryRef &Res) const {
1188 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1191 error_code MachOObjectFile::getLibraryPath(DataRefImpl LibData,
1192 StringRef &Res) const {
1193 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1196 symbol_iterator MachOObjectFile::begin_symbols() const {
1199 return symbol_iterator(SymbolRef(DRI, this));
1201 macho::SymtabLoadCommand Symtab = getSymtabLoadCommand();
1202 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Symtab.SymbolTableOffset));
1203 return symbol_iterator(SymbolRef(DRI, this));
1206 symbol_iterator MachOObjectFile::end_symbols() const {
1209 return symbol_iterator(SymbolRef(DRI, this));
1211 macho::SymtabLoadCommand Symtab = getSymtabLoadCommand();
1212 unsigned SymbolTableEntrySize = is64Bit() ?
1213 sizeof(macho::Symbol64TableEntry) :
1214 sizeof(macho::SymbolTableEntry);
1215 unsigned Offset = Symtab.SymbolTableOffset +
1216 Symtab.NumSymbolTableEntries * SymbolTableEntrySize;
1217 DRI.p = reinterpret_cast<uintptr_t>(getPtr(this, Offset));
1218 return symbol_iterator(SymbolRef(DRI, this));
1221 symbol_iterator MachOObjectFile::begin_dynamic_symbols() const {
1223 report_fatal_error("Dynamic symbols unimplemented in MachOObjectFile");
1226 symbol_iterator MachOObjectFile::end_dynamic_symbols() const {
1228 report_fatal_error("Dynamic symbols unimplemented in MachOObjectFile");
1231 section_iterator MachOObjectFile::begin_sections() const {
1233 return section_iterator(SectionRef(DRI, this));
1236 section_iterator MachOObjectFile::end_sections() const {
1238 DRI.d.a = Sections.size();
1239 return section_iterator(SectionRef(DRI, this));
1242 library_iterator MachOObjectFile::begin_libraries_needed() const {
1244 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1247 library_iterator MachOObjectFile::end_libraries_needed() const {
1249 report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
1252 uint8_t MachOObjectFile::getBytesInAddress() const {
1253 return is64Bit() ? 8 : 4;
1256 StringRef MachOObjectFile::getFileFormatName() const {
1257 unsigned CPUType = getCPUType(this);
1260 case llvm::MachO::CPUTypeI386:
1261 return "Mach-O 32-bit i386";
1262 case llvm::MachO::CPUTypeARM:
1263 return "Mach-O arm";
1264 case llvm::MachO::CPUTypePowerPC:
1265 return "Mach-O 32-bit ppc";
1267 assert((CPUType & llvm::MachO::CPUArchABI64) == 0 &&
1268 "64-bit object file when we're not 64-bit?");
1269 return "Mach-O 32-bit unknown";
1273 // Make sure the cpu type has the correct mask.
1274 assert((CPUType & llvm::MachO::CPUArchABI64)
1275 == llvm::MachO::CPUArchABI64 &&
1276 "32-bit object file when we're 64-bit?");
1279 case llvm::MachO::CPUTypeX86_64:
1280 return "Mach-O 64-bit x86-64";
1281 case llvm::MachO::CPUTypePowerPC64:
1282 return "Mach-O 64-bit ppc64";
1284 return "Mach-O 64-bit unknown";
1288 unsigned MachOObjectFile::getArch() const {
1289 switch (getCPUType(this)) {
1290 case llvm::MachO::CPUTypeI386:
1292 case llvm::MachO::CPUTypeX86_64:
1293 return Triple::x86_64;
1294 case llvm::MachO::CPUTypeARM:
1296 case llvm::MachO::CPUTypePowerPC:
1298 case llvm::MachO::CPUTypePowerPC64:
1299 return Triple::ppc64;
1301 return Triple::UnknownArch;
1305 StringRef MachOObjectFile::getLoadName() const {
1307 report_fatal_error("get_load_name() unimplemented in MachOObjectFile");
1310 relocation_iterator MachOObjectFile::getSectionRelBegin(unsigned Index) const {
1313 return getSectionRelBegin(DRI);
1316 relocation_iterator MachOObjectFile::getSectionRelEnd(unsigned Index) const {
1319 return getSectionRelEnd(DRI);
1323 MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
1324 ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
1325 return parseSegmentOrSectionName(Raw.data());
1329 MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
1330 const SectionBase *Base =
1331 reinterpret_cast<const SectionBase*>(Sections[Sec.d.a]);
1332 return ArrayRef<char>(Base->Name);
1336 MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
1337 const SectionBase *Base =
1338 reinterpret_cast<const SectionBase*>(Sections[Sec.d.a]);
1339 return ArrayRef<char>(Base->SegmentName);
1343 MachOObjectFile::isRelocationScattered(const macho::RelocationEntry &RE)
1345 if (getCPUType(this) == llvm::MachO::CPUTypeX86_64)
1347 return getPlainRelocationAddress(RE) & macho::RF_Scattered;
1350 unsigned MachOObjectFile::getPlainRelocationSymbolNum(const macho::RelocationEntry &RE) const {
1351 if (isLittleEndian())
1352 return RE.Word1 & 0xffffff;
1353 return RE.Word1 >> 8;
1356 bool MachOObjectFile::getPlainRelocationExternal(const macho::RelocationEntry &RE) const {
1357 if (isLittleEndian())
1358 return (RE.Word1 >> 27) & 1;
1359 return (RE.Word1 >> 4) & 1;
1363 MachOObjectFile::getScatteredRelocationScattered(const macho::RelocationEntry &RE) const {
1364 return RE.Word0 >> 31;
1368 MachOObjectFile::getScatteredRelocationValue(const macho::RelocationEntry &RE) const {
1373 MachOObjectFile::getAnyRelocationAddress(const macho::RelocationEntry &RE) const {
1374 if (isRelocationScattered(RE))
1375 return getScatteredRelocationAddress(RE);
1376 return getPlainRelocationAddress(RE);
1380 MachOObjectFile::getAnyRelocationPCRel(const macho::RelocationEntry &RE) const {
1381 if (isRelocationScattered(RE))
1382 return getScatteredRelocationPCRel(this, RE);
1383 return getPlainRelocationPCRel(this, RE);
1387 MachOObjectFile::getAnyRelocationLength(const macho::RelocationEntry &RE) const {
1388 if (isRelocationScattered(RE))
1389 return getScatteredRelocationLength(RE);
1390 return getPlainRelocationLength(this, RE);
1394 MachOObjectFile::getAnyRelocationType(const macho::RelocationEntry &RE) const {
1395 if (isRelocationScattered(RE))
1396 return getScatteredRelocationType(RE);
1397 return getPlainRelocationType(this, RE);
1400 MachOObjectFile::LoadCommandInfo
1401 MachOObjectFile::getFirstLoadCommandInfo() const {
1402 MachOObjectFile::LoadCommandInfo Load;
1404 unsigned HeaderSize = is64Bit() ? macho::Header64Size : macho::Header32Size;
1405 Load.Ptr = getPtr(this, HeaderSize);
1406 Load.C = getStruct<macho::LoadCommand>(this, Load.Ptr);
1410 MachOObjectFile::LoadCommandInfo
1411 MachOObjectFile::getNextLoadCommandInfo(const LoadCommandInfo &L) const {
1412 MachOObjectFile::LoadCommandInfo Next;
1413 Next.Ptr = L.Ptr + L.C.Size;
1414 Next.C = getStruct<macho::LoadCommand>(this, Next.Ptr);
1418 macho::Section MachOObjectFile::getSection(DataRefImpl DRI) const {
1419 return getStruct<macho::Section>(this, Sections[DRI.d.a]);
1422 macho::Section64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
1423 return getStruct<macho::Section64>(this, Sections[DRI.d.a]);
1426 macho::Section MachOObjectFile::getSection(const LoadCommandInfo &L,
1427 unsigned Index) const {
1428 const char *Sec = getSectionPtr(this, L, Index);
1429 return getStruct<macho::Section>(this, Sec);
1432 macho::Section64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
1433 unsigned Index) const {
1434 const char *Sec = getSectionPtr(this, L, Index);
1435 return getStruct<macho::Section64>(this, Sec);
1438 macho::SymbolTableEntry
1439 MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
1440 const char *P = reinterpret_cast<const char *>(DRI.p);
1441 return getStruct<macho::SymbolTableEntry>(this, P);
1444 macho::Symbol64TableEntry
1445 MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
1446 const char *P = reinterpret_cast<const char *>(DRI.p);
1447 return getStruct<macho::Symbol64TableEntry>(this, P);
1450 macho::LinkeditDataLoadCommand
1451 MachOObjectFile::getLinkeditDataLoadCommand(const MachOObjectFile::LoadCommandInfo &L) const {
1452 return getStruct<macho::LinkeditDataLoadCommand>(this, L.Ptr);
1455 macho::SegmentLoadCommand
1456 MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
1457 return getStruct<macho::SegmentLoadCommand>(this, L.Ptr);
1460 macho::Segment64LoadCommand
1461 MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
1462 return getStruct<macho::Segment64LoadCommand>(this, L.Ptr);
1465 macho::LinkerOptionsLoadCommand
1466 MachOObjectFile::getLinkerOptionsLoadCommand(const LoadCommandInfo &L) const {
1467 return getStruct<macho::LinkerOptionsLoadCommand>(this, L.Ptr);
1470 macho::RelocationEntry
1471 MachOObjectFile::getRelocation(DataRefImpl Rel) const {
1472 const char *P = reinterpret_cast<const char *>(Rel.p);
1473 return getStruct<macho::RelocationEntry>(this, P);
1476 macho::Header MachOObjectFile::getHeader() const {
1477 return getStruct<macho::Header>(this, getPtr(this, 0));
1480 macho::Header64Ext MachOObjectFile::getHeader64Ext() const {
1482 getStruct<macho::Header64Ext>(this, getPtr(this, sizeof(macho::Header)));
1485 macho::IndirectSymbolTableEntry MachOObjectFile::getIndirectSymbolTableEntry(
1486 const macho::DysymtabLoadCommand &DLC,
1487 unsigned Index) const {
1488 uint64_t Offset = DLC.IndirectSymbolTableOffset +
1489 Index * sizeof(macho::IndirectSymbolTableEntry);
1490 return getStruct<macho::IndirectSymbolTableEntry>(this, getPtr(this, Offset));
1493 macho::DataInCodeTableEntry
1494 MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
1495 unsigned Index) const {
1496 uint64_t Offset = DataOffset + Index * sizeof(macho::DataInCodeTableEntry);
1497 return getStruct<macho::DataInCodeTableEntry>(this, getPtr(this, Offset));
1500 macho::SymtabLoadCommand MachOObjectFile::getSymtabLoadCommand() const {
1501 return getStruct<macho::SymtabLoadCommand>(this, SymtabLoadCmd);
1504 macho::DysymtabLoadCommand MachOObjectFile::getDysymtabLoadCommand() const {
1505 return getStruct<macho::DysymtabLoadCommand>(this, DysymtabLoadCmd);
1508 StringRef MachOObjectFile::getStringTableData() const {
1509 macho::SymtabLoadCommand S = getSymtabLoadCommand();
1510 return getData().substr(S.StringTableOffset, S.StringTableSize);
1513 bool MachOObjectFile::is64Bit() const {
1514 return getType() == getMachOType(false, true) ||
1515 getType() == getMachOType(true, true);
1518 void MachOObjectFile::ReadULEB128s(uint64_t Index,
1519 SmallVectorImpl<uint64_t> &Out) const {
1520 DataExtractor extractor(ObjectFile::getData(), true, 0);
1522 uint32_t offset = Index;
1524 while (uint64_t delta = extractor.getULEB128(&offset)) {
1526 Out.push_back(data);
1530 ObjectFile *ObjectFile::createMachOObjectFile(MemoryBuffer *Buffer) {
1531 StringRef Magic = Buffer->getBuffer().slice(0, 4);
1534 if (Magic == "\xFE\xED\xFA\xCE")
1535 Ret = new MachOObjectFile(Buffer, false, false, ec);
1536 else if (Magic == "\xCE\xFA\xED\xFE")
1537 Ret = new MachOObjectFile(Buffer, true, false, ec);
1538 else if (Magic == "\xFE\xED\xFA\xCF")
1539 Ret = new MachOObjectFile(Buffer, false, true, ec);
1540 else if (Magic == "\xCF\xFA\xED\xFE")
1541 Ret = new MachOObjectFile(Buffer, true, true, ec);
1550 } // end namespace object
1551 } // end namespace llvm