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();
67 Symbol->getName(TargetName);
68 RTDyldSymbolTable::const_iterator SI =
69 GlobalSymbolTable.find(TargetName.data());
70 if (SI != GlobalSymbolTable.end()) {
71 const auto &SymInfo = SI->second;
72 Value.SectionID = SymInfo.getSectionID();
73 Value.Offset = SymInfo.getOffset() + RE.Addend;
75 Value.SymbolName = TargetName.data();
76 Value.Offset = RE.Addend;
79 SectionRef Sec = Obj.getAnyRelocationSection(RelInfo);
80 bool IsCode = Sec.isText();
81 Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
82 uint64_t Addr = Sec.getAddress();
83 Value.Offset = RE.Addend - Addr;
89 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
90 const ObjectFile &BaseTObj,
91 const relocation_iterator &RI,
92 unsigned OffsetToNextPC) {
93 const MachOObjectFile &Obj =
94 static_cast<const MachOObjectFile &>(BaseTObj);
95 MachO::any_relocation_info RelInfo =
96 Obj.getRelocation(RI->getRawDataRefImpl());
98 bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
100 uint64_t RelocAddr = 0;
101 RI->getAddress(RelocAddr);
102 Value.Offset += RelocAddr + OffsetToNextPC;
106 void RuntimeDyldMachO::dumpRelocationToResolve(const RelocationEntry &RE,
107 uint64_t Value) const {
108 const SectionEntry &Section = Sections[RE.SectionID];
109 uint8_t *LocalAddress = Section.Address + RE.Offset;
110 uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
112 dbgs() << "resolveRelocation Section: " << RE.SectionID
113 << " LocalAddress: " << format("%p", LocalAddress)
114 << " FinalAddress: " << format("0x%016" PRIx64, FinalAddress)
115 << " Value: " << format("0x%016" PRIx64, Value) << " Addend: " << RE.Addend
116 << " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
117 << " Size: " << (1 << RE.Size) << "\n";
121 RuntimeDyldMachO::getSectionByAddress(const MachOObjectFile &Obj,
123 section_iterator SI = Obj.section_begin();
124 section_iterator SE = Obj.section_end();
126 for (; SI != SE; ++SI) {
127 uint64_t SAddr = SI->getAddress();
128 uint64_t SSize = SI->getSize();
129 if ((Addr >= SAddr) && (Addr < SAddr + SSize))
137 // Populate __pointers section.
138 void RuntimeDyldMachO::populateIndirectSymbolPointersSection(
139 const MachOObjectFile &Obj,
140 const SectionRef &PTSection,
141 unsigned PTSectionID) {
142 assert(!Obj.is64Bit() &&
143 "Pointer table section not supported in 64-bit MachO.");
145 MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
146 MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
147 uint32_t PTSectionSize = Sec32.size;
148 unsigned FirstIndirectSymbol = Sec32.reserved1;
149 const unsigned PTEntrySize = 4;
150 unsigned NumPTEntries = PTSectionSize / PTEntrySize;
151 unsigned PTEntryOffset = 0;
153 assert((PTSectionSize % PTEntrySize) == 0 &&
154 "Pointers section does not contain a whole number of stubs?");
156 DEBUG(dbgs() << "Populating pointer table section "
157 << Sections[PTSectionID].Name
158 << ", Section ID " << PTSectionID << ", "
159 << NumPTEntries << " entries, " << PTEntrySize
160 << " bytes each:\n");
162 for (unsigned i = 0; i < NumPTEntries; ++i) {
163 unsigned SymbolIndex =
164 Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
165 symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
166 StringRef IndirectSymbolName;
167 SI->getName(IndirectSymbolName);
168 DEBUG(dbgs() << " " << IndirectSymbolName << ": index " << SymbolIndex
169 << ", PT offset: " << PTEntryOffset << "\n");
170 RelocationEntry RE(PTSectionID, PTEntryOffset,
171 MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
172 addRelocationForSymbol(RE, IndirectSymbolName);
173 PTEntryOffset += PTEntrySize;
177 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
178 return Obj.isMachO();
181 template <typename Impl>
182 void RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &Obj,
183 ObjSectionToIDMap &SectionMap) {
184 unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
185 unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
186 unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
188 for (const auto &Section : Obj.sections()) {
190 Section.getName(Name);
192 // Force emission of the __text, __eh_frame, and __gcc_except_tab sections
193 // if they're present. Otherwise call down to the impl to handle other
194 // sections that have already been emitted.
195 if (Name == "__text")
196 TextSID = findOrEmitSection(Obj, Section, true, SectionMap);
197 else if (Name == "__eh_frame")
198 EHFrameSID = findOrEmitSection(Obj, Section, false, SectionMap);
199 else if (Name == "__gcc_except_tab")
200 ExceptTabSID = findOrEmitSection(Obj, Section, true, SectionMap);
202 auto I = SectionMap.find(Section);
203 if (I != SectionMap.end())
204 impl().finalizeSection(Obj, I->second, Section);
207 UnregisteredEHFrameSections.push_back(
208 EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
211 template <typename Impl>
212 unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(unsigned char *P,
213 int64_t DeltaForText,
214 int64_t DeltaForEH) {
215 typedef typename Impl::TargetPtrT TargetPtrT;
217 DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
218 << ", Delta for EH: " << DeltaForEH << "\n");
219 uint32_t Length = readBytesUnaligned(P, 4);
221 unsigned char *Ret = P + Length;
222 uint32_t Offset = readBytesUnaligned(P, 4);
223 if (Offset == 0) // is a CIE
227 TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
228 TargetPtrT NewLocation = FDELocation - DeltaForText;
229 writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
231 P += sizeof(TargetPtrT);
233 // Skip the FDE address range
234 P += sizeof(TargetPtrT);
236 uint8_t Augmentationsize = *P;
238 if (Augmentationsize != 0) {
239 TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
240 TargetPtrT NewLSDA = LSDA - DeltaForEH;
241 writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
247 static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
248 int64_t ObjDistance =
249 static_cast<int64_t>(A->ObjAddress) - static_cast<int64_t>(B->ObjAddress);
250 int64_t MemDistance = A->LoadAddress - B->LoadAddress;
251 return ObjDistance - MemDistance;
254 template <typename Impl>
255 void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
257 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
258 EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
259 if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
260 SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
262 SectionEntry *Text = &Sections[SectionInfo.TextSID];
263 SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
264 SectionEntry *ExceptTab = nullptr;
265 if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
266 ExceptTab = &Sections[SectionInfo.ExceptTabSID];
268 int64_t DeltaForText = computeDelta(Text, EHFrame);
269 int64_t DeltaForEH = 0;
271 DeltaForEH = computeDelta(ExceptTab, EHFrame);
273 unsigned char *P = EHFrame->Address;
274 unsigned char *End = P + EHFrame->Size;
276 P = processFDE(P, DeltaForText, DeltaForEH);
279 MemMgr.registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
282 UnregisteredEHFrameSections.clear();
285 std::unique_ptr<RuntimeDyldMachO>
286 RuntimeDyldMachO::create(Triple::ArchType Arch,
287 RuntimeDyld::MemoryManager &MemMgr,
288 RuntimeDyld::SymbolResolver &Resolver) {
291 llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
294 return make_unique<RuntimeDyldMachOARM>(MemMgr, Resolver);
295 case Triple::aarch64:
296 return make_unique<RuntimeDyldMachOAArch64>(MemMgr, Resolver);
298 return make_unique<RuntimeDyldMachOI386>(MemMgr, Resolver);
300 return make_unique<RuntimeDyldMachOX86_64>(MemMgr, Resolver);
304 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
305 RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
306 unsigned SectionStartIdx, SectionEndIdx;
307 std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
308 return llvm::make_unique<LoadedMachOObjectInfo>(*this, SectionStartIdx,
312 } // end namespace llvm