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
30 : public RuntimeDyld::LoadedObjectInfoHelper<LoadedMachOObjectInfo> {
32 LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
34 : LoadedObjectInfoHelper(RTDyld, BeginIdx, EndIdx) {}
36 OwningBinary<ObjectFile>
37 getObjectForDebug(const ObjectFile &Obj) const override {
38 return OwningBinary<ObjectFile>();
46 int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
47 unsigned NumBytes = 1 << RE.Size;
48 uint8_t *Src = Sections[RE.SectionID].Address + RE.Offset;
50 return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
53 RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
54 const ObjectFile &BaseTObj, const relocation_iterator &RI,
55 const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID) {
57 const MachOObjectFile &Obj =
58 static_cast<const MachOObjectFile &>(BaseTObj);
59 MachO::any_relocation_info RelInfo =
60 Obj.getRelocation(RI->getRawDataRefImpl());
61 RelocationValueRef Value;
63 bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
65 symbol_iterator Symbol = RI->getSymbol();
66 ErrorOr<StringRef> TargetNameOrErr = Symbol->getName();
67 if (std::error_code EC = TargetNameOrErr.getError())
68 report_fatal_error(EC.message());
69 StringRef TargetName = *TargetNameOrErr;
70 RTDyldSymbolTable::const_iterator SI =
71 GlobalSymbolTable.find(TargetName.data());
72 if (SI != GlobalSymbolTable.end()) {
73 const auto &SymInfo = SI->second;
74 Value.SectionID = SymInfo.getSectionID();
75 Value.Offset = SymInfo.getOffset() + RE.Addend;
77 Value.SymbolName = TargetName.data();
78 Value.Offset = RE.Addend;
81 SectionRef Sec = Obj.getAnyRelocationSection(RelInfo);
82 bool IsCode = Sec.isText();
83 Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
84 uint64_t Addr = Sec.getAddress();
85 Value.Offset = RE.Addend - Addr;
91 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
92 const ObjectFile &BaseTObj,
93 const relocation_iterator &RI,
94 unsigned OffsetToNextPC) {
95 const MachOObjectFile &Obj =
96 static_cast<const MachOObjectFile &>(BaseTObj);
97 MachO::any_relocation_info RelInfo =
98 Obj.getRelocation(RI->getRawDataRefImpl());
100 bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
102 ErrorOr<uint64_t> RelocAddr = RI->getAddress();
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 ErrorOr<StringRef> IndirectSymbolNameOrErr = SI->getName();
168 if (std::error_code EC = IndirectSymbolNameOrErr.getError())
169 report_fatal_error(EC.message());
170 StringRef IndirectSymbolName = *IndirectSymbolNameOrErr;
171 DEBUG(dbgs() << " " << IndirectSymbolName << ": index " << SymbolIndex
172 << ", PT offset: " << PTEntryOffset << "\n");
173 RelocationEntry RE(PTSectionID, PTEntryOffset,
174 MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
175 addRelocationForSymbol(RE, IndirectSymbolName);
176 PTEntryOffset += PTEntrySize;
180 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
181 return Obj.isMachO();
184 template <typename Impl>
185 void RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &Obj,
186 ObjSectionToIDMap &SectionMap) {
187 unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
188 unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
189 unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
191 for (const auto &Section : Obj.sections()) {
193 Section.getName(Name);
195 // Force emission of the __text, __eh_frame, and __gcc_except_tab sections
196 // if they're present. Otherwise call down to the impl to handle other
197 // sections that have already been emitted.
198 if (Name == "__text")
199 TextSID = findOrEmitSection(Obj, Section, true, SectionMap);
200 else if (Name == "__eh_frame")
201 EHFrameSID = findOrEmitSection(Obj, Section, false, SectionMap);
202 else if (Name == "__gcc_except_tab")
203 ExceptTabSID = findOrEmitSection(Obj, Section, true, SectionMap);
205 auto I = SectionMap.find(Section);
206 if (I != SectionMap.end())
207 impl().finalizeSection(Obj, I->second, Section);
210 UnregisteredEHFrameSections.push_back(
211 EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
214 template <typename Impl>
215 unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(unsigned char *P,
216 int64_t DeltaForText,
217 int64_t DeltaForEH) {
218 typedef typename Impl::TargetPtrT TargetPtrT;
220 DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
221 << ", Delta for EH: " << DeltaForEH << "\n");
222 uint32_t Length = readBytesUnaligned(P, 4);
224 unsigned char *Ret = P + Length;
225 uint32_t Offset = readBytesUnaligned(P, 4);
226 if (Offset == 0) // is a CIE
230 TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
231 TargetPtrT NewLocation = FDELocation - DeltaForText;
232 writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
234 P += sizeof(TargetPtrT);
236 // Skip the FDE address range
237 P += sizeof(TargetPtrT);
239 uint8_t Augmentationsize = *P;
241 if (Augmentationsize != 0) {
242 TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
243 TargetPtrT NewLSDA = LSDA - DeltaForEH;
244 writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
250 static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
251 int64_t ObjDistance =
252 static_cast<int64_t>(A->ObjAddress) - static_cast<int64_t>(B->ObjAddress);
253 int64_t MemDistance = A->LoadAddress - B->LoadAddress;
254 return ObjDistance - MemDistance;
257 template <typename Impl>
258 void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
260 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
261 EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
262 if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
263 SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
265 SectionEntry *Text = &Sections[SectionInfo.TextSID];
266 SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
267 SectionEntry *ExceptTab = nullptr;
268 if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
269 ExceptTab = &Sections[SectionInfo.ExceptTabSID];
271 int64_t DeltaForText = computeDelta(Text, EHFrame);
272 int64_t DeltaForEH = 0;
274 DeltaForEH = computeDelta(ExceptTab, EHFrame);
276 unsigned char *P = EHFrame->Address;
277 unsigned char *End = P + EHFrame->Size;
279 P = processFDE(P, DeltaForText, DeltaForEH);
282 MemMgr.registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
285 UnregisteredEHFrameSections.clear();
288 std::unique_ptr<RuntimeDyldMachO>
289 RuntimeDyldMachO::create(Triple::ArchType Arch,
290 RuntimeDyld::MemoryManager &MemMgr,
291 RuntimeDyld::SymbolResolver &Resolver) {
294 llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
297 return make_unique<RuntimeDyldMachOARM>(MemMgr, Resolver);
298 case Triple::aarch64:
299 return make_unique<RuntimeDyldMachOAArch64>(MemMgr, Resolver);
301 return make_unique<RuntimeDyldMachOI386>(MemMgr, Resolver);
303 return make_unique<RuntimeDyldMachOX86_64>(MemMgr, Resolver);
307 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
308 RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
309 unsigned SectionStartIdx, SectionEndIdx;
310 std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
311 return llvm::make_unique<LoadedMachOObjectInfo>(*this, SectionStartIdx,
315 } // end namespace llvm