blob: 6aa6576e2eceb6c40c3944ad7365f41b3617074f [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"
Andrew Kaylor61694532013-10-21 17:42:06 +000022#include "llvm/Support/MutexGuard.h"
Rafael Espindola7486d922013-05-30 03:05:14 +000023#include "llvm/Object/ELF.h"
Eli Bendersky76463fd2012-01-22 07:05:02 +000024
Jim Grosbach6e563312011-03-21 22:15:52 +000025using namespace llvm;
26using namespace llvm::object;
27
Chandler Carruth53c5e7b2011-04-05 23:54:31 +000028// Empty out-of-line virtual destructor as the key function.
Danil Malyshevcf852dc2011-07-13 07:57:58 +000029RuntimeDyldImpl::~RuntimeDyldImpl() {}
Chandler Carruth53c5e7b2011-04-05 23:54:31 +000030
Jim Grosbach6e563312011-03-21 22:15:52 +000031namespace llvm {
Jim Grosbach6e563312011-03-21 22:15:52 +000032
Andrew Kaylor528f6d72013-10-11 21:25:48 +000033void RuntimeDyldImpl::registerEHFrames() {
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +000034}
35
Andrew Kaylor43507d02013-10-16 00:14:21 +000036void RuntimeDyldImpl::deregisterEHFrames() {
37}
38
Jim Grosbachf8c1c842011-04-12 21:20:41 +000039// Resolve the relocations for all symbols we currently know about.
40void RuntimeDyldImpl::resolveRelocations() {
Andrew Kaylor61694532013-10-21 17:42:06 +000041 MutexGuard locked(lock);
42
Preston Gurdc68dda82012-04-12 20:13:57 +000043 // First, resolve relocations associated with external symbols.
Eli Bendersky37bc5a22012-04-30 12:15:58 +000044 resolveExternalSymbols();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000045
Jim Grosbach61425c02012-01-16 22:26:39 +000046 // Just iterate over the sections we have and resolve all the relocations
47 // in them. Gross overkill, but it gets the job done.
48 for (int i = 0, e = Sections.size(); i != e; ++i) {
Andrew Kaylor32bd10b2013-08-19 19:38:06 +000049 // The Section here (Sections[i]) refers to the section in which the
50 // symbol for the relocation is located. The SectionID in the relocation
51 // entry provides the section to which the relocation will be applied.
Andrew Kaylor28989882012-11-05 20:57:16 +000052 uint64_t Addr = Sections[i].LoadAddress;
53 DEBUG(dbgs() << "Resolving relocations Section #" << i
54 << "\t" << format("%p", (uint8_t *)Addr)
55 << "\n");
56 resolveRelocationList(Relocations[i], Addr);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000057 Relocations.erase(i);
Jim Grosbach61425c02012-01-16 22:26:39 +000058 }
Jim Grosbachf8c1c842011-04-12 21:20:41 +000059}
60
Jim Grosbache940c1b2012-09-13 21:50:06 +000061void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
Jim Grosbach020f4e82012-01-16 23:50:55 +000062 uint64_t TargetAddress) {
Andrew Kaylor61694532013-10-21 17:42:06 +000063 MutexGuard locked(lock);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000064 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
65 if (Sections[i].Address == LocalAddress) {
66 reassignSectionAddress(i, TargetAddress);
67 return;
68 }
69 }
70 llvm_unreachable("Attempting to remap address of unknown section!");
Jim Grosbach020f4e82012-01-16 23:50:55 +000071}
72
Eli Bendersky5fe01982012-04-29 12:40:47 +000073// Subclasses can implement this method to create specialized image instances.
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +000074// The caller owns the pointer that is returned.
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000075ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
76 return new ObjectImageCommon(InputBuffer);
Preston Gurd689ff9c2012-04-16 22:12:58 +000077}
78
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000079ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
Andrew Kaylor61694532013-10-21 17:42:06 +000080 MutexGuard locked(lock);
81
Preston Gurd689ff9c2012-04-16 22:12:58 +000082 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
Preston Gurdc68dda82012-04-12 20:13:57 +000083 if (!obj)
84 report_fatal_error("Unable to create object image from memory buffer!");
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000085
Andrew Kaylorab950f52013-10-15 20:44:55 +000086 // Save information about our target
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000087 Arch = (Triple::ArchType)obj->getArch();
Andrew Kaylorab950f52013-10-15 20:44:55 +000088 IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000089
Eli Benderskyd98c9e92012-05-01 06:58:59 +000090 // Symbols found in this object
91 StringMap<SymbolLoc> LocalSymbols;
92 // Used sections from the object file
93 ObjSectionToIDMap LocalSections;
94
Tim Northoverf00677d2012-10-29 10:47:04 +000095 // Common symbols requiring allocation, with their sizes and alignments
Eli Benderskyd98c9e92012-05-01 06:58:59 +000096 CommonSymbolMap CommonSymbols;
Tim Northoverf00677d2012-10-29 10:47:04 +000097 // Maximum required total memory to allocate all common symbols
Eli Benderskyd98c9e92012-05-01 06:58:59 +000098 uint64_t CommonSize = 0;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000099
100 error_code err;
101 // Parse symbols
102 DEBUG(dbgs() << "Parse symbols:\n");
103 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
104 i != e; i.increment(err)) {
105 Check(err);
106 object::SymbolRef::Type SymType;
107 StringRef Name;
108 Check(i->getType(SymType));
109 Check(i->getName(Name));
110
Preston Gurdc68dda82012-04-12 20:13:57 +0000111 uint32_t flags;
112 Check(i->getFlags(flags));
113
114 bool isCommon = flags & SymbolRef::SF_Common;
115 if (isCommon) {
116 // Add the common symbols to a list. We'll allocate them all below.
Rafael Espindola59a0e792013-04-29 22:24:22 +0000117 uint32_t Align;
118 Check(i->getAlignment(Align));
Preston Gurdc68dda82012-04-12 20:13:57 +0000119 uint64_t Size = 0;
120 Check(i->getSize(Size));
Tim Northoverf00677d2012-10-29 10:47:04 +0000121 CommonSize += Size + Align;
122 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
Preston Gurdc68dda82012-04-12 20:13:57 +0000123 } else {
124 if (SymType == object::SymbolRef::ST_Function ||
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000125 SymType == object::SymbolRef::ST_Data ||
126 SymType == object::SymbolRef::ST_Unknown) {
Preston Gurdc68dda82012-04-12 20:13:57 +0000127 uint64_t FileOffset;
Eli Bendersky5fe01982012-04-29 12:40:47 +0000128 StringRef SectionData;
Tim Northover78822132012-12-17 17:59:35 +0000129 bool IsCode;
Preston Gurdc68dda82012-04-12 20:13:57 +0000130 section_iterator si = obj->end_sections();
131 Check(i->getFileOffset(FileOffset));
132 Check(i->getSection(si));
133 if (si == obj->end_sections()) continue;
Eli Bendersky5fe01982012-04-29 12:40:47 +0000134 Check(si->getContents(SectionData));
Tim Northover78822132012-12-17 17:59:35 +0000135 Check(si->isText(IsCode));
Preston Gurdc68dda82012-04-12 20:13:57 +0000136 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
137 (uintptr_t)FileOffset;
Eli Bendersky5fe01982012-04-29 12:40:47 +0000138 uintptr_t SectOffset = (uintptr_t)(SymPtr -
139 (const uint8_t*)SectionData.begin());
Tim Northover78822132012-12-17 17:59:35 +0000140 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
Preston Gurdc68dda82012-04-12 20:13:57 +0000141 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
142 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
143 << " flags: " << flags
144 << " SID: " << SectionID
145 << " Offset: " << format("%p", SectOffset));
Amara Emerson098d6d52012-11-16 11:11:59 +0000146 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
Preston Gurdc68dda82012-04-12 20:13:57 +0000147 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000148 }
149 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
150 }
151
Preston Gurdc68dda82012-04-12 20:13:57 +0000152 // Allocate common symbols
153 if (CommonSize != 0)
Preston Gurd689ff9c2012-04-16 22:12:58 +0000154 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
Preston Gurdc68dda82012-04-12 20:13:57 +0000155
Eli Bendersky5fe01982012-04-29 12:40:47 +0000156 // Parse and process relocations
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000157 DEBUG(dbgs() << "Parse relocations:\n");
158 for (section_iterator si = obj->begin_sections(),
159 se = obj->end_sections(); si != se; si.increment(err)) {
160 Check(err);
161 bool isFirstRelocation = true;
162 unsigned SectionID = 0;
163 StubMap Stubs;
Rafael Espindola7486d922013-05-30 03:05:14 +0000164 section_iterator RelocatedSection = si->getRelocatedSection();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000165
166 for (relocation_iterator i = si->begin_relocations(),
167 e = si->end_relocations(); i != e; i.increment(err)) {
168 Check(err);
169
Eli Bendersky5fe01982012-04-29 12:40:47 +0000170 // If it's the first relocation in this section, find its SectionID
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000171 if (isFirstRelocation) {
Rafael Espindola7486d922013-05-30 03:05:14 +0000172 SectionID =
173 findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000174 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
175 isFirstRelocation = false;
176 }
177
Rafael Espindolaca0e7362013-04-29 19:03:21 +0000178 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
Rafael Espindolaefa91f62013-04-29 14:44:23 +0000179 Stubs);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000180 }
181 }
Preston Gurd689ff9c2012-04-16 22:12:58 +0000182
Andrew Kaylorff9fa052013-08-19 23:27:43 +0000183 // Give the subclasses a chance to tie-up any loose ends.
Andrew Kaylor528f6d72013-10-11 21:25:48 +0000184 finalizeLoad(LocalSections);
Andrew Kaylorff9fa052013-08-19 23:27:43 +0000185
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000186 return obj.take();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000187}
188
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000189void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
190 const CommonSymbolMap &CommonSymbols,
191 uint64_t TotalSize,
192 SymbolTableMap &SymbolTable) {
Preston Gurdc68dda82012-04-12 20:13:57 +0000193 // Allocate memory for the section
194 unsigned SectionID = Sections.size();
Filip Pizlo6eb43d22013-10-02 00:59:25 +0000195 uint8_t *Addr = MemMgr->allocateDataSection(
196 TotalSize, sizeof(void*), SectionID, StringRef(), false);
Preston Gurdc68dda82012-04-12 20:13:57 +0000197 if (!Addr)
198 report_fatal_error("Unable to allocate memory for common symbols!");
199 uint64_t Offset = 0;
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +0000200 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
Preston Gurdc68dda82012-04-12 20:13:57 +0000201 memset(Addr, 0, TotalSize);
202
203 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
204 << " new addr: " << format("%p", Addr)
205 << " DataSize: " << TotalSize
206 << "\n");
207
208 // Assign the address of each symbol
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000209 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
210 itEnd = CommonSymbols.end(); it != itEnd; it++) {
Tim Northoverf00677d2012-10-29 10:47:04 +0000211 uint64_t Size = it->second.first;
212 uint64_t Align = it->second.second;
Preston Gurdc68dda82012-04-12 20:13:57 +0000213 StringRef Name;
214 it->first.getName(Name);
Tim Northoverf00677d2012-10-29 10:47:04 +0000215 if (Align) {
216 // This symbol has an alignment requirement.
217 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
218 Addr += AlignOffset;
219 Offset += AlignOffset;
220 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
Andrew Kaylor5fc8c7c2012-11-01 19:49:21 +0000221 format("%p\n", Addr));
Tim Northoverf00677d2012-10-29 10:47:04 +0000222 }
Preston Gurd689ff9c2012-04-16 22:12:58 +0000223 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000224 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
Preston Gurdc68dda82012-04-12 20:13:57 +0000225 Offset += Size;
226 Addr += Size;
227 }
Preston Gurdc68dda82012-04-12 20:13:57 +0000228}
229
Preston Gurd689ff9c2012-04-16 22:12:58 +0000230unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
231 const SectionRef &Section,
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000232 bool IsCode) {
233
234 unsigned StubBufSize = 0,
235 StubSize = getMaxStubSize();
236 error_code err;
Rafael Espindola7486d922013-05-30 03:05:14 +0000237 const ObjectFile *ObjFile = Obj.getObjectFile();
238 // FIXME: this is an inefficient way to handle this. We should computed the
239 // necessary section allocation size in loadObject by walking all the sections
240 // once.
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000241 if (StubSize > 0) {
Rafael Espindola7486d922013-05-30 03:05:14 +0000242 for (section_iterator SI = ObjFile->begin_sections(),
243 SE = ObjFile->end_sections();
244 SI != SE; SI.increment(err), Check(err)) {
245 section_iterator RelSecI = SI->getRelocatedSection();
246 if (!(RelSecI == Section))
247 continue;
248
249 for (relocation_iterator I = SI->begin_relocations(),
250 E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
251 StubBufSize += StubSize;
252 }
253 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000254 }
Rafael Espindola7486d922013-05-30 03:05:14 +0000255
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000256 StringRef data;
257 uint64_t Alignment64;
258 Check(Section.getContents(data));
259 Check(Section.getAlignment(Alignment64));
260
261 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
Preston Gurdc68dda82012-04-12 20:13:57 +0000262 bool IsRequired;
263 bool IsVirtual;
264 bool IsZeroInit;
Andrew Kaylor53608a32012-11-15 23:50:01 +0000265 bool IsReadOnly;
Preston Gurdc68dda82012-04-12 20:13:57 +0000266 uint64_t DataSize;
Andrew Kaylor28a76552013-10-16 00:32:24 +0000267 unsigned PaddingSize = 0;
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000268 StringRef Name;
Preston Gurdc68dda82012-04-12 20:13:57 +0000269 Check(Section.isRequiredForExecution(IsRequired));
270 Check(Section.isVirtual(IsVirtual));
271 Check(Section.isZeroInit(IsZeroInit));
Andrew Kaylor53608a32012-11-15 23:50:01 +0000272 Check(Section.isReadOnlyData(IsReadOnly));
Preston Gurdc68dda82012-04-12 20:13:57 +0000273 Check(Section.getSize(DataSize));
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000274 Check(Section.getName(Name));
Richard Sandiford6fc2ad62013-05-03 14:15:35 +0000275 if (StubSize > 0) {
276 unsigned StubAlignment = getStubAlignment();
277 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
278 if (StubAlignment > EndAlignment)
279 StubBufSize += StubAlignment - EndAlignment;
280 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000281
Andrew Kaylor28a76552013-10-16 00:32:24 +0000282 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
283 // with zeroes added at the end. For MachO objects, this section has a
284 // slightly different name, so this won't have any effect for MachO objects.
285 if (Name == ".eh_frame")
286 PaddingSize = 4;
287
Preston Gurdc68dda82012-04-12 20:13:57 +0000288 unsigned Allocate;
289 unsigned SectionID = Sections.size();
290 uint8_t *Addr;
291 const char *pData = 0;
292
293 // Some sections, such as debug info, don't need to be loaded for execution.
294 // Leave those where they are.
295 if (IsRequired) {
Andrew Kaylor28a76552013-10-16 00:32:24 +0000296 Allocate = DataSize + PaddingSize + StubBufSize;
Preston Gurdc68dda82012-04-12 20:13:57 +0000297 Addr = IsCode
Filip Pizlo6eb43d22013-10-02 00:59:25 +0000298 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
299 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
300 IsReadOnly);
Preston Gurdc68dda82012-04-12 20:13:57 +0000301 if (!Addr)
302 report_fatal_error("Unable to allocate section memory!");
303
304 // Virtual sections have no data in the object image, so leave pData = 0
305 if (!IsVirtual)
306 pData = data.data();
307
308 // Zero-initialize or copy the data from the image
309 if (IsZeroInit || IsVirtual)
310 memset(Addr, 0, DataSize);
311 else
312 memcpy(Addr, pData, DataSize);
313
Andrew Kaylor28a76552013-10-16 00:32:24 +0000314 // Fill in any extra bytes we allocated for padding
315 if (PaddingSize != 0) {
316 memset(Addr + DataSize, 0, PaddingSize);
317 // Update the DataSize variable so that the stub offset is set correctly.
318 DataSize += PaddingSize;
319 }
320
Preston Gurdc68dda82012-04-12 20:13:57 +0000321 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000322 << " Name: " << Name
Preston Gurdc68dda82012-04-12 20:13:57 +0000323 << " obj addr: " << format("%p", pData)
324 << " new addr: " << format("%p", Addr)
325 << " DataSize: " << DataSize
326 << " StubBufSize: " << StubBufSize
327 << " Allocate: " << Allocate
328 << "\n");
Preston Gurd689ff9c2012-04-16 22:12:58 +0000329 Obj.updateSectionAddress(Section, (uint64_t)Addr);
Preston Gurdc68dda82012-04-12 20:13:57 +0000330 }
331 else {
332 // Even if we didn't load the section, we need to record an entry for it
Eli Bendersky5fe01982012-04-29 12:40:47 +0000333 // to handle later processing (and by 'handle' I mean don't do anything
334 // with these sections).
Preston Gurdc68dda82012-04-12 20:13:57 +0000335 Allocate = 0;
336 Addr = 0;
337 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000338 << " Name: " << Name
Preston Gurdc68dda82012-04-12 20:13:57 +0000339 << " obj addr: " << format("%p", data.data())
340 << " new addr: 0"
341 << " DataSize: " << DataSize
342 << " StubBufSize: " << StubBufSize
343 << " Allocate: " << Allocate
344 << "\n");
345 }
346
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +0000347 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000348 return SectionID;
349}
350
Preston Gurd689ff9c2012-04-16 22:12:58 +0000351unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
352 const SectionRef &Section,
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000353 bool IsCode,
354 ObjSectionToIDMap &LocalSections) {
355
356 unsigned SectionID = 0;
357 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
358 if (i != LocalSections.end())
359 SectionID = i->second;
360 else {
Preston Gurd689ff9c2012-04-16 22:12:58 +0000361 SectionID = emitSection(Obj, Section, IsCode);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000362 LocalSections[Section] = SectionID;
363 }
364 return SectionID;
365}
366
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000367void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
368 unsigned SectionID) {
369 Relocations[SectionID].push_back(RE);
370}
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000371
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000372void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
373 StringRef SymbolName) {
374 // Relocation by symbol. If the symbol is found in the global symbol table,
375 // create an appropriate section relocation. Otherwise, add it to
376 // ExternalSymbolRelocations.
377 SymbolTableMap::const_iterator Loc =
378 GlobalSymbolTable.find(SymbolName);
379 if (Loc == GlobalSymbolTable.end()) {
380 ExternalSymbolRelocations[SymbolName].push_back(RE);
Eli Bendersky37bc5a22012-04-30 12:15:58 +0000381 } else {
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000382 // Copy the RE since we want to modify its addend.
383 RelocationEntry RECopy = RE;
384 RECopy.Addend += Loc->second.second;
385 Relocations[Loc->second.first].push_back(RECopy);
Eli Bendersky37bc5a22012-04-30 12:15:58 +0000386 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000387}
388
389uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
Tim Northover4a9b6b72013-05-04 20:14:09 +0000390 if (Arch == Triple::aarch64) {
391 // This stub has to be able to access the full address space,
392 // since symbol lookup won't necessarily find a handy, in-range,
393 // PLT stub for functions which could be anywhere.
394 uint32_t *StubAddr = (uint32_t*)Addr;
395
396 // Stub can use ip0 (== x16) to calculate address
397 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
398 StubAddr++;
399 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
400 StubAddr++;
401 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
402 StubAddr++;
403 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
404 StubAddr++;
405 *StubAddr = 0xd61f0200; // br ip0
406
407 return Addr;
408 } else if (Arch == Triple::arm) {
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000409 // TODO: There is only ARM far stub now. We should add the Thumb stub,
410 // and stubs for branches Thumb - ARM and ARM - Thumb.
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000411 uint32_t *StubAddr = (uint32_t*)Addr;
412 *StubAddr = 0xe51ff004; // ldr pc,<label>
413 return (uint8_t*)++StubAddr;
NAKAMURA Takumi4af1ca52012-12-04 00:08:14 +0000414 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000415 uint32_t *StubAddr = (uint32_t*)Addr;
416 // 0: 3c190000 lui t9,%hi(addr).
417 // 4: 27390000 addiu t9,t9,%lo(addr).
418 // 8: 03200008 jr t9.
419 // c: 00000000 nop.
420 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
421 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
422
423 *StubAddr = LuiT9Instr;
424 StubAddr++;
425 *StubAddr = AdduiT9Instr;
426 StubAddr++;
427 *StubAddr = JrT9Instr;
428 StubAddr++;
429 *StubAddr = NopInstr;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000430 return Addr;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000431 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000432 // PowerPC64 stub: the address points to a function descriptor
433 // instead of the function itself. Load the function address
434 // on r11 and sets it to control register. Also loads the function
435 // TOC in r2 and environment pointer to r11.
436 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
437 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
438 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
439 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
440 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
441 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
442 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
443 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
444 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
445 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
446 writeInt32BE(Addr+40, 0x4E800420); // bctr
Andrew Kaylor5fc8c7c2012-11-01 19:49:21 +0000447
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000448 return Addr;
Richard Sandiford6fc2ad62013-05-03 14:15:35 +0000449 } else if (Arch == Triple::systemz) {
450 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
451 writeInt16BE(Addr+2, 0x0000);
452 writeInt16BE(Addr+4, 0x0004);
453 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
454 // 8-byte address stored at Addr + 8
455 return Addr;
Andrew Kaylorff9fa052013-08-19 23:27:43 +0000456 } else if (Arch == Triple::x86_64) {
457 *Addr = 0xFF; // jmp
458 *(Addr+1) = 0x25; // rip
459 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000460 }
461 return Addr;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000462}
463
464// Assign an address to a symbol name and resolve all the relocations
465// associated with it.
466void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
467 uint64_t Addr) {
468 // The address to use for relocation resolution is not
469 // the address of the local section buffer. We must be doing
Andrew Kaylor28989882012-11-05 20:57:16 +0000470 // a remote execution environment of some sort. Relocations can't
471 // be applied until all the sections have been moved. The client must
472 // trigger this with a call to MCJIT::finalize() or
473 // RuntimeDyld::resolveRelocations().
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000474 //
475 // Addr is a uint64_t because we can't assume the pointer width
476 // of the target is the same as that of the host. Just use a generic
477 // "big enough" type.
478 Sections[SectionID].LoadAddress = Addr;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000479}
480
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000481void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
482 uint64_t Value) {
483 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola87b50172013-04-29 17:24:34 +0000484 const RelocationEntry &RE = Relocs[i];
485 // Ignore relocations for sections that were not loaded
486 if (Sections[RE.SectionID].Address == 0)
487 continue;
488 resolveRelocation(RE, Value);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000489 }
490}
491
Eli Bendersky37bc5a22012-04-30 12:15:58 +0000492void RuntimeDyldImpl::resolveExternalSymbols() {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000493 while(!ExternalSymbolRelocations.empty()) {
494 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
495
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000496 StringRef Name = i->first();
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000497 if (Name.size() == 0) {
498 // This is an absolute symbol, use an address of zero.
499 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
Andrew Kaylor559d4092013-11-11 19:55:10 +0000500 RelocationList &Relocs = i->second;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000501 resolveRelocationList(Relocs, 0);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000502 } else {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000503 uint64_t Addr = 0;
504 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
505 if (Loc == GlobalSymbolTable.end()) {
506 // This is an external symbol, try to get its address from
507 // MemoryManager.
508 Addr = MemMgr->getSymbolAddress(Name.data());
Andrew Kaylor559d4092013-11-11 19:55:10 +0000509 // The call to getSymbolAddress may have caused additional modules to
510 // be loaded, which may have added new entries to the
511 // ExternalSymbolRelocations map. Consquently, we need to update our
512 // iterator. This is also why retrieval of the relocation list
513 // associated with this symbol is deferred until below this point.
514 // New entries may have been added to the relocation list.
515 i = ExternalSymbolRelocations.find(Name);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000516 } else {
517 // We found the symbol in our global table. It was probably in a
518 // Module that we loaded previously.
Yaron Keren4805bf52013-10-19 09:04:26 +0000519 SymbolLoc SymLoc = Loc->second;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000520 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
521 }
522
523 // FIXME: Implement error handling that doesn't kill the host program!
524 if (!Addr)
525 report_fatal_error("Program used external function '" + Name +
526 "' which could not be resolved!");
527
528 updateGOTEntries(Name, Addr);
529 DEBUG(dbgs() << "Resolving relocations Name: " << Name
530 << "\t" << format("0x%lx", Addr)
531 << "\n");
Andrew Kaylor559d4092013-11-11 19:55:10 +0000532 // This list may have been updated when we called getSymbolAddress, so
533 // don't change this code to get the list earlier.
534 RelocationList &Relocs = i->second;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000535 resolveRelocationList(Relocs, Addr);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000536 }
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000537
Andrew Kaylor559d4092013-11-11 19:55:10 +0000538 ExternalSymbolRelocations.erase(i);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000539 }
540}
541
542
Jim Grosbach6e563312011-03-21 22:15:52 +0000543//===----------------------------------------------------------------------===//
544// RuntimeDyld class implementation
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000545RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
Andrew Kaylor53608a32012-11-15 23:50:01 +0000546 // FIXME: There's a potential issue lurking here if a single instance of
547 // RuntimeDyld is used to load multiple objects. The current implementation
548 // associates a single memory manager with a RuntimeDyld instance. Even
549 // though the public class spawns a new 'impl' instance for each load,
550 // they share a single memory manager. This can become a problem when page
551 // permissions are applied.
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000552 Dyld = 0;
553 MM = mm;
Jim Grosbach6e563312011-03-21 22:15:52 +0000554}
555
556RuntimeDyld::~RuntimeDyld() {
557 delete Dyld;
558}
559
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000560ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000561 if (!Dyld) {
Rafael Espindola3ecfcc22013-06-11 18:01:14 +0000562 sys::fs::file_magic Type =
563 sys::fs::identify_magic(InputBuffer->getBuffer());
564 switch (Type) {
565 case sys::fs::file_magic::elf_relocatable:
566 case sys::fs::file_magic::elf_executable:
567 case sys::fs::file_magic::elf_shared_object:
568 case sys::fs::file_magic::elf_core:
569 Dyld = new RuntimeDyldELF(MM);
570 break;
571 case sys::fs::file_magic::macho_object:
572 case sys::fs::file_magic::macho_executable:
573 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
574 case sys::fs::file_magic::macho_core:
575 case sys::fs::file_magic::macho_preload_executable:
576 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
577 case sys::fs::file_magic::macho_dynamic_linker:
578 case sys::fs::file_magic::macho_bundle:
579 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
580 case sys::fs::file_magic::macho_dsym_companion:
581 Dyld = new RuntimeDyldMachO(MM);
582 break;
583 case sys::fs::file_magic::unknown:
584 case sys::fs::file_magic::bitcode:
585 case sys::fs::file_magic::archive:
586 case sys::fs::file_magic::coff_object:
587 case sys::fs::file_magic::pecoff_executable:
Alexey Samsonov9c22f872013-06-18 15:03:28 +0000588 case sys::fs::file_magic::macho_universal_binary:
Rui Ueyamab32b0372013-10-15 22:45:38 +0000589 case sys::fs::file_magic::windows_resource:
Rafael Espindola3ecfcc22013-06-11 18:01:14 +0000590 report_fatal_error("Incompatible object format!");
Eli Benderskya66a1852012-01-16 08:56:09 +0000591 }
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000592 } else {
Eli Benderskya66a1852012-01-16 08:56:09 +0000593 if (!Dyld->isCompatibleFormat(InputBuffer))
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000594 report_fatal_error("Incompatible object format!");
595 }
596
Jim Grosbach6e563312011-03-21 22:15:52 +0000597 return Dyld->loadObject(InputBuffer);
598}
599
Jim Grosbachb0271052011-04-08 17:31:24 +0000600void *RuntimeDyld::getSymbolAddress(StringRef Name) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000601 if (!Dyld)
602 return NULL;
Jim Grosbach6e563312011-03-21 22:15:52 +0000603 return Dyld->getSymbolAddress(Name);
604}
605
Jim Grosbach35ed8422012-09-05 16:50:40 +0000606uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000607 if (!Dyld)
608 return 0;
Jim Grosbach35ed8422012-09-05 16:50:40 +0000609 return Dyld->getSymbolLoadAddress(Name);
610}
611
Jim Grosbachf8c1c842011-04-12 21:20:41 +0000612void RuntimeDyld::resolveRelocations() {
613 Dyld->resolveRelocations();
614}
615
Jim Grosbach61425c02012-01-16 22:26:39 +0000616void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
617 uint64_t Addr) {
618 Dyld->reassignSectionAddress(SectionID, Addr);
Jim Grosbachf8c1c842011-04-12 21:20:41 +0000619}
620
Jim Grosbache940c1b2012-09-13 21:50:06 +0000621void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
Jim Grosbach020f4e82012-01-16 23:50:55 +0000622 uint64_t TargetAddress) {
623 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
624}
625
Jim Grosbach91dde152011-03-22 18:22:27 +0000626StringRef RuntimeDyld::getErrorString() {
Jim Grosbachb3eecaf2011-03-22 18:19:42 +0000627 return Dyld->getErrorString();
628}
629
Andrew Kaylor528f6d72013-10-11 21:25:48 +0000630void RuntimeDyld::registerEHFrames() {
Andrew Kaylor43507d02013-10-16 00:14:21 +0000631 if (Dyld)
632 Dyld->registerEHFrames();
633}
634
635void RuntimeDyld::deregisterEHFrames() {
636 if (Dyld)
637 Dyld->deregisterEHFrames();
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +0000638}
639
Jim Grosbach6e563312011-03-21 22:15:52 +0000640} // end namespace llvm