blob: 07de4ba8cd5f740a75ffeee5c51e775f33800ca7 [file] [log] [blame]
Jim Grosbache0934be2012-01-16 23:50:58 +00001//===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
Jim Grosbach6e563312011-03-21 22:15:52 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implementation of the MC-JIT runtime dynamic linker.
11//
12//===----------------------------------------------------------------------===//
13
Jim Grosbach8b54dca2011-03-23 19:52:00 +000014#define DEBUG_TYPE "dyld"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000015#include "llvm/ExecutionEngine/RuntimeDyld.h"
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000016#include "ObjectImageCommon.h"
Eli Bendersky76463fd2012-01-22 07:05:02 +000017#include "RuntimeDyldELF.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "RuntimeDyldImpl.h"
Eli Bendersky76463fd2012-01-22 07:05:02 +000019#include "RuntimeDyldMachO.h"
Rafael Espindola3ecfcc22013-06-11 18:01:14 +000020#include "llvm/Support/FileSystem.h"
Tim Northoverf00677d2012-10-29 10:47:04 +000021#include "llvm/Support/MathExtras.h"
Rafael Espindola7486d922013-05-30 03:05:14 +000022#include "llvm/Object/ELF.h"
Eli Bendersky76463fd2012-01-22 07:05:02 +000023
Jim Grosbach6e563312011-03-21 22:15:52 +000024using namespace llvm;
25using namespace llvm::object;
26
Chandler Carruth53c5e7b2011-04-05 23:54:31 +000027// Empty out-of-line virtual destructor as the key function.
Danil Malyshevcf852dc2011-07-13 07:57:58 +000028RuntimeDyldImpl::~RuntimeDyldImpl() {}
Chandler Carruth53c5e7b2011-04-05 23:54:31 +000029
Jim Grosbach6e563312011-03-21 22:15:52 +000030namespace llvm {
Jim Grosbach6e563312011-03-21 22:15:52 +000031
Andrew Kaylor528f6d72013-10-11 21:25:48 +000032void RuntimeDyldImpl::registerEHFrames() {
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +000033}
34
Andrew Kaylor43507d02013-10-16 00:14:21 +000035void RuntimeDyldImpl::deregisterEHFrames() {
36}
37
Jim Grosbachf8c1c842011-04-12 21:20:41 +000038// Resolve the relocations for all symbols we currently know about.
39void RuntimeDyldImpl::resolveRelocations() {
Preston Gurdc68dda82012-04-12 20:13:57 +000040 // First, resolve relocations associated with external symbols.
Eli Bendersky37bc5a22012-04-30 12:15:58 +000041 resolveExternalSymbols();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000042
Jim Grosbach61425c02012-01-16 22:26:39 +000043 // Just iterate over the sections we have and resolve all the relocations
44 // in them. Gross overkill, but it gets the job done.
45 for (int i = 0, e = Sections.size(); i != e; ++i) {
Andrew Kaylor32bd10b2013-08-19 19:38:06 +000046 // The Section here (Sections[i]) refers to the section in which the
47 // symbol for the relocation is located. The SectionID in the relocation
48 // entry provides the section to which the relocation will be applied.
Andrew Kaylor28989882012-11-05 20:57:16 +000049 uint64_t Addr = Sections[i].LoadAddress;
50 DEBUG(dbgs() << "Resolving relocations Section #" << i
51 << "\t" << format("%p", (uint8_t *)Addr)
52 << "\n");
53 resolveRelocationList(Relocations[i], Addr);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000054 Relocations.erase(i);
Jim Grosbach61425c02012-01-16 22:26:39 +000055 }
Jim Grosbachf8c1c842011-04-12 21:20:41 +000056}
57
Jim Grosbache940c1b2012-09-13 21:50:06 +000058void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
Jim Grosbach020f4e82012-01-16 23:50:55 +000059 uint64_t TargetAddress) {
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000060 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
61 if (Sections[i].Address == LocalAddress) {
62 reassignSectionAddress(i, TargetAddress);
63 return;
64 }
65 }
66 llvm_unreachable("Attempting to remap address of unknown section!");
Jim Grosbach020f4e82012-01-16 23:50:55 +000067}
68
Eli Bendersky5fe01982012-04-29 12:40:47 +000069// Subclasses can implement this method to create specialized image instances.
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +000070// The caller owns the pointer that is returned.
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000071ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
72 return new ObjectImageCommon(InputBuffer);
Preston Gurd689ff9c2012-04-16 22:12:58 +000073}
74
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000075ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
Preston Gurd689ff9c2012-04-16 22:12:58 +000076 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
Preston Gurdc68dda82012-04-12 20:13:57 +000077 if (!obj)
78 report_fatal_error("Unable to create object image from memory buffer!");
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000079
Andrew Kaylorab950f52013-10-15 20:44:55 +000080 // Save information about our target
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000081 Arch = (Triple::ArchType)obj->getArch();
Andrew Kaylorab950f52013-10-15 20:44:55 +000082 IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000083
Eli Benderskyd98c9e92012-05-01 06:58:59 +000084 // Symbols found in this object
85 StringMap<SymbolLoc> LocalSymbols;
86 // Used sections from the object file
87 ObjSectionToIDMap LocalSections;
88
Tim Northoverf00677d2012-10-29 10:47:04 +000089 // Common symbols requiring allocation, with their sizes and alignments
Eli Benderskyd98c9e92012-05-01 06:58:59 +000090 CommonSymbolMap CommonSymbols;
Tim Northoverf00677d2012-10-29 10:47:04 +000091 // Maximum required total memory to allocate all common symbols
Eli Benderskyd98c9e92012-05-01 06:58:59 +000092 uint64_t CommonSize = 0;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000093
94 error_code err;
95 // Parse symbols
96 DEBUG(dbgs() << "Parse symbols:\n");
97 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
98 i != e; i.increment(err)) {
99 Check(err);
100 object::SymbolRef::Type SymType;
101 StringRef Name;
102 Check(i->getType(SymType));
103 Check(i->getName(Name));
104
Preston Gurdc68dda82012-04-12 20:13:57 +0000105 uint32_t flags;
106 Check(i->getFlags(flags));
107
108 bool isCommon = flags & SymbolRef::SF_Common;
109 if (isCommon) {
110 // Add the common symbols to a list. We'll allocate them all below.
Rafael Espindola59a0e792013-04-29 22:24:22 +0000111 uint32_t Align;
112 Check(i->getAlignment(Align));
Preston Gurdc68dda82012-04-12 20:13:57 +0000113 uint64_t Size = 0;
114 Check(i->getSize(Size));
Tim Northoverf00677d2012-10-29 10:47:04 +0000115 CommonSize += Size + Align;
116 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
Preston Gurdc68dda82012-04-12 20:13:57 +0000117 } else {
118 if (SymType == object::SymbolRef::ST_Function ||
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000119 SymType == object::SymbolRef::ST_Data ||
120 SymType == object::SymbolRef::ST_Unknown) {
Preston Gurdc68dda82012-04-12 20:13:57 +0000121 uint64_t FileOffset;
Eli Bendersky5fe01982012-04-29 12:40:47 +0000122 StringRef SectionData;
Tim Northover78822132012-12-17 17:59:35 +0000123 bool IsCode;
Preston Gurdc68dda82012-04-12 20:13:57 +0000124 section_iterator si = obj->end_sections();
125 Check(i->getFileOffset(FileOffset));
126 Check(i->getSection(si));
127 if (si == obj->end_sections()) continue;
Eli Bendersky5fe01982012-04-29 12:40:47 +0000128 Check(si->getContents(SectionData));
Tim Northover78822132012-12-17 17:59:35 +0000129 Check(si->isText(IsCode));
Preston Gurdc68dda82012-04-12 20:13:57 +0000130 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
131 (uintptr_t)FileOffset;
Eli Bendersky5fe01982012-04-29 12:40:47 +0000132 uintptr_t SectOffset = (uintptr_t)(SymPtr -
133 (const uint8_t*)SectionData.begin());
Tim Northover78822132012-12-17 17:59:35 +0000134 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
Preston Gurdc68dda82012-04-12 20:13:57 +0000135 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
136 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
137 << " flags: " << flags
138 << " SID: " << SectionID
139 << " Offset: " << format("%p", SectOffset));
Amara Emerson098d6d52012-11-16 11:11:59 +0000140 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
Preston Gurdc68dda82012-04-12 20:13:57 +0000141 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000142 }
143 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
144 }
145
Preston Gurdc68dda82012-04-12 20:13:57 +0000146 // Allocate common symbols
147 if (CommonSize != 0)
Preston Gurd689ff9c2012-04-16 22:12:58 +0000148 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
Preston Gurdc68dda82012-04-12 20:13:57 +0000149
Eli Bendersky5fe01982012-04-29 12:40:47 +0000150 // Parse and process relocations
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000151 DEBUG(dbgs() << "Parse relocations:\n");
152 for (section_iterator si = obj->begin_sections(),
153 se = obj->end_sections(); si != se; si.increment(err)) {
154 Check(err);
155 bool isFirstRelocation = true;
156 unsigned SectionID = 0;
157 StubMap Stubs;
Rafael Espindola7486d922013-05-30 03:05:14 +0000158 section_iterator RelocatedSection = si->getRelocatedSection();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000159
160 for (relocation_iterator i = si->begin_relocations(),
161 e = si->end_relocations(); i != e; i.increment(err)) {
162 Check(err);
163
Eli Bendersky5fe01982012-04-29 12:40:47 +0000164 // If it's the first relocation in this section, find its SectionID
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000165 if (isFirstRelocation) {
Rafael Espindola7486d922013-05-30 03:05:14 +0000166 SectionID =
167 findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000168 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
169 isFirstRelocation = false;
170 }
171
Rafael Espindolaca0e7362013-04-29 19:03:21 +0000172 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
Rafael Espindolaefa91f62013-04-29 14:44:23 +0000173 Stubs);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000174 }
175 }
Preston Gurd689ff9c2012-04-16 22:12:58 +0000176
Andrew Kaylorff9fa052013-08-19 23:27:43 +0000177 // Give the subclasses a chance to tie-up any loose ends.
Andrew Kaylor528f6d72013-10-11 21:25:48 +0000178 finalizeLoad(LocalSections);
Andrew Kaylorff9fa052013-08-19 23:27:43 +0000179
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000180 return obj.take();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000181}
182
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000183void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
184 const CommonSymbolMap &CommonSymbols,
185 uint64_t TotalSize,
186 SymbolTableMap &SymbolTable) {
Preston Gurdc68dda82012-04-12 20:13:57 +0000187 // Allocate memory for the section
188 unsigned SectionID = Sections.size();
Filip Pizlo6eb43d22013-10-02 00:59:25 +0000189 uint8_t *Addr = MemMgr->allocateDataSection(
190 TotalSize, sizeof(void*), SectionID, StringRef(), false);
Preston Gurdc68dda82012-04-12 20:13:57 +0000191 if (!Addr)
192 report_fatal_error("Unable to allocate memory for common symbols!");
193 uint64_t Offset = 0;
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +0000194 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
Preston Gurdc68dda82012-04-12 20:13:57 +0000195 memset(Addr, 0, TotalSize);
196
197 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
198 << " new addr: " << format("%p", Addr)
199 << " DataSize: " << TotalSize
200 << "\n");
201
202 // Assign the address of each symbol
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000203 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
204 itEnd = CommonSymbols.end(); it != itEnd; it++) {
Tim Northoverf00677d2012-10-29 10:47:04 +0000205 uint64_t Size = it->second.first;
206 uint64_t Align = it->second.second;
Preston Gurdc68dda82012-04-12 20:13:57 +0000207 StringRef Name;
208 it->first.getName(Name);
Tim Northoverf00677d2012-10-29 10:47:04 +0000209 if (Align) {
210 // This symbol has an alignment requirement.
211 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
212 Addr += AlignOffset;
213 Offset += AlignOffset;
214 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
Andrew Kaylor5fc8c7c2012-11-01 19:49:21 +0000215 format("%p\n", Addr));
Tim Northoverf00677d2012-10-29 10:47:04 +0000216 }
Preston Gurd689ff9c2012-04-16 22:12:58 +0000217 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000218 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
Preston Gurdc68dda82012-04-12 20:13:57 +0000219 Offset += Size;
220 Addr += Size;
221 }
Preston Gurdc68dda82012-04-12 20:13:57 +0000222}
223
Preston Gurd689ff9c2012-04-16 22:12:58 +0000224unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
225 const SectionRef &Section,
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000226 bool IsCode) {
227
228 unsigned StubBufSize = 0,
229 StubSize = getMaxStubSize();
230 error_code err;
Rafael Espindola7486d922013-05-30 03:05:14 +0000231 const ObjectFile *ObjFile = Obj.getObjectFile();
232 // FIXME: this is an inefficient way to handle this. We should computed the
233 // necessary section allocation size in loadObject by walking all the sections
234 // once.
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000235 if (StubSize > 0) {
Rafael Espindola7486d922013-05-30 03:05:14 +0000236 for (section_iterator SI = ObjFile->begin_sections(),
237 SE = ObjFile->end_sections();
238 SI != SE; SI.increment(err), Check(err)) {
239 section_iterator RelSecI = SI->getRelocatedSection();
240 if (!(RelSecI == Section))
241 continue;
242
243 for (relocation_iterator I = SI->begin_relocations(),
244 E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
245 StubBufSize += StubSize;
246 }
247 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000248 }
Rafael Espindola7486d922013-05-30 03:05:14 +0000249
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000250 StringRef data;
251 uint64_t Alignment64;
252 Check(Section.getContents(data));
253 Check(Section.getAlignment(Alignment64));
254
255 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
Preston Gurdc68dda82012-04-12 20:13:57 +0000256 bool IsRequired;
257 bool IsVirtual;
258 bool IsZeroInit;
Andrew Kaylor53608a32012-11-15 23:50:01 +0000259 bool IsReadOnly;
Preston Gurdc68dda82012-04-12 20:13:57 +0000260 uint64_t DataSize;
Andrew Kaylor28a76552013-10-16 00:32:24 +0000261 unsigned PaddingSize = 0;
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000262 StringRef Name;
Preston Gurdc68dda82012-04-12 20:13:57 +0000263 Check(Section.isRequiredForExecution(IsRequired));
264 Check(Section.isVirtual(IsVirtual));
265 Check(Section.isZeroInit(IsZeroInit));
Andrew Kaylor53608a32012-11-15 23:50:01 +0000266 Check(Section.isReadOnlyData(IsReadOnly));
Preston Gurdc68dda82012-04-12 20:13:57 +0000267 Check(Section.getSize(DataSize));
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000268 Check(Section.getName(Name));
Richard Sandiford6fc2ad62013-05-03 14:15:35 +0000269 if (StubSize > 0) {
270 unsigned StubAlignment = getStubAlignment();
271 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
272 if (StubAlignment > EndAlignment)
273 StubBufSize += StubAlignment - EndAlignment;
274 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000275
Andrew Kaylor28a76552013-10-16 00:32:24 +0000276 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
277 // with zeroes added at the end. For MachO objects, this section has a
278 // slightly different name, so this won't have any effect for MachO objects.
279 if (Name == ".eh_frame")
280 PaddingSize = 4;
281
Preston Gurdc68dda82012-04-12 20:13:57 +0000282 unsigned Allocate;
283 unsigned SectionID = Sections.size();
284 uint8_t *Addr;
285 const char *pData = 0;
286
287 // Some sections, such as debug info, don't need to be loaded for execution.
288 // Leave those where they are.
289 if (IsRequired) {
Andrew Kaylor28a76552013-10-16 00:32:24 +0000290 Allocate = DataSize + PaddingSize + StubBufSize;
Preston Gurdc68dda82012-04-12 20:13:57 +0000291 Addr = IsCode
Filip Pizlo6eb43d22013-10-02 00:59:25 +0000292 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
293 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
294 IsReadOnly);
Preston Gurdc68dda82012-04-12 20:13:57 +0000295 if (!Addr)
296 report_fatal_error("Unable to allocate section memory!");
297
298 // Virtual sections have no data in the object image, so leave pData = 0
299 if (!IsVirtual)
300 pData = data.data();
301
302 // Zero-initialize or copy the data from the image
303 if (IsZeroInit || IsVirtual)
304 memset(Addr, 0, DataSize);
305 else
306 memcpy(Addr, pData, DataSize);
307
Andrew Kaylor28a76552013-10-16 00:32:24 +0000308 // Fill in any extra bytes we allocated for padding
309 if (PaddingSize != 0) {
310 memset(Addr + DataSize, 0, PaddingSize);
311 // Update the DataSize variable so that the stub offset is set correctly.
312 DataSize += PaddingSize;
313 }
314
Preston Gurdc68dda82012-04-12 20:13:57 +0000315 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000316 << " Name: " << Name
Preston Gurdc68dda82012-04-12 20:13:57 +0000317 << " obj addr: " << format("%p", pData)
318 << " new addr: " << format("%p", Addr)
319 << " DataSize: " << DataSize
320 << " StubBufSize: " << StubBufSize
321 << " Allocate: " << Allocate
322 << "\n");
Preston Gurd689ff9c2012-04-16 22:12:58 +0000323 Obj.updateSectionAddress(Section, (uint64_t)Addr);
Preston Gurdc68dda82012-04-12 20:13:57 +0000324 }
325 else {
326 // Even if we didn't load the section, we need to record an entry for it
Eli Bendersky5fe01982012-04-29 12:40:47 +0000327 // to handle later processing (and by 'handle' I mean don't do anything
328 // with these sections).
Preston Gurdc68dda82012-04-12 20:13:57 +0000329 Allocate = 0;
330 Addr = 0;
331 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000332 << " Name: " << Name
Preston Gurdc68dda82012-04-12 20:13:57 +0000333 << " obj addr: " << format("%p", data.data())
334 << " new addr: 0"
335 << " DataSize: " << DataSize
336 << " StubBufSize: " << StubBufSize
337 << " Allocate: " << Allocate
338 << "\n");
339 }
340
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +0000341 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000342 return SectionID;
343}
344
Preston Gurd689ff9c2012-04-16 22:12:58 +0000345unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
346 const SectionRef &Section,
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000347 bool IsCode,
348 ObjSectionToIDMap &LocalSections) {
349
350 unsigned SectionID = 0;
351 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
352 if (i != LocalSections.end())
353 SectionID = i->second;
354 else {
Preston Gurd689ff9c2012-04-16 22:12:58 +0000355 SectionID = emitSection(Obj, Section, IsCode);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000356 LocalSections[Section] = SectionID;
357 }
358 return SectionID;
359}
360
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000361void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
362 unsigned SectionID) {
363 Relocations[SectionID].push_back(RE);
364}
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000365
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000366void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
367 StringRef SymbolName) {
368 // Relocation by symbol. If the symbol is found in the global symbol table,
369 // create an appropriate section relocation. Otherwise, add it to
370 // ExternalSymbolRelocations.
371 SymbolTableMap::const_iterator Loc =
372 GlobalSymbolTable.find(SymbolName);
373 if (Loc == GlobalSymbolTable.end()) {
374 ExternalSymbolRelocations[SymbolName].push_back(RE);
Eli Bendersky37bc5a22012-04-30 12:15:58 +0000375 } else {
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000376 // Copy the RE since we want to modify its addend.
377 RelocationEntry RECopy = RE;
378 RECopy.Addend += Loc->second.second;
379 Relocations[Loc->second.first].push_back(RECopy);
Eli Bendersky37bc5a22012-04-30 12:15:58 +0000380 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000381}
382
383uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
Tim Northover4a9b6b72013-05-04 20:14:09 +0000384 if (Arch == Triple::aarch64) {
385 // This stub has to be able to access the full address space,
386 // since symbol lookup won't necessarily find a handy, in-range,
387 // PLT stub for functions which could be anywhere.
388 uint32_t *StubAddr = (uint32_t*)Addr;
389
390 // Stub can use ip0 (== x16) to calculate address
391 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
392 StubAddr++;
393 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
394 StubAddr++;
395 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
396 StubAddr++;
397 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
398 StubAddr++;
399 *StubAddr = 0xd61f0200; // br ip0
400
401 return Addr;
402 } else if (Arch == Triple::arm) {
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000403 // TODO: There is only ARM far stub now. We should add the Thumb stub,
404 // and stubs for branches Thumb - ARM and ARM - Thumb.
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000405 uint32_t *StubAddr = (uint32_t*)Addr;
406 *StubAddr = 0xe51ff004; // ldr pc,<label>
407 return (uint8_t*)++StubAddr;
NAKAMURA Takumi4af1ca52012-12-04 00:08:14 +0000408 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000409 uint32_t *StubAddr = (uint32_t*)Addr;
410 // 0: 3c190000 lui t9,%hi(addr).
411 // 4: 27390000 addiu t9,t9,%lo(addr).
412 // 8: 03200008 jr t9.
413 // c: 00000000 nop.
414 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
415 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
416
417 *StubAddr = LuiT9Instr;
418 StubAddr++;
419 *StubAddr = AdduiT9Instr;
420 StubAddr++;
421 *StubAddr = JrT9Instr;
422 StubAddr++;
423 *StubAddr = NopInstr;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000424 return Addr;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000425 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000426 // PowerPC64 stub: the address points to a function descriptor
427 // instead of the function itself. Load the function address
428 // on r11 and sets it to control register. Also loads the function
429 // TOC in r2 and environment pointer to r11.
430 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
431 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
432 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
433 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
434 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
435 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
436 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
437 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
438 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
439 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
440 writeInt32BE(Addr+40, 0x4E800420); // bctr
Andrew Kaylor5fc8c7c2012-11-01 19:49:21 +0000441
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000442 return Addr;
Richard Sandiford6fc2ad62013-05-03 14:15:35 +0000443 } else if (Arch == Triple::systemz) {
444 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
445 writeInt16BE(Addr+2, 0x0000);
446 writeInt16BE(Addr+4, 0x0004);
447 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
448 // 8-byte address stored at Addr + 8
449 return Addr;
Andrew Kaylorff9fa052013-08-19 23:27:43 +0000450 } else if (Arch == Triple::x86_64) {
451 *Addr = 0xFF; // jmp
452 *(Addr+1) = 0x25; // rip
453 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000454 }
455 return Addr;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000456}
457
458// Assign an address to a symbol name and resolve all the relocations
459// associated with it.
460void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
461 uint64_t Addr) {
462 // The address to use for relocation resolution is not
463 // the address of the local section buffer. We must be doing
Andrew Kaylor28989882012-11-05 20:57:16 +0000464 // a remote execution environment of some sort. Relocations can't
465 // be applied until all the sections have been moved. The client must
466 // trigger this with a call to MCJIT::finalize() or
467 // RuntimeDyld::resolveRelocations().
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000468 //
469 // Addr is a uint64_t because we can't assume the pointer width
470 // of the target is the same as that of the host. Just use a generic
471 // "big enough" type.
472 Sections[SectionID].LoadAddress = Addr;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000473}
474
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000475void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
476 uint64_t Value) {
477 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola87b50172013-04-29 17:24:34 +0000478 const RelocationEntry &RE = Relocs[i];
479 // Ignore relocations for sections that were not loaded
480 if (Sections[RE.SectionID].Address == 0)
481 continue;
482 resolveRelocation(RE, Value);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000483 }
484}
485
Eli Bendersky37bc5a22012-04-30 12:15:58 +0000486void RuntimeDyldImpl::resolveExternalSymbols() {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000487 while(!ExternalSymbolRelocations.empty()) {
488 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
489
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000490 StringRef Name = i->first();
491 RelocationList &Relocs = i->second;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000492 if (Name.size() == 0) {
493 // This is an absolute symbol, use an address of zero.
494 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
495 resolveRelocationList(Relocs, 0);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000496 } else {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000497 uint64_t Addr = 0;
498 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
499 if (Loc == GlobalSymbolTable.end()) {
500 // This is an external symbol, try to get its address from
501 // MemoryManager.
502 Addr = MemMgr->getSymbolAddress(Name.data());
503 } else {
504 // We found the symbol in our global table. It was probably in a
505 // Module that we loaded previously.
Yaron Keren4805bf52013-10-19 09:04:26 +0000506 SymbolLoc SymLoc = Loc->second;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000507 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
508 }
509
510 // FIXME: Implement error handling that doesn't kill the host program!
511 if (!Addr)
512 report_fatal_error("Program used external function '" + Name +
513 "' which could not be resolved!");
514
515 updateGOTEntries(Name, Addr);
516 DEBUG(dbgs() << "Resolving relocations Name: " << Name
517 << "\t" << format("0x%lx", Addr)
518 << "\n");
519 resolveRelocationList(Relocs, Addr);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000520 }
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000521
522 ExternalSymbolRelocations.erase(i->first());
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000523 }
524}
525
526
Jim Grosbach6e563312011-03-21 22:15:52 +0000527//===----------------------------------------------------------------------===//
528// RuntimeDyld class implementation
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000529RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
Andrew Kaylor53608a32012-11-15 23:50:01 +0000530 // FIXME: There's a potential issue lurking here if a single instance of
531 // RuntimeDyld is used to load multiple objects. The current implementation
532 // associates a single memory manager with a RuntimeDyld instance. Even
533 // though the public class spawns a new 'impl' instance for each load,
534 // they share a single memory manager. This can become a problem when page
535 // permissions are applied.
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000536 Dyld = 0;
537 MM = mm;
Jim Grosbach6e563312011-03-21 22:15:52 +0000538}
539
540RuntimeDyld::~RuntimeDyld() {
541 delete Dyld;
542}
543
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000544ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000545 if (!Dyld) {
Rafael Espindola3ecfcc22013-06-11 18:01:14 +0000546 sys::fs::file_magic Type =
547 sys::fs::identify_magic(InputBuffer->getBuffer());
548 switch (Type) {
549 case sys::fs::file_magic::elf_relocatable:
550 case sys::fs::file_magic::elf_executable:
551 case sys::fs::file_magic::elf_shared_object:
552 case sys::fs::file_magic::elf_core:
553 Dyld = new RuntimeDyldELF(MM);
554 break;
555 case sys::fs::file_magic::macho_object:
556 case sys::fs::file_magic::macho_executable:
557 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
558 case sys::fs::file_magic::macho_core:
559 case sys::fs::file_magic::macho_preload_executable:
560 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
561 case sys::fs::file_magic::macho_dynamic_linker:
562 case sys::fs::file_magic::macho_bundle:
563 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
564 case sys::fs::file_magic::macho_dsym_companion:
565 Dyld = new RuntimeDyldMachO(MM);
566 break;
567 case sys::fs::file_magic::unknown:
568 case sys::fs::file_magic::bitcode:
569 case sys::fs::file_magic::archive:
570 case sys::fs::file_magic::coff_object:
571 case sys::fs::file_magic::pecoff_executable:
Alexey Samsonov9c22f872013-06-18 15:03:28 +0000572 case sys::fs::file_magic::macho_universal_binary:
Rui Ueyamab32b0372013-10-15 22:45:38 +0000573 case sys::fs::file_magic::windows_resource:
Rafael Espindola3ecfcc22013-06-11 18:01:14 +0000574 report_fatal_error("Incompatible object format!");
Eli Benderskya66a1852012-01-16 08:56:09 +0000575 }
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000576 } else {
Eli Benderskya66a1852012-01-16 08:56:09 +0000577 if (!Dyld->isCompatibleFormat(InputBuffer))
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000578 report_fatal_error("Incompatible object format!");
579 }
580
Jim Grosbach6e563312011-03-21 22:15:52 +0000581 return Dyld->loadObject(InputBuffer);
582}
583
Jim Grosbachb0271052011-04-08 17:31:24 +0000584void *RuntimeDyld::getSymbolAddress(StringRef Name) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000585 if (!Dyld)
586 return NULL;
Jim Grosbach6e563312011-03-21 22:15:52 +0000587 return Dyld->getSymbolAddress(Name);
588}
589
Jim Grosbach35ed8422012-09-05 16:50:40 +0000590uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000591 if (!Dyld)
592 return 0;
Jim Grosbach35ed8422012-09-05 16:50:40 +0000593 return Dyld->getSymbolLoadAddress(Name);
594}
595
Jim Grosbachf8c1c842011-04-12 21:20:41 +0000596void RuntimeDyld::resolveRelocations() {
597 Dyld->resolveRelocations();
598}
599
Jim Grosbach61425c02012-01-16 22:26:39 +0000600void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
601 uint64_t Addr) {
602 Dyld->reassignSectionAddress(SectionID, Addr);
Jim Grosbachf8c1c842011-04-12 21:20:41 +0000603}
604
Jim Grosbache940c1b2012-09-13 21:50:06 +0000605void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
Jim Grosbach020f4e82012-01-16 23:50:55 +0000606 uint64_t TargetAddress) {
607 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
608}
609
Jim Grosbach91dde152011-03-22 18:22:27 +0000610StringRef RuntimeDyld::getErrorString() {
Jim Grosbachb3eecaf2011-03-22 18:19:42 +0000611 return Dyld->getErrorString();
612}
613
Andrew Kaylor528f6d72013-10-11 21:25:48 +0000614void RuntimeDyld::registerEHFrames() {
Andrew Kaylor43507d02013-10-16 00:14:21 +0000615 if (Dyld)
616 Dyld->registerEHFrames();
617}
618
619void RuntimeDyld::deregisterEHFrames() {
620 if (Dyld)
621 Dyld->deregisterEHFrames();
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +0000622}
623
Jim Grosbach6e563312011-03-21 22:15:52 +0000624} // end namespace llvm