blob: 161135a4f8c0f6622c902e0ad2e2fe13870edabe [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"
Juergen Ributzka35436252013-11-19 00:57:56 +000016#include "JITRegistrar.h"
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000017#include "ObjectImageCommon.h"
Eli Bendersky76463fd2012-01-22 07:05:02 +000018#include "RuntimeDyldELF.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000019#include "RuntimeDyldImpl.h"
Eli Bendersky76463fd2012-01-22 07:05:02 +000020#include "RuntimeDyldMachO.h"
Rafael Espindola3ecfcc22013-06-11 18:01:14 +000021#include "llvm/Support/FileSystem.h"
Tim Northoverf00677d2012-10-29 10:47:04 +000022#include "llvm/Support/MathExtras.h"
Andrew Kaylor61694532013-10-21 17:42:06 +000023#include "llvm/Support/MutexGuard.h"
Rafael Espindola7486d922013-05-30 03:05:14 +000024#include "llvm/Object/ELF.h"
Eli Bendersky76463fd2012-01-22 07:05:02 +000025
Jim Grosbach6e563312011-03-21 22:15:52 +000026using namespace llvm;
27using namespace llvm::object;
28
Chandler Carruth53c5e7b2011-04-05 23:54:31 +000029// Empty out-of-line virtual destructor as the key function.
Danil Malyshevcf852dc2011-07-13 07:57:58 +000030RuntimeDyldImpl::~RuntimeDyldImpl() {}
Chandler Carruth53c5e7b2011-04-05 23:54:31 +000031
Juergen Ributzka35436252013-11-19 00:57:56 +000032// Pin the JITRegistrar's and ObjectImage*'s vtables to this file.
33void JITRegistrar::anchor() {}
34void ObjectImage::anchor() {}
35void ObjectImageCommon::anchor() {}
36
Jim Grosbach6e563312011-03-21 22:15:52 +000037namespace llvm {
Jim Grosbach6e563312011-03-21 22:15:52 +000038
Andrew Kaylor528f6d72013-10-11 21:25:48 +000039void RuntimeDyldImpl::registerEHFrames() {
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +000040}
41
Andrew Kaylor43507d02013-10-16 00:14:21 +000042void RuntimeDyldImpl::deregisterEHFrames() {
43}
44
Jim Grosbachf8c1c842011-04-12 21:20:41 +000045// Resolve the relocations for all symbols we currently know about.
46void RuntimeDyldImpl::resolveRelocations() {
Andrew Kaylor61694532013-10-21 17:42:06 +000047 MutexGuard locked(lock);
48
Preston Gurdc68dda82012-04-12 20:13:57 +000049 // First, resolve relocations associated with external symbols.
Eli Bendersky37bc5a22012-04-30 12:15:58 +000050 resolveExternalSymbols();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000051
Jim Grosbach61425c02012-01-16 22:26:39 +000052 // Just iterate over the sections we have and resolve all the relocations
53 // in them. Gross overkill, but it gets the job done.
54 for (int i = 0, e = Sections.size(); i != e; ++i) {
Andrew Kaylor32bd10b2013-08-19 19:38:06 +000055 // The Section here (Sections[i]) refers to the section in which the
56 // symbol for the relocation is located. The SectionID in the relocation
57 // entry provides the section to which the relocation will be applied.
Andrew Kaylor28989882012-11-05 20:57:16 +000058 uint64_t Addr = Sections[i].LoadAddress;
59 DEBUG(dbgs() << "Resolving relocations Section #" << i
60 << "\t" << format("%p", (uint8_t *)Addr)
61 << "\n");
62 resolveRelocationList(Relocations[i], Addr);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +000063 Relocations.erase(i);
Jim Grosbach61425c02012-01-16 22:26:39 +000064 }
Jim Grosbachf8c1c842011-04-12 21:20:41 +000065}
66
Jim Grosbache940c1b2012-09-13 21:50:06 +000067void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
Jim Grosbach020f4e82012-01-16 23:50:55 +000068 uint64_t TargetAddress) {
Andrew Kaylor61694532013-10-21 17:42:06 +000069 MutexGuard locked(lock);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000070 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
71 if (Sections[i].Address == LocalAddress) {
72 reassignSectionAddress(i, TargetAddress);
73 return;
74 }
75 }
76 llvm_unreachable("Attempting to remap address of unknown section!");
Jim Grosbach020f4e82012-01-16 23:50:55 +000077}
78
Eli Bendersky5fe01982012-04-29 12:40:47 +000079// Subclasses can implement this method to create specialized image instances.
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +000080// The caller owns the pointer that is returned.
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000081ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
82 return new ObjectImageCommon(InputBuffer);
Preston Gurd689ff9c2012-04-16 22:12:58 +000083}
84
Andrew Kaylor3f23cef2012-10-02 21:18:39 +000085ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
Andrew Kaylor61694532013-10-21 17:42:06 +000086 MutexGuard locked(lock);
87
Preston Gurd689ff9c2012-04-16 22:12:58 +000088 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
Preston Gurdc68dda82012-04-12 20:13:57 +000089 if (!obj)
90 report_fatal_error("Unable to create object image from memory buffer!");
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000091
Andrew Kaylorab950f52013-10-15 20:44:55 +000092 // Save information about our target
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000093 Arch = (Triple::ArchType)obj->getArch();
Andrew Kaylorab950f52013-10-15 20:44:55 +000094 IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +000095
Eli Benderskyd98c9e92012-05-01 06:58:59 +000096 // Symbols found in this object
97 StringMap<SymbolLoc> LocalSymbols;
98 // Used sections from the object file
99 ObjSectionToIDMap LocalSections;
100
Tim Northoverf00677d2012-10-29 10:47:04 +0000101 // Common symbols requiring allocation, with their sizes and alignments
Eli Benderskyd98c9e92012-05-01 06:58:59 +0000102 CommonSymbolMap CommonSymbols;
Tim Northoverf00677d2012-10-29 10:47:04 +0000103 // Maximum required total memory to allocate all common symbols
Eli Benderskyd98c9e92012-05-01 06:58:59 +0000104 uint64_t CommonSize = 0;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000105
106 error_code err;
107 // Parse symbols
108 DEBUG(dbgs() << "Parse symbols:\n");
109 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
110 i != e; i.increment(err)) {
111 Check(err);
112 object::SymbolRef::Type SymType;
113 StringRef Name;
114 Check(i->getType(SymType));
115 Check(i->getName(Name));
116
Preston Gurdc68dda82012-04-12 20:13:57 +0000117 uint32_t flags;
118 Check(i->getFlags(flags));
119
120 bool isCommon = flags & SymbolRef::SF_Common;
121 if (isCommon) {
122 // Add the common symbols to a list. We'll allocate them all below.
Rafael Espindola59a0e792013-04-29 22:24:22 +0000123 uint32_t Align;
124 Check(i->getAlignment(Align));
Preston Gurdc68dda82012-04-12 20:13:57 +0000125 uint64_t Size = 0;
126 Check(i->getSize(Size));
Tim Northoverf00677d2012-10-29 10:47:04 +0000127 CommonSize += Size + Align;
128 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
Preston Gurdc68dda82012-04-12 20:13:57 +0000129 } else {
130 if (SymType == object::SymbolRef::ST_Function ||
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000131 SymType == object::SymbolRef::ST_Data ||
132 SymType == object::SymbolRef::ST_Unknown) {
Preston Gurdc68dda82012-04-12 20:13:57 +0000133 uint64_t FileOffset;
Eli Bendersky5fe01982012-04-29 12:40:47 +0000134 StringRef SectionData;
Tim Northover78822132012-12-17 17:59:35 +0000135 bool IsCode;
Preston Gurdc68dda82012-04-12 20:13:57 +0000136 section_iterator si = obj->end_sections();
137 Check(i->getFileOffset(FileOffset));
138 Check(i->getSection(si));
139 if (si == obj->end_sections()) continue;
Eli Bendersky5fe01982012-04-29 12:40:47 +0000140 Check(si->getContents(SectionData));
Tim Northover78822132012-12-17 17:59:35 +0000141 Check(si->isText(IsCode));
Preston Gurdc68dda82012-04-12 20:13:57 +0000142 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
143 (uintptr_t)FileOffset;
Eli Bendersky5fe01982012-04-29 12:40:47 +0000144 uintptr_t SectOffset = (uintptr_t)(SymPtr -
145 (const uint8_t*)SectionData.begin());
Tim Northover78822132012-12-17 17:59:35 +0000146 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
Preston Gurdc68dda82012-04-12 20:13:57 +0000147 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
148 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
149 << " flags: " << flags
150 << " SID: " << SectionID
151 << " Offset: " << format("%p", SectOffset));
Amara Emerson098d6d52012-11-16 11:11:59 +0000152 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
Preston Gurdc68dda82012-04-12 20:13:57 +0000153 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000154 }
155 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
156 }
157
Preston Gurdc68dda82012-04-12 20:13:57 +0000158 // Allocate common symbols
159 if (CommonSize != 0)
Preston Gurd689ff9c2012-04-16 22:12:58 +0000160 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
Preston Gurdc68dda82012-04-12 20:13:57 +0000161
Eli Bendersky5fe01982012-04-29 12:40:47 +0000162 // Parse and process relocations
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000163 DEBUG(dbgs() << "Parse relocations:\n");
164 for (section_iterator si = obj->begin_sections(),
165 se = obj->end_sections(); si != se; si.increment(err)) {
166 Check(err);
167 bool isFirstRelocation = true;
168 unsigned SectionID = 0;
169 StubMap Stubs;
Rafael Espindola7486d922013-05-30 03:05:14 +0000170 section_iterator RelocatedSection = si->getRelocatedSection();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000171
172 for (relocation_iterator i = si->begin_relocations(),
173 e = si->end_relocations(); i != e; i.increment(err)) {
174 Check(err);
175
Eli Bendersky5fe01982012-04-29 12:40:47 +0000176 // If it's the first relocation in this section, find its SectionID
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000177 if (isFirstRelocation) {
Rafael Espindola7486d922013-05-30 03:05:14 +0000178 SectionID =
179 findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000180 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
181 isFirstRelocation = false;
182 }
183
Rafael Espindolaca0e7362013-04-29 19:03:21 +0000184 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
Rafael Espindolaefa91f62013-04-29 14:44:23 +0000185 Stubs);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000186 }
187 }
Preston Gurd689ff9c2012-04-16 22:12:58 +0000188
Andrew Kaylorff9fa052013-08-19 23:27:43 +0000189 // Give the subclasses a chance to tie-up any loose ends.
Andrew Kaylor528f6d72013-10-11 21:25:48 +0000190 finalizeLoad(LocalSections);
Andrew Kaylorff9fa052013-08-19 23:27:43 +0000191
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000192 return obj.take();
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000193}
194
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000195void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
196 const CommonSymbolMap &CommonSymbols,
197 uint64_t TotalSize,
198 SymbolTableMap &SymbolTable) {
Preston Gurdc68dda82012-04-12 20:13:57 +0000199 // Allocate memory for the section
200 unsigned SectionID = Sections.size();
Filip Pizlo6eb43d22013-10-02 00:59:25 +0000201 uint8_t *Addr = MemMgr->allocateDataSection(
202 TotalSize, sizeof(void*), SectionID, StringRef(), false);
Preston Gurdc68dda82012-04-12 20:13:57 +0000203 if (!Addr)
204 report_fatal_error("Unable to allocate memory for common symbols!");
205 uint64_t Offset = 0;
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +0000206 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
Preston Gurdc68dda82012-04-12 20:13:57 +0000207 memset(Addr, 0, TotalSize);
208
209 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
210 << " new addr: " << format("%p", Addr)
211 << " DataSize: " << TotalSize
212 << "\n");
213
214 // Assign the address of each symbol
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000215 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
216 itEnd = CommonSymbols.end(); it != itEnd; it++) {
Tim Northoverf00677d2012-10-29 10:47:04 +0000217 uint64_t Size = it->second.first;
218 uint64_t Align = it->second.second;
Preston Gurdc68dda82012-04-12 20:13:57 +0000219 StringRef Name;
220 it->first.getName(Name);
Tim Northoverf00677d2012-10-29 10:47:04 +0000221 if (Align) {
222 // This symbol has an alignment requirement.
223 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
224 Addr += AlignOffset;
225 Offset += AlignOffset;
226 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
Andrew Kaylor5fc8c7c2012-11-01 19:49:21 +0000227 format("%p\n", Addr));
Tim Northoverf00677d2012-10-29 10:47:04 +0000228 }
Preston Gurd689ff9c2012-04-16 22:12:58 +0000229 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000230 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
Preston Gurdc68dda82012-04-12 20:13:57 +0000231 Offset += Size;
232 Addr += Size;
233 }
Preston Gurdc68dda82012-04-12 20:13:57 +0000234}
235
Preston Gurd689ff9c2012-04-16 22:12:58 +0000236unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
237 const SectionRef &Section,
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000238 bool IsCode) {
239
240 unsigned StubBufSize = 0,
241 StubSize = getMaxStubSize();
242 error_code err;
Rafael Espindola7486d922013-05-30 03:05:14 +0000243 const ObjectFile *ObjFile = Obj.getObjectFile();
244 // FIXME: this is an inefficient way to handle this. We should computed the
245 // necessary section allocation size in loadObject by walking all the sections
246 // once.
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000247 if (StubSize > 0) {
Rafael Espindola7486d922013-05-30 03:05:14 +0000248 for (section_iterator SI = ObjFile->begin_sections(),
249 SE = ObjFile->end_sections();
250 SI != SE; SI.increment(err), Check(err)) {
251 section_iterator RelSecI = SI->getRelocatedSection();
252 if (!(RelSecI == Section))
253 continue;
254
255 for (relocation_iterator I = SI->begin_relocations(),
256 E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
257 StubBufSize += StubSize;
258 }
259 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000260 }
Rafael Espindola7486d922013-05-30 03:05:14 +0000261
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000262 StringRef data;
263 uint64_t Alignment64;
264 Check(Section.getContents(data));
265 Check(Section.getAlignment(Alignment64));
266
267 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
Preston Gurdc68dda82012-04-12 20:13:57 +0000268 bool IsRequired;
269 bool IsVirtual;
270 bool IsZeroInit;
Andrew Kaylor53608a32012-11-15 23:50:01 +0000271 bool IsReadOnly;
Preston Gurdc68dda82012-04-12 20:13:57 +0000272 uint64_t DataSize;
Andrew Kaylor28a76552013-10-16 00:32:24 +0000273 unsigned PaddingSize = 0;
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000274 StringRef Name;
Preston Gurdc68dda82012-04-12 20:13:57 +0000275 Check(Section.isRequiredForExecution(IsRequired));
276 Check(Section.isVirtual(IsVirtual));
277 Check(Section.isZeroInit(IsZeroInit));
Andrew Kaylor53608a32012-11-15 23:50:01 +0000278 Check(Section.isReadOnlyData(IsReadOnly));
Preston Gurdc68dda82012-04-12 20:13:57 +0000279 Check(Section.getSize(DataSize));
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000280 Check(Section.getName(Name));
Richard Sandiford6fc2ad62013-05-03 14:15:35 +0000281 if (StubSize > 0) {
282 unsigned StubAlignment = getStubAlignment();
283 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
284 if (StubAlignment > EndAlignment)
285 StubBufSize += StubAlignment - EndAlignment;
286 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000287
Andrew Kaylor28a76552013-10-16 00:32:24 +0000288 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
289 // with zeroes added at the end. For MachO objects, this section has a
290 // slightly different name, so this won't have any effect for MachO objects.
291 if (Name == ".eh_frame")
292 PaddingSize = 4;
293
Preston Gurdc68dda82012-04-12 20:13:57 +0000294 unsigned Allocate;
295 unsigned SectionID = Sections.size();
296 uint8_t *Addr;
297 const char *pData = 0;
298
299 // Some sections, such as debug info, don't need to be loaded for execution.
300 // Leave those where they are.
301 if (IsRequired) {
Andrew Kaylor28a76552013-10-16 00:32:24 +0000302 Allocate = DataSize + PaddingSize + StubBufSize;
Preston Gurdc68dda82012-04-12 20:13:57 +0000303 Addr = IsCode
Filip Pizlo6eb43d22013-10-02 00:59:25 +0000304 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
305 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
306 IsReadOnly);
Preston Gurdc68dda82012-04-12 20:13:57 +0000307 if (!Addr)
308 report_fatal_error("Unable to allocate section memory!");
309
310 // Virtual sections have no data in the object image, so leave pData = 0
311 if (!IsVirtual)
312 pData = data.data();
313
314 // Zero-initialize or copy the data from the image
315 if (IsZeroInit || IsVirtual)
316 memset(Addr, 0, DataSize);
317 else
318 memcpy(Addr, pData, DataSize);
319
Andrew Kaylor28a76552013-10-16 00:32:24 +0000320 // Fill in any extra bytes we allocated for padding
321 if (PaddingSize != 0) {
322 memset(Addr + DataSize, 0, PaddingSize);
323 // Update the DataSize variable so that the stub offset is set correctly.
324 DataSize += PaddingSize;
325 }
326
Preston Gurdc68dda82012-04-12 20:13:57 +0000327 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000328 << " Name: " << Name
Preston Gurdc68dda82012-04-12 20:13:57 +0000329 << " obj addr: " << format("%p", pData)
330 << " new addr: " << format("%p", Addr)
331 << " DataSize: " << DataSize
332 << " StubBufSize: " << StubBufSize
333 << " Allocate: " << Allocate
334 << "\n");
Preston Gurd689ff9c2012-04-16 22:12:58 +0000335 Obj.updateSectionAddress(Section, (uint64_t)Addr);
Preston Gurdc68dda82012-04-12 20:13:57 +0000336 }
337 else {
338 // Even if we didn't load the section, we need to record an entry for it
Eli Bendersky5fe01982012-04-29 12:40:47 +0000339 // to handle later processing (and by 'handle' I mean don't do anything
340 // with these sections).
Preston Gurdc68dda82012-04-12 20:13:57 +0000341 Allocate = 0;
342 Addr = 0;
343 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000344 << " Name: " << Name
Preston Gurdc68dda82012-04-12 20:13:57 +0000345 << " obj addr: " << format("%p", data.data())
346 << " new addr: 0"
347 << " DataSize: " << DataSize
348 << " StubBufSize: " << StubBufSize
349 << " Allocate: " << Allocate
350 << "\n");
351 }
352
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +0000353 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000354 return SectionID;
355}
356
Preston Gurd689ff9c2012-04-16 22:12:58 +0000357unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
358 const SectionRef &Section,
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000359 bool IsCode,
360 ObjSectionToIDMap &LocalSections) {
361
362 unsigned SectionID = 0;
363 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
364 if (i != LocalSections.end())
365 SectionID = i->second;
366 else {
Preston Gurd689ff9c2012-04-16 22:12:58 +0000367 SectionID = emitSection(Obj, Section, IsCode);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000368 LocalSections[Section] = SectionID;
369 }
370 return SectionID;
371}
372
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000373void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
374 unsigned SectionID) {
375 Relocations[SectionID].push_back(RE);
376}
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000377
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000378void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
379 StringRef SymbolName) {
380 // Relocation by symbol. If the symbol is found in the global symbol table,
381 // create an appropriate section relocation. Otherwise, add it to
382 // ExternalSymbolRelocations.
383 SymbolTableMap::const_iterator Loc =
384 GlobalSymbolTable.find(SymbolName);
385 if (Loc == GlobalSymbolTable.end()) {
386 ExternalSymbolRelocations[SymbolName].push_back(RE);
Eli Bendersky37bc5a22012-04-30 12:15:58 +0000387 } else {
Eli Benderskyc201e6e2012-05-01 10:41:12 +0000388 // Copy the RE since we want to modify its addend.
389 RelocationEntry RECopy = RE;
390 RECopy.Addend += Loc->second.second;
391 Relocations[Loc->second.first].push_back(RECopy);
Eli Bendersky37bc5a22012-04-30 12:15:58 +0000392 }
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000393}
394
395uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
Tim Northover4a9b6b72013-05-04 20:14:09 +0000396 if (Arch == Triple::aarch64) {
397 // This stub has to be able to access the full address space,
398 // since symbol lookup won't necessarily find a handy, in-range,
399 // PLT stub for functions which could be anywhere.
400 uint32_t *StubAddr = (uint32_t*)Addr;
401
402 // Stub can use ip0 (== x16) to calculate address
403 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
404 StubAddr++;
405 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
406 StubAddr++;
407 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
408 StubAddr++;
409 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
410 StubAddr++;
411 *StubAddr = 0xd61f0200; // br ip0
412
413 return Addr;
414 } else if (Arch == Triple::arm) {
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000415 // TODO: There is only ARM far stub now. We should add the Thumb stub,
416 // and stubs for branches Thumb - ARM and ARM - Thumb.
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000417 uint32_t *StubAddr = (uint32_t*)Addr;
418 *StubAddr = 0xe51ff004; // ldr pc,<label>
419 return (uint8_t*)++StubAddr;
NAKAMURA Takumi4af1ca52012-12-04 00:08:14 +0000420 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000421 uint32_t *StubAddr = (uint32_t*)Addr;
422 // 0: 3c190000 lui t9,%hi(addr).
423 // 4: 27390000 addiu t9,t9,%lo(addr).
424 // 8: 03200008 jr t9.
425 // c: 00000000 nop.
426 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
427 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
428
429 *StubAddr = LuiT9Instr;
430 StubAddr++;
431 *StubAddr = AdduiT9Instr;
432 StubAddr++;
433 *StubAddr = JrT9Instr;
434 StubAddr++;
435 *StubAddr = NopInstr;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000436 return Addr;
Bill Schmidtf38cc382013-07-26 01:35:43 +0000437 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000438 // PowerPC64 stub: the address points to a function descriptor
439 // instead of the function itself. Load the function address
440 // on r11 and sets it to control register. Also loads the function
441 // TOC in r2 and environment pointer to r11.
442 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
443 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
444 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
445 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
446 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
447 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
448 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
449 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
450 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
451 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
452 writeInt32BE(Addr+40, 0x4E800420); // bctr
Andrew Kaylor5fc8c7c2012-11-01 19:49:21 +0000453
Adhemerval Zanella6e8946c2012-10-25 13:13:48 +0000454 return Addr;
Richard Sandiford6fc2ad62013-05-03 14:15:35 +0000455 } else if (Arch == Triple::systemz) {
456 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
457 writeInt16BE(Addr+2, 0x0000);
458 writeInt16BE(Addr+4, 0x0004);
459 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
460 // 8-byte address stored at Addr + 8
461 return Addr;
Andrew Kaylorff9fa052013-08-19 23:27:43 +0000462 } else if (Arch == Triple::x86_64) {
463 *Addr = 0xFF; // jmp
464 *(Addr+1) = 0x25; // rip
465 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
Akira Hatanakab889e0c2012-08-17 21:28:04 +0000466 }
467 return Addr;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000468}
469
470// Assign an address to a symbol name and resolve all the relocations
471// associated with it.
472void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
473 uint64_t Addr) {
474 // The address to use for relocation resolution is not
475 // the address of the local section buffer. We must be doing
Andrew Kaylor28989882012-11-05 20:57:16 +0000476 // a remote execution environment of some sort. Relocations can't
477 // be applied until all the sections have been moved. The client must
478 // trigger this with a call to MCJIT::finalize() or
479 // RuntimeDyld::resolveRelocations().
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000480 //
481 // Addr is a uint64_t because we can't assume the pointer width
482 // of the target is the same as that of the host. Just use a generic
483 // "big enough" type.
484 Sections[SectionID].LoadAddress = Addr;
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000485}
486
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000487void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
488 uint64_t Value) {
489 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola87b50172013-04-29 17:24:34 +0000490 const RelocationEntry &RE = Relocs[i];
491 // Ignore relocations for sections that were not loaded
492 if (Sections[RE.SectionID].Address == 0)
493 continue;
494 resolveRelocation(RE, Value);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000495 }
496}
497
Eli Bendersky37bc5a22012-04-30 12:15:58 +0000498void RuntimeDyldImpl::resolveExternalSymbols() {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000499 while(!ExternalSymbolRelocations.empty()) {
500 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
501
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000502 StringRef Name = i->first();
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000503 if (Name.size() == 0) {
504 // This is an absolute symbol, use an address of zero.
505 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
Andrew Kaylor559d4092013-11-11 19:55:10 +0000506 RelocationList &Relocs = i->second;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000507 resolveRelocationList(Relocs, 0);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000508 } else {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000509 uint64_t Addr = 0;
510 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
511 if (Loc == GlobalSymbolTable.end()) {
512 // This is an external symbol, try to get its address from
513 // MemoryManager.
514 Addr = MemMgr->getSymbolAddress(Name.data());
Andrew Kaylor559d4092013-11-11 19:55:10 +0000515 // The call to getSymbolAddress may have caused additional modules to
516 // be loaded, which may have added new entries to the
517 // ExternalSymbolRelocations map. Consquently, we need to update our
518 // iterator. This is also why retrieval of the relocation list
519 // associated with this symbol is deferred until below this point.
520 // New entries may have been added to the relocation list.
521 i = ExternalSymbolRelocations.find(Name);
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000522 } else {
523 // We found the symbol in our global table. It was probably in a
524 // Module that we loaded previously.
Yaron Keren4805bf52013-10-19 09:04:26 +0000525 SymbolLoc SymLoc = Loc->second;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000526 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
527 }
528
529 // FIXME: Implement error handling that doesn't kill the host program!
530 if (!Addr)
531 report_fatal_error("Program used external function '" + Name +
532 "' which could not be resolved!");
533
534 updateGOTEntries(Name, Addr);
535 DEBUG(dbgs() << "Resolving relocations Name: " << Name
536 << "\t" << format("0x%lx", Addr)
537 << "\n");
Andrew Kaylor559d4092013-11-11 19:55:10 +0000538 // This list may have been updated when we called getSymbolAddress, so
539 // don't change this code to get the list earlier.
540 RelocationList &Relocs = i->second;
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000541 resolveRelocationList(Relocs, Addr);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000542 }
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000543
Andrew Kaylor559d4092013-11-11 19:55:10 +0000544 ExternalSymbolRelocations.erase(i);
Danil Malyshev0e4fa5f2012-03-30 16:45:19 +0000545 }
546}
547
548
Jim Grosbach6e563312011-03-21 22:15:52 +0000549//===----------------------------------------------------------------------===//
550// RuntimeDyld class implementation
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000551RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
Andrew Kaylor53608a32012-11-15 23:50:01 +0000552 // FIXME: There's a potential issue lurking here if a single instance of
553 // RuntimeDyld is used to load multiple objects. The current implementation
554 // associates a single memory manager with a RuntimeDyld instance. Even
555 // though the public class spawns a new 'impl' instance for each load,
556 // they share a single memory manager. This can become a problem when page
557 // permissions are applied.
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000558 Dyld = 0;
559 MM = mm;
Jim Grosbach6e563312011-03-21 22:15:52 +0000560}
561
562RuntimeDyld::~RuntimeDyld() {
563 delete Dyld;
564}
565
Andrew Kaylor3f23cef2012-10-02 21:18:39 +0000566ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000567 if (!Dyld) {
Rafael Espindola3ecfcc22013-06-11 18:01:14 +0000568 sys::fs::file_magic Type =
569 sys::fs::identify_magic(InputBuffer->getBuffer());
570 switch (Type) {
571 case sys::fs::file_magic::elf_relocatable:
572 case sys::fs::file_magic::elf_executable:
573 case sys::fs::file_magic::elf_shared_object:
574 case sys::fs::file_magic::elf_core:
575 Dyld = new RuntimeDyldELF(MM);
576 break;
577 case sys::fs::file_magic::macho_object:
578 case sys::fs::file_magic::macho_executable:
579 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
580 case sys::fs::file_magic::macho_core:
581 case sys::fs::file_magic::macho_preload_executable:
582 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
583 case sys::fs::file_magic::macho_dynamic_linker:
584 case sys::fs::file_magic::macho_bundle:
585 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
586 case sys::fs::file_magic::macho_dsym_companion:
587 Dyld = new RuntimeDyldMachO(MM);
588 break;
589 case sys::fs::file_magic::unknown:
590 case sys::fs::file_magic::bitcode:
591 case sys::fs::file_magic::archive:
592 case sys::fs::file_magic::coff_object:
Rui Ueyama8a631b22013-11-15 21:22:02 +0000593 case sys::fs::file_magic::coff_import_library:
Rafael Espindola3ecfcc22013-06-11 18:01:14 +0000594 case sys::fs::file_magic::pecoff_executable:
Alexey Samsonov9c22f872013-06-18 15:03:28 +0000595 case sys::fs::file_magic::macho_universal_binary:
Rui Ueyamab32b0372013-10-15 22:45:38 +0000596 case sys::fs::file_magic::windows_resource:
Rafael Espindola3ecfcc22013-06-11 18:01:14 +0000597 report_fatal_error("Incompatible object format!");
Eli Benderskya66a1852012-01-16 08:56:09 +0000598 }
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000599 } else {
Eli Benderskya66a1852012-01-16 08:56:09 +0000600 if (!Dyld->isCompatibleFormat(InputBuffer))
Danil Malyshevcf852dc2011-07-13 07:57:58 +0000601 report_fatal_error("Incompatible object format!");
602 }
603
Jim Grosbach6e563312011-03-21 22:15:52 +0000604 return Dyld->loadObject(InputBuffer);
605}
606
Jim Grosbachb0271052011-04-08 17:31:24 +0000607void *RuntimeDyld::getSymbolAddress(StringRef Name) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000608 if (!Dyld)
609 return NULL;
Jim Grosbach6e563312011-03-21 22:15:52 +0000610 return Dyld->getSymbolAddress(Name);
611}
612
Jim Grosbach35ed8422012-09-05 16:50:40 +0000613uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
Andrew Kaylor8e9ec012013-10-01 01:47:35 +0000614 if (!Dyld)
615 return 0;
Jim Grosbach35ed8422012-09-05 16:50:40 +0000616 return Dyld->getSymbolLoadAddress(Name);
617}
618
Jim Grosbachf8c1c842011-04-12 21:20:41 +0000619void RuntimeDyld::resolveRelocations() {
620 Dyld->resolveRelocations();
621}
622
Jim Grosbach61425c02012-01-16 22:26:39 +0000623void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
624 uint64_t Addr) {
625 Dyld->reassignSectionAddress(SectionID, Addr);
Jim Grosbachf8c1c842011-04-12 21:20:41 +0000626}
627
Jim Grosbache940c1b2012-09-13 21:50:06 +0000628void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
Jim Grosbach020f4e82012-01-16 23:50:55 +0000629 uint64_t TargetAddress) {
630 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
631}
632
Jim Grosbach91dde152011-03-22 18:22:27 +0000633StringRef RuntimeDyld::getErrorString() {
Jim Grosbachb3eecaf2011-03-22 18:19:42 +0000634 return Dyld->getErrorString();
635}
636
Andrew Kaylor528f6d72013-10-11 21:25:48 +0000637void RuntimeDyld::registerEHFrames() {
Andrew Kaylor43507d02013-10-16 00:14:21 +0000638 if (Dyld)
639 Dyld->registerEHFrames();
640}
641
642void RuntimeDyld::deregisterEHFrames() {
643 if (Dyld)
644 Dyld->deregisterEHFrames();
Rafael Espindolaa2e40fb2013-05-05 20:43:10 +0000645}
646
Jim Grosbach6e563312011-03-21 22:15:52 +0000647} // end namespace llvm