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 final
30 : public LoadedObjectInfoHelper<LoadedMachOObjectInfo,
31 RuntimeDyld::LoadedObjectInfo> {
33 LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld,
34 ObjSectionToIDMap ObjSecToIDMap)
35 : LoadedObjectInfoHelper(RTDyld, std::move(ObjSecToIDMap)) {}
37 OwningBinary<ObjectFile>
38 getObjectForDebug(const ObjectFile &Obj) const override {
39 return OwningBinary<ObjectFile>();
47 int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
48 unsigned NumBytes = 1 << RE.Size;
49 uint8_t *Src = Sections[RE.SectionID].getAddress() + RE.Offset;
51 return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
54 Expected<relocation_iterator>
55 RuntimeDyldMachO::processScatteredVANILLA(
56 unsigned SectionID, relocation_iterator RelI,
57 const ObjectFile &BaseObjT,
58 RuntimeDyldMachO::ObjSectionToIDMap &ObjSectionToID) {
59 const MachOObjectFile &Obj =
60 static_cast<const MachOObjectFile&>(BaseObjT);
61 MachO::any_relocation_info RE =
62 Obj.getRelocation(RelI->getRawDataRefImpl());
64 SectionEntry &Section = Sections[SectionID];
65 uint32_t RelocType = Obj.getAnyRelocationType(RE);
66 bool IsPCRel = Obj.getAnyRelocationPCRel(RE);
67 unsigned Size = Obj.getAnyRelocationLength(RE);
68 uint64_t Offset = RelI->getOffset();
69 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
70 unsigned NumBytes = 1 << Size;
71 int64_t Addend = readBytesUnaligned(LocalAddress, NumBytes);
73 unsigned SymbolBaseAddr = Obj.getScatteredRelocationValue(RE);
74 section_iterator TargetSI = getSectionByAddress(Obj, SymbolBaseAddr);
75 assert(TargetSI != Obj.section_end() && "Can't find section for symbol");
76 uint64_t SectionBaseAddr = TargetSI->getAddress();
77 SectionRef TargetSection = *TargetSI;
78 bool IsCode = TargetSection.isText();
79 uint32_t TargetSectionID = ~0U;
80 if (auto TargetSectionIDOrErr =
81 findOrEmitSection(Obj, TargetSection, IsCode, ObjSectionToID))
82 TargetSectionID = *TargetSectionIDOrErr;
84 return TargetSectionIDOrErr.takeError();
86 Addend -= SectionBaseAddr;
87 RelocationEntry R(SectionID, Offset, RelocType, Addend, IsPCRel, Size);
89 addRelocationForSection(R, TargetSectionID);
95 Expected<RelocationValueRef>
96 RuntimeDyldMachO::getRelocationValueRef(
97 const ObjectFile &BaseTObj, const relocation_iterator &RI,
98 const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID) {
100 const MachOObjectFile &Obj =
101 static_cast<const MachOObjectFile &>(BaseTObj);
102 MachO::any_relocation_info RelInfo =
103 Obj.getRelocation(RI->getRawDataRefImpl());
104 RelocationValueRef Value;
106 bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
108 symbol_iterator Symbol = RI->getSymbol();
109 StringRef TargetName;
110 if (auto TargetNameOrErr = Symbol->getName())
111 TargetName = *TargetNameOrErr;
113 return TargetNameOrErr.takeError();
114 RTDyldSymbolTable::const_iterator SI =
115 GlobalSymbolTable.find(TargetName.data());
116 if (SI != GlobalSymbolTable.end()) {
117 const auto &SymInfo = SI->second;
118 Value.SectionID = SymInfo.getSectionID();
119 Value.Offset = SymInfo.getOffset() + RE.Addend;
121 Value.SymbolName = TargetName.data();
122 Value.Offset = RE.Addend;
125 SectionRef Sec = Obj.getAnyRelocationSection(RelInfo);
126 bool IsCode = Sec.isText();
127 if (auto SectionIDOrErr = findOrEmitSection(Obj, Sec, IsCode,
129 Value.SectionID = *SectionIDOrErr;
131 return SectionIDOrErr.takeError();
132 uint64_t Addr = Sec.getAddress();
133 Value.Offset = RE.Addend - Addr;
139 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
140 const relocation_iterator &RI,
141 unsigned OffsetToNextPC) {
142 auto &O = *cast<MachOObjectFile>(RI->getObject());
143 section_iterator SecI = O.getRelocationRelocatedSection(RI);
144 Value.Offset += RI->getOffset() + OffsetToNextPC + SecI->getAddress();
147 void RuntimeDyldMachO::dumpRelocationToResolve(const RelocationEntry &RE,
148 uint64_t Value) const {
149 const SectionEntry &Section = Sections[RE.SectionID];
150 uint8_t *LocalAddress = Section.getAddress() + RE.Offset;
151 uint64_t FinalAddress = Section.getLoadAddress() + RE.Offset;
153 dbgs() << "resolveRelocation Section: " << RE.SectionID
154 << " LocalAddress: " << format("%p", LocalAddress)
155 << " FinalAddress: " << format("0x%016" PRIx64, FinalAddress)
156 << " Value: " << format("0x%016" PRIx64, Value) << " Addend: " << RE.Addend
157 << " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
158 << " Size: " << (1 << RE.Size) << "\n";
162 RuntimeDyldMachO::getSectionByAddress(const MachOObjectFile &Obj,
164 section_iterator SI = Obj.section_begin();
165 section_iterator SE = Obj.section_end();
167 for (; SI != SE; ++SI) {
168 uint64_t SAddr = SI->getAddress();
169 uint64_t SSize = SI->getSize();
170 if ((Addr >= SAddr) && (Addr < SAddr + SSize))
178 // Populate __pointers section.
179 Error RuntimeDyldMachO::populateIndirectSymbolPointersSection(
180 const MachOObjectFile &Obj,
181 const SectionRef &PTSection,
182 unsigned PTSectionID) {
183 assert(!Obj.is64Bit() &&
184 "Pointer table section not supported in 64-bit MachO.");
186 MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
187 MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
188 uint32_t PTSectionSize = Sec32.size;
189 unsigned FirstIndirectSymbol = Sec32.reserved1;
190 const unsigned PTEntrySize = 4;
191 unsigned NumPTEntries = PTSectionSize / PTEntrySize;
192 unsigned PTEntryOffset = 0;
194 assert((PTSectionSize % PTEntrySize) == 0 &&
195 "Pointers section does not contain a whole number of stubs?");
197 DEBUG(dbgs() << "Populating pointer table section "
198 << Sections[PTSectionID].getName() << ", Section ID "
199 << PTSectionID << ", " << NumPTEntries << " entries, "
200 << PTEntrySize << " bytes each:\n");
202 for (unsigned i = 0; i < NumPTEntries; ++i) {
203 unsigned SymbolIndex =
204 Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
205 symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
206 StringRef IndirectSymbolName;
207 if (auto IndirectSymbolNameOrErr = SI->getName())
208 IndirectSymbolName = *IndirectSymbolNameOrErr;
210 return IndirectSymbolNameOrErr.takeError();
211 DEBUG(dbgs() << " " << IndirectSymbolName << ": index " << SymbolIndex
212 << ", PT offset: " << PTEntryOffset << "\n");
213 RelocationEntry RE(PTSectionID, PTEntryOffset,
214 MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
215 addRelocationForSymbol(RE, IndirectSymbolName);
216 PTEntryOffset += PTEntrySize;
218 return Error::success();
221 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
222 return Obj.isMachO();
225 template <typename Impl>
227 RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &Obj,
228 ObjSectionToIDMap &SectionMap) {
229 unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
230 unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
231 unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
233 for (const auto &Section : Obj.sections()) {
235 Section.getName(Name);
237 // Force emission of the __text, __eh_frame, and __gcc_except_tab sections
238 // if they're present. Otherwise call down to the impl to handle other
239 // sections that have already been emitted.
240 if (Name == "__text") {
241 if (auto TextSIDOrErr = findOrEmitSection(Obj, Section, true, SectionMap))
242 TextSID = *TextSIDOrErr;
244 return TextSIDOrErr.takeError();
245 } else if (Name == "__eh_frame") {
246 if (auto EHFrameSIDOrErr = findOrEmitSection(Obj, Section, false,
248 EHFrameSID = *EHFrameSIDOrErr;
250 return EHFrameSIDOrErr.takeError();
251 } else if (Name == "__gcc_except_tab") {
252 if (auto ExceptTabSIDOrErr = findOrEmitSection(Obj, Section, true,
254 ExceptTabSID = *ExceptTabSIDOrErr;
256 return ExceptTabSIDOrErr.takeError();
258 auto I = SectionMap.find(Section);
259 if (I != SectionMap.end())
260 if (auto Err = impl().finalizeSection(Obj, I->second, Section))
264 UnregisteredEHFrameSections.push_back(
265 EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
267 return Error::success();
270 template <typename Impl>
271 unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(uint8_t *P,
272 int64_t DeltaForText,
273 int64_t DeltaForEH) {
274 typedef typename Impl::TargetPtrT TargetPtrT;
276 DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
277 << ", Delta for EH: " << DeltaForEH << "\n");
278 uint32_t Length = readBytesUnaligned(P, 4);
280 uint8_t *Ret = P + Length;
281 uint32_t Offset = readBytesUnaligned(P, 4);
282 if (Offset == 0) // is a CIE
286 TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
287 TargetPtrT NewLocation = FDELocation - DeltaForText;
288 writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
290 P += sizeof(TargetPtrT);
292 // Skip the FDE address range
293 P += sizeof(TargetPtrT);
295 uint8_t Augmentationsize = *P;
297 if (Augmentationsize != 0) {
298 TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
299 TargetPtrT NewLSDA = LSDA - DeltaForEH;
300 writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
306 static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
307 int64_t ObjDistance = static_cast<int64_t>(A->getObjAddress()) -
308 static_cast<int64_t>(B->getObjAddress());
309 int64_t MemDistance = A->getLoadAddress() - B->getLoadAddress();
310 return ObjDistance - MemDistance;
313 template <typename Impl>
314 void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
316 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
317 EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
318 if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
319 SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
321 SectionEntry *Text = &Sections[SectionInfo.TextSID];
322 SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
323 SectionEntry *ExceptTab = nullptr;
324 if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
325 ExceptTab = &Sections[SectionInfo.ExceptTabSID];
327 int64_t DeltaForText = computeDelta(Text, EHFrame);
328 int64_t DeltaForEH = 0;
330 DeltaForEH = computeDelta(ExceptTab, EHFrame);
332 uint8_t *P = EHFrame->getAddress();
333 uint8_t *End = P + EHFrame->getSize();
335 P = processFDE(P, DeltaForText, DeltaForEH);
338 MemMgr.registerEHFrames(EHFrame->getAddress(), EHFrame->getLoadAddress(),
341 UnregisteredEHFrameSections.clear();
344 std::unique_ptr<RuntimeDyldMachO>
345 RuntimeDyldMachO::create(Triple::ArchType Arch,
346 RuntimeDyld::MemoryManager &MemMgr,
347 JITSymbolResolver &Resolver) {
350 llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
353 return make_unique<RuntimeDyldMachOARM>(MemMgr, Resolver);
354 case Triple::aarch64:
355 return make_unique<RuntimeDyldMachOAArch64>(MemMgr, Resolver);
357 return make_unique<RuntimeDyldMachOI386>(MemMgr, Resolver);
359 return make_unique<RuntimeDyldMachOX86_64>(MemMgr, Resolver);
363 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
364 RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
365 if (auto ObjSectionToIDOrErr = loadObjectImpl(O))
366 return llvm::make_unique<LoadedMachOObjectInfo>(*this,
367 *ObjSectionToIDOrErr);
370 raw_string_ostream ErrStream(ErrorStr);
371 logAllUnhandledErrors(ObjSectionToIDOrErr.takeError(), ErrStream, "");
376 } // end namespace llvm