1 //===-- RuntimeDyldMachO.cpp - Run-time dynamic linker for MC-JIT -*- 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 // Implementation of the MC-JIT runtime dynamic linker.
12 //===----------------------------------------------------------------------===//
14 #include "RuntimeDyldMachO.h"
15 #include "Targets/RuntimeDyldMachOAArch64.h"
16 #include "Targets/RuntimeDyldMachOARM.h"
17 #include "Targets/RuntimeDyldMachOI386.h"
18 #include "Targets/RuntimeDyldMachOX86_64.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
23 using namespace llvm::object;
25 #define DEBUG_TYPE "dyld"
29 class LoadedMachOObjectInfo : public RuntimeDyld::LoadedObjectInfo {
31 LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
33 : RuntimeDyld::LoadedObjectInfo(RTDyld, BeginIdx, EndIdx) {}
35 OwningBinary<ObjectFile>
36 getObjectForDebug(const ObjectFile &Obj) const override {
37 return OwningBinary<ObjectFile>();
40 RuntimeDyld::LoadedObjectInfo *clone() const { return new LoadedMachOObjectInfo(*this); }
47 int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
48 unsigned NumBytes = 1 << RE.Size;
49 uint8_t *Src = Sections[RE.SectionID].Address + RE.Offset;
51 return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
54 RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
55 const ObjectFile &BaseTObj, const relocation_iterator &RI,
56 const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID) {
58 const MachOObjectFile &Obj =
59 static_cast<const MachOObjectFile &>(BaseTObj);
60 MachO::any_relocation_info RelInfo =
61 Obj.getRelocation(RI->getRawDataRefImpl());
62 RelocationValueRef Value;
64 bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
66 symbol_iterator Symbol = RI->getSymbol();
68 Symbol->getName(TargetName);
69 RTDyldSymbolTable::const_iterator SI =
70 GlobalSymbolTable.find(TargetName.data());
71 if (SI != GlobalSymbolTable.end()) {
72 const auto &SymInfo = SI->second;
73 Value.SectionID = SymInfo.getSectionID();
74 Value.Offset = SymInfo.getOffset() + RE.Addend;
76 Value.SymbolName = TargetName.data();
77 Value.Offset = RE.Addend;
80 SectionRef Sec = Obj.getAnyRelocationSection(RelInfo);
81 bool IsCode = Sec.isText();
82 Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
83 uint64_t Addr = Sec.getAddress();
84 Value.Offset = RE.Addend - Addr;
90 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
91 const ObjectFile &BaseTObj,
92 const relocation_iterator &RI,
93 unsigned OffsetToNextPC) {
94 const MachOObjectFile &Obj =
95 static_cast<const MachOObjectFile &>(BaseTObj);
96 MachO::any_relocation_info RelInfo =
97 Obj.getRelocation(RI->getRawDataRefImpl());
99 bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
101 uint64_t RelocAddr = 0;
102 RI->getAddress(RelocAddr);
103 Value.Offset += RelocAddr + OffsetToNextPC;
107 void RuntimeDyldMachO::dumpRelocationToResolve(const RelocationEntry &RE,
108 uint64_t Value) const {
109 const SectionEntry &Section = Sections[RE.SectionID];
110 uint8_t *LocalAddress = Section.Address + RE.Offset;
111 uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
113 dbgs() << "resolveRelocation Section: " << RE.SectionID
114 << " LocalAddress: " << format("%p", LocalAddress)
115 << " FinalAddress: " << format("0x%016" PRIx64, FinalAddress)
116 << " Value: " << format("0x%016" PRIx64, Value) << " Addend: " << RE.Addend
117 << " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
118 << " Size: " << (1 << RE.Size) << "\n";
122 RuntimeDyldMachO::getSectionByAddress(const MachOObjectFile &Obj,
124 section_iterator SI = Obj.section_begin();
125 section_iterator SE = Obj.section_end();
127 for (; SI != SE; ++SI) {
128 uint64_t SAddr = SI->getAddress();
129 uint64_t SSize = SI->getSize();
130 if ((Addr >= SAddr) && (Addr < SAddr + SSize))
138 // Populate __pointers section.
139 void RuntimeDyldMachO::populateIndirectSymbolPointersSection(
140 const MachOObjectFile &Obj,
141 const SectionRef &PTSection,
142 unsigned PTSectionID) {
143 assert(!Obj.is64Bit() &&
144 "Pointer table section not supported in 64-bit MachO.");
146 MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
147 MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
148 uint32_t PTSectionSize = Sec32.size;
149 unsigned FirstIndirectSymbol = Sec32.reserved1;
150 const unsigned PTEntrySize = 4;
151 unsigned NumPTEntries = PTSectionSize / PTEntrySize;
152 unsigned PTEntryOffset = 0;
154 assert((PTSectionSize % PTEntrySize) == 0 &&
155 "Pointers section does not contain a whole number of stubs?");
157 DEBUG(dbgs() << "Populating pointer table section "
158 << Sections[PTSectionID].Name
159 << ", Section ID " << PTSectionID << ", "
160 << NumPTEntries << " entries, " << PTEntrySize
161 << " bytes each:\n");
163 for (unsigned i = 0; i < NumPTEntries; ++i) {
164 unsigned SymbolIndex =
165 Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
166 symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
167 StringRef IndirectSymbolName;
168 SI->getName(IndirectSymbolName);
169 DEBUG(dbgs() << " " << IndirectSymbolName << ": index " << SymbolIndex
170 << ", PT offset: " << PTEntryOffset << "\n");
171 RelocationEntry RE(PTSectionID, PTEntryOffset,
172 MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
173 addRelocationForSymbol(RE, IndirectSymbolName);
174 PTEntryOffset += PTEntrySize;
178 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
179 return Obj.isMachO();
182 template <typename Impl>
183 void RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &Obj,
184 ObjSectionToIDMap &SectionMap) {
185 unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
186 unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
187 unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
189 for (const auto &Section : Obj.sections()) {
191 Section.getName(Name);
193 // Force emission of the __text, __eh_frame, and __gcc_except_tab sections
194 // if they're present. Otherwise call down to the impl to handle other
195 // sections that have already been emitted.
196 if (Name == "__text")
197 TextSID = findOrEmitSection(Obj, Section, true, SectionMap);
198 else if (Name == "__eh_frame")
199 EHFrameSID = findOrEmitSection(Obj, Section, false, SectionMap);
200 else if (Name == "__gcc_except_tab")
201 ExceptTabSID = findOrEmitSection(Obj, Section, true, SectionMap);
203 auto I = SectionMap.find(Section);
204 if (I != SectionMap.end())
205 impl().finalizeSection(Obj, I->second, Section);
208 UnregisteredEHFrameSections.push_back(
209 EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
212 template <typename Impl>
213 unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(unsigned char *P,
214 int64_t DeltaForText,
215 int64_t DeltaForEH) {
216 typedef typename Impl::TargetPtrT TargetPtrT;
218 DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
219 << ", Delta for EH: " << DeltaForEH << "\n");
220 uint32_t Length = readBytesUnaligned(P, 4);
222 unsigned char *Ret = P + Length;
223 uint32_t Offset = readBytesUnaligned(P, 4);
224 if (Offset == 0) // is a CIE
228 TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
229 TargetPtrT NewLocation = FDELocation - DeltaForText;
230 writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
232 P += sizeof(TargetPtrT);
234 // Skip the FDE address range
235 P += sizeof(TargetPtrT);
237 uint8_t Augmentationsize = *P;
239 if (Augmentationsize != 0) {
240 TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
241 TargetPtrT NewLSDA = LSDA - DeltaForEH;
242 writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
248 static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
249 int64_t ObjDistance =
250 static_cast<int64_t>(A->ObjAddress) - static_cast<int64_t>(B->ObjAddress);
251 int64_t MemDistance = A->LoadAddress - B->LoadAddress;
252 return ObjDistance - MemDistance;
255 template <typename Impl>
256 void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
258 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
259 EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
260 if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
261 SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
263 SectionEntry *Text = &Sections[SectionInfo.TextSID];
264 SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
265 SectionEntry *ExceptTab = nullptr;
266 if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
267 ExceptTab = &Sections[SectionInfo.ExceptTabSID];
269 int64_t DeltaForText = computeDelta(Text, EHFrame);
270 int64_t DeltaForEH = 0;
272 DeltaForEH = computeDelta(ExceptTab, EHFrame);
274 unsigned char *P = EHFrame->Address;
275 unsigned char *End = P + EHFrame->Size;
277 P = processFDE(P, DeltaForText, DeltaForEH);
280 MemMgr.registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
283 UnregisteredEHFrameSections.clear();
286 std::unique_ptr<RuntimeDyldMachO>
287 RuntimeDyldMachO::create(Triple::ArchType Arch,
288 RuntimeDyld::MemoryManager &MemMgr,
289 RuntimeDyld::SymbolResolver &Resolver) {
292 llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
295 return make_unique<RuntimeDyldMachOARM>(MemMgr, Resolver);
296 case Triple::aarch64:
297 return make_unique<RuntimeDyldMachOAArch64>(MemMgr, Resolver);
299 return make_unique<RuntimeDyldMachOI386>(MemMgr, Resolver);
301 return make_unique<RuntimeDyldMachOX86_64>(MemMgr, Resolver);
305 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
306 RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
307 unsigned SectionStartIdx, SectionEndIdx;
308 std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
309 return llvm::make_unique<LoadedMachOObjectInfo>(*this, SectionStartIdx,
313 } // end namespace llvm