blob: f99d7d0b279de724da79545babb14486b218e4d3 [file] [log] [blame]
Jim Grosbach06594e12012-01-16 23:50:58 +00001//===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
Jim Grosbachf016b0a2011-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 Grosbach6a85a052011-03-23 19:52:00 +000014#define DEBUG_TYPE "dyld"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ExecutionEngine/RuntimeDyld.h"
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000016#include "JITRegistrar.h"
Andrew Kayloradc70562012-10-02 21:18:39 +000017#include "ObjectImageCommon.h"
Eli Bendersky058d6472012-01-22 07:05:02 +000018#include "RuntimeDyldELF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "RuntimeDyldImpl.h"
Eli Bendersky058d6472012-01-22 07:05:02 +000020#include "RuntimeDyldMachO.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000021#include "llvm/Object/ELF.h"
Rafael Espindola8de86072013-06-11 18:01:14 +000022#include "llvm/Support/FileSystem.h"
Tim Northover94bc73d2012-10-29 10:47:04 +000023#include "llvm/Support/MathExtras.h"
Andrew Kaylor4fba0492013-10-21 17:42:06 +000024#include "llvm/Support/MutexGuard.h"
Eli Bendersky058d6472012-01-22 07:05:02 +000025
Jim Grosbachf016b0a2011-03-21 22:15:52 +000026using namespace llvm;
27using namespace llvm::object;
28
Chandler Carruth086f7082011-04-05 23:54:31 +000029// Empty out-of-line virtual destructor as the key function.
Danil Malyshev72510f22011-07-13 07:57:58 +000030RuntimeDyldImpl::~RuntimeDyldImpl() {}
Chandler Carruth086f7082011-04-05 23:54:31 +000031
Juergen Ributzkad12ccbd2013-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 Grosbachf016b0a2011-03-21 22:15:52 +000037namespace llvm {
Jim Grosbachf016b0a2011-03-21 22:15:52 +000038
Andrew Kaylor7bb13442013-10-11 21:25:48 +000039void RuntimeDyldImpl::registerEHFrames() {
Rafael Espindolafa5942b2013-05-05 20:43:10 +000040}
41
Andrew Kaylorc442a762013-10-16 00:14:21 +000042void RuntimeDyldImpl::deregisterEHFrames() {
43}
44
Jim Grosbach733d3052011-04-12 21:20:41 +000045// Resolve the relocations for all symbols we currently know about.
46void RuntimeDyldImpl::resolveRelocations() {
Andrew Kaylor4fba0492013-10-21 17:42:06 +000047 MutexGuard locked(lock);
48
Preston Gurd2138ef62012-04-12 20:13:57 +000049 // First, resolve relocations associated with external symbols.
Eli Benderskyb92e1cf2012-04-30 12:15:58 +000050 resolveExternalSymbols();
Danil Malyshev70d22cc2012-03-30 16:45:19 +000051
Jim Grosbacheff0a402012-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 Kaylor5f3a9982013-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 Kaylora714efc2012-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 Kaylorea395922013-10-01 01:47:35 +000063 Relocations.erase(i);
Jim Grosbacheff0a402012-01-16 22:26:39 +000064 }
Jim Grosbach733d3052011-04-12 21:20:41 +000065}
66
Jim Grosbach6d613972012-09-13 21:50:06 +000067void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
Jim Grosbach0ddb3a42012-01-16 23:50:55 +000068 uint64_t TargetAddress) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +000069 MutexGuard locked(lock);
Danil Malyshev70d22cc2012-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 Grosbach0ddb3a42012-01-16 23:50:55 +000077}
78
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +000079// Subclasses can implement this method to create specialized image instances.
Sylvestre Ledru35521e22012-07-23 08:51:15 +000080// The caller owns the pointer that is returned.
Andrew Kayloradc70562012-10-02 21:18:39 +000081ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
82 return new ObjectImageCommon(InputBuffer);
Preston Gurdcc31af92012-04-16 22:12:58 +000083}
84
Lang Hames173c69f2014-01-08 04:09:09 +000085ObjectImage *RuntimeDyldImpl::createObjectImageFromFile(ObjectFile *InputObject) {
86 return new ObjectImageCommon(InputObject);
87}
88
89ObjectImage *RuntimeDyldImpl::loadObject(ObjectFile *InputObject) {
90 return loadObject(createObjectImageFromFile(InputObject));
91}
92
Andrew Kayloradc70562012-10-02 21:18:39 +000093ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
Lang Hames173c69f2014-01-08 04:09:09 +000094 return loadObject(createObjectImage(InputBuffer));
95}
96
97ObjectImage *RuntimeDyldImpl::loadObject(ObjectImage *InputObject) {
Andrew Kaylor4fba0492013-10-21 17:42:06 +000098 MutexGuard locked(lock);
99
Lang Hames173c69f2014-01-08 04:09:09 +0000100 OwningPtr<ObjectImage> obj(InputObject);
Preston Gurd2138ef62012-04-12 20:13:57 +0000101 if (!obj)
Lang Hames173c69f2014-01-08 04:09:09 +0000102 return NULL;
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000103
Andrew Kaylor33c5b1b2013-10-15 20:44:55 +0000104 // Save information about our target
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000105 Arch = (Triple::ArchType)obj->getArch();
Andrew Kaylor33c5b1b2013-10-15 20:44:55 +0000106 IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000107
Eli Benderskyfc079082012-05-01 06:58:59 +0000108 // Symbols found in this object
109 StringMap<SymbolLoc> LocalSymbols;
110 // Used sections from the object file
111 ObjSectionToIDMap LocalSections;
112
Tim Northover94bc73d2012-10-29 10:47:04 +0000113 // Common symbols requiring allocation, with their sizes and alignments
Eli Benderskyfc079082012-05-01 06:58:59 +0000114 CommonSymbolMap CommonSymbols;
Tim Northover94bc73d2012-10-29 10:47:04 +0000115 // Maximum required total memory to allocate all common symbols
Eli Benderskyfc079082012-05-01 06:58:59 +0000116 uint64_t CommonSize = 0;
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000117
118 error_code err;
119 // Parse symbols
120 DEBUG(dbgs() << "Parse symbols:\n");
121 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
122 i != e; i.increment(err)) {
123 Check(err);
124 object::SymbolRef::Type SymType;
125 StringRef Name;
126 Check(i->getType(SymType));
127 Check(i->getName(Name));
128
Preston Gurd2138ef62012-04-12 20:13:57 +0000129 uint32_t flags;
130 Check(i->getFlags(flags));
131
132 bool isCommon = flags & SymbolRef::SF_Common;
133 if (isCommon) {
134 // Add the common symbols to a list. We'll allocate them all below.
Rafael Espindolae4dd2e02013-04-29 22:24:22 +0000135 uint32_t Align;
136 Check(i->getAlignment(Align));
Preston Gurd2138ef62012-04-12 20:13:57 +0000137 uint64_t Size = 0;
138 Check(i->getSize(Size));
Tim Northover94bc73d2012-10-29 10:47:04 +0000139 CommonSize += Size + Align;
140 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
Preston Gurd2138ef62012-04-12 20:13:57 +0000141 } else {
142 if (SymType == object::SymbolRef::ST_Function ||
Akira Hatanaka111174b2012-08-17 21:28:04 +0000143 SymType == object::SymbolRef::ST_Data ||
144 SymType == object::SymbolRef::ST_Unknown) {
Preston Gurd2138ef62012-04-12 20:13:57 +0000145 uint64_t FileOffset;
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000146 StringRef SectionData;
Tim Northoverd05e6b52012-12-17 17:59:35 +0000147 bool IsCode;
Preston Gurd2138ef62012-04-12 20:13:57 +0000148 section_iterator si = obj->end_sections();
149 Check(i->getFileOffset(FileOffset));
150 Check(i->getSection(si));
151 if (si == obj->end_sections()) continue;
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000152 Check(si->getContents(SectionData));
Tim Northoverd05e6b52012-12-17 17:59:35 +0000153 Check(si->isText(IsCode));
Lang Hames173c69f2014-01-08 04:09:09 +0000154 const uint8_t* SymPtr = (const uint8_t*)InputObject->getData().data() +
Preston Gurd2138ef62012-04-12 20:13:57 +0000155 (uintptr_t)FileOffset;
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000156 uintptr_t SectOffset = (uintptr_t)(SymPtr -
157 (const uint8_t*)SectionData.begin());
Tim Northoverd05e6b52012-12-17 17:59:35 +0000158 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
Preston Gurd2138ef62012-04-12 20:13:57 +0000159 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
160 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
161 << " flags: " << flags
162 << " SID: " << SectionID
163 << " Offset: " << format("%p", SectOffset));
Amara Emersonc958bf32012-11-16 11:11:59 +0000164 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
Preston Gurd2138ef62012-04-12 20:13:57 +0000165 }
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000166 }
167 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
168 }
169
Preston Gurd2138ef62012-04-12 20:13:57 +0000170 // Allocate common symbols
171 if (CommonSize != 0)
Preston Gurdcc31af92012-04-16 22:12:58 +0000172 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
Preston Gurd2138ef62012-04-12 20:13:57 +0000173
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000174 // Parse and process relocations
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000175 DEBUG(dbgs() << "Parse relocations:\n");
176 for (section_iterator si = obj->begin_sections(),
177 se = obj->end_sections(); si != se; si.increment(err)) {
178 Check(err);
179 bool isFirstRelocation = true;
180 unsigned SectionID = 0;
181 StubMap Stubs;
Rafael Espindola4f60a382013-05-30 03:05:14 +0000182 section_iterator RelocatedSection = si->getRelocatedSection();
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000183
184 for (relocation_iterator i = si->begin_relocations(),
185 e = si->end_relocations(); i != e; i.increment(err)) {
186 Check(err);
187
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000188 // If it's the first relocation in this section, find its SectionID
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000189 if (isFirstRelocation) {
Rafael Espindola4f60a382013-05-30 03:05:14 +0000190 SectionID =
191 findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000192 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
193 isFirstRelocation = false;
194 }
195
Rafael Espindola37008942013-04-29 19:03:21 +0000196 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
NAKAMURA Takumi87e08802013-12-07 11:21:42 +0000197 Stubs);
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000198 }
199 }
Preston Gurdcc31af92012-04-16 22:12:58 +0000200
Andrew Kaylor4612fed2013-08-19 23:27:43 +0000201 // Give the subclasses a chance to tie-up any loose ends.
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000202 finalizeLoad(LocalSections);
Andrew Kaylor4612fed2013-08-19 23:27:43 +0000203
Andrew Kayloradc70562012-10-02 21:18:39 +0000204 return obj.take();
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000205}
206
Eli Bendersky667b8792012-05-01 10:41:12 +0000207void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
208 const CommonSymbolMap &CommonSymbols,
209 uint64_t TotalSize,
210 SymbolTableMap &SymbolTable) {
Preston Gurd2138ef62012-04-12 20:13:57 +0000211 // Allocate memory for the section
212 unsigned SectionID = Sections.size();
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000213 uint8_t *Addr = MemMgr->allocateDataSection(
214 TotalSize, sizeof(void*), SectionID, StringRef(), false);
Preston Gurd2138ef62012-04-12 20:13:57 +0000215 if (!Addr)
216 report_fatal_error("Unable to allocate memory for common symbols!");
217 uint64_t Offset = 0;
Rafael Espindolafa5942b2013-05-05 20:43:10 +0000218 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
Preston Gurd2138ef62012-04-12 20:13:57 +0000219 memset(Addr, 0, TotalSize);
220
221 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
222 << " new addr: " << format("%p", Addr)
223 << " DataSize: " << TotalSize
224 << "\n");
225
226 // Assign the address of each symbol
Eli Bendersky667b8792012-05-01 10:41:12 +0000227 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
228 itEnd = CommonSymbols.end(); it != itEnd; it++) {
Tim Northover94bc73d2012-10-29 10:47:04 +0000229 uint64_t Size = it->second.first;
230 uint64_t Align = it->second.second;
Preston Gurd2138ef62012-04-12 20:13:57 +0000231 StringRef Name;
232 it->first.getName(Name);
Tim Northover94bc73d2012-10-29 10:47:04 +0000233 if (Align) {
234 // This symbol has an alignment requirement.
235 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
236 Addr += AlignOffset;
237 Offset += AlignOffset;
238 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
Andrew Kaylor0eece8d2012-11-01 19:49:21 +0000239 format("%p\n", Addr));
Tim Northover94bc73d2012-10-29 10:47:04 +0000240 }
Preston Gurdcc31af92012-04-16 22:12:58 +0000241 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
Eli Bendersky667b8792012-05-01 10:41:12 +0000242 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
Preston Gurd2138ef62012-04-12 20:13:57 +0000243 Offset += Size;
244 Addr += Size;
245 }
Preston Gurd2138ef62012-04-12 20:13:57 +0000246}
247
Preston Gurdcc31af92012-04-16 22:12:58 +0000248unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
249 const SectionRef &Section,
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000250 bool IsCode) {
251
252 unsigned StubBufSize = 0,
253 StubSize = getMaxStubSize();
254 error_code err;
Rafael Espindola4f60a382013-05-30 03:05:14 +0000255 const ObjectFile *ObjFile = Obj.getObjectFile();
256 // FIXME: this is an inefficient way to handle this. We should computed the
257 // necessary section allocation size in loadObject by walking all the sections
258 // once.
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000259 if (StubSize > 0) {
Rafael Espindola4f60a382013-05-30 03:05:14 +0000260 for (section_iterator SI = ObjFile->begin_sections(),
261 SE = ObjFile->end_sections();
262 SI != SE; SI.increment(err), Check(err)) {
263 section_iterator RelSecI = SI->getRelocatedSection();
264 if (!(RelSecI == Section))
265 continue;
266
267 for (relocation_iterator I = SI->begin_relocations(),
268 E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
269 StubBufSize += StubSize;
270 }
271 }
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000272 }
Rafael Espindola4f60a382013-05-30 03:05:14 +0000273
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000274 StringRef data;
275 uint64_t Alignment64;
276 Check(Section.getContents(data));
277 Check(Section.getAlignment(Alignment64));
278
279 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
Preston Gurd2138ef62012-04-12 20:13:57 +0000280 bool IsRequired;
281 bool IsVirtual;
282 bool IsZeroInit;
Andrew Kaylora342cb92012-11-15 23:50:01 +0000283 bool IsReadOnly;
Preston Gurd2138ef62012-04-12 20:13:57 +0000284 uint64_t DataSize;
Andrew Kaylor877b9312013-10-16 00:32:24 +0000285 unsigned PaddingSize = 0;
Adhemerval Zanella5fc11b32012-10-25 13:13:48 +0000286 StringRef Name;
Preston Gurd2138ef62012-04-12 20:13:57 +0000287 Check(Section.isRequiredForExecution(IsRequired));
288 Check(Section.isVirtual(IsVirtual));
289 Check(Section.isZeroInit(IsZeroInit));
Andrew Kaylora342cb92012-11-15 23:50:01 +0000290 Check(Section.isReadOnlyData(IsReadOnly));
Preston Gurd2138ef62012-04-12 20:13:57 +0000291 Check(Section.getSize(DataSize));
Adhemerval Zanella5fc11b32012-10-25 13:13:48 +0000292 Check(Section.getName(Name));
Richard Sandifordca044082013-05-03 14:15:35 +0000293 if (StubSize > 0) {
294 unsigned StubAlignment = getStubAlignment();
295 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
296 if (StubAlignment > EndAlignment)
297 StubBufSize += StubAlignment - EndAlignment;
298 }
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000299
Andrew Kaylor877b9312013-10-16 00:32:24 +0000300 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
301 // with zeroes added at the end. For MachO objects, this section has a
302 // slightly different name, so this won't have any effect for MachO objects.
303 if (Name == ".eh_frame")
304 PaddingSize = 4;
305
Preston Gurd2138ef62012-04-12 20:13:57 +0000306 unsigned Allocate;
307 unsigned SectionID = Sections.size();
308 uint8_t *Addr;
309 const char *pData = 0;
310
311 // Some sections, such as debug info, don't need to be loaded for execution.
312 // Leave those where they are.
313 if (IsRequired) {
Andrew Kaylor877b9312013-10-16 00:32:24 +0000314 Allocate = DataSize + PaddingSize + StubBufSize;
Preston Gurd2138ef62012-04-12 20:13:57 +0000315 Addr = IsCode
Filip Pizlo7aa695e02013-10-02 00:59:25 +0000316 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
317 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
318 IsReadOnly);
Preston Gurd2138ef62012-04-12 20:13:57 +0000319 if (!Addr)
320 report_fatal_error("Unable to allocate section memory!");
321
322 // Virtual sections have no data in the object image, so leave pData = 0
323 if (!IsVirtual)
324 pData = data.data();
325
326 // Zero-initialize or copy the data from the image
327 if (IsZeroInit || IsVirtual)
328 memset(Addr, 0, DataSize);
329 else
330 memcpy(Addr, pData, DataSize);
331
Andrew Kaylor877b9312013-10-16 00:32:24 +0000332 // Fill in any extra bytes we allocated for padding
333 if (PaddingSize != 0) {
334 memset(Addr + DataSize, 0, PaddingSize);
335 // Update the DataSize variable so that the stub offset is set correctly.
336 DataSize += PaddingSize;
337 }
338
Preston Gurd2138ef62012-04-12 20:13:57 +0000339 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
Adhemerval Zanella5fc11b32012-10-25 13:13:48 +0000340 << " Name: " << Name
Preston Gurd2138ef62012-04-12 20:13:57 +0000341 << " obj addr: " << format("%p", pData)
342 << " new addr: " << format("%p", Addr)
343 << " DataSize: " << DataSize
344 << " StubBufSize: " << StubBufSize
345 << " Allocate: " << Allocate
346 << "\n");
Preston Gurdcc31af92012-04-16 22:12:58 +0000347 Obj.updateSectionAddress(Section, (uint64_t)Addr);
Preston Gurd2138ef62012-04-12 20:13:57 +0000348 }
349 else {
350 // Even if we didn't load the section, we need to record an entry for it
Eli Bendersky0e2ac5b2012-04-29 12:40:47 +0000351 // to handle later processing (and by 'handle' I mean don't do anything
352 // with these sections).
Preston Gurd2138ef62012-04-12 20:13:57 +0000353 Allocate = 0;
354 Addr = 0;
355 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
Adhemerval Zanella5fc11b32012-10-25 13:13:48 +0000356 << " Name: " << Name
Preston Gurd2138ef62012-04-12 20:13:57 +0000357 << " obj addr: " << format("%p", data.data())
358 << " new addr: 0"
359 << " DataSize: " << DataSize
360 << " StubBufSize: " << StubBufSize
361 << " Allocate: " << Allocate
362 << "\n");
363 }
364
Rafael Espindolafa5942b2013-05-05 20:43:10 +0000365 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000366 return SectionID;
367}
368
Preston Gurdcc31af92012-04-16 22:12:58 +0000369unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
370 const SectionRef &Section,
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000371 bool IsCode,
372 ObjSectionToIDMap &LocalSections) {
373
374 unsigned SectionID = 0;
375 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
376 if (i != LocalSections.end())
377 SectionID = i->second;
378 else {
Preston Gurdcc31af92012-04-16 22:12:58 +0000379 SectionID = emitSection(Obj, Section, IsCode);
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000380 LocalSections[Section] = SectionID;
381 }
382 return SectionID;
383}
384
Eli Bendersky667b8792012-05-01 10:41:12 +0000385void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
386 unsigned SectionID) {
387 Relocations[SectionID].push_back(RE);
388}
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000389
Eli Bendersky667b8792012-05-01 10:41:12 +0000390void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
391 StringRef SymbolName) {
392 // Relocation by symbol. If the symbol is found in the global symbol table,
393 // create an appropriate section relocation. Otherwise, add it to
394 // ExternalSymbolRelocations.
395 SymbolTableMap::const_iterator Loc =
396 GlobalSymbolTable.find(SymbolName);
397 if (Loc == GlobalSymbolTable.end()) {
398 ExternalSymbolRelocations[SymbolName].push_back(RE);
Eli Benderskyb92e1cf2012-04-30 12:15:58 +0000399 } else {
Eli Bendersky667b8792012-05-01 10:41:12 +0000400 // Copy the RE since we want to modify its addend.
401 RelocationEntry RECopy = RE;
402 RECopy.Addend += Loc->second.second;
403 Relocations[Loc->second.first].push_back(RECopy);
Eli Benderskyb92e1cf2012-04-30 12:15:58 +0000404 }
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000405}
406
407uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
Tim Northover37cde972013-05-04 20:14:09 +0000408 if (Arch == Triple::aarch64) {
409 // This stub has to be able to access the full address space,
410 // since symbol lookup won't necessarily find a handy, in-range,
411 // PLT stub for functions which could be anywhere.
412 uint32_t *StubAddr = (uint32_t*)Addr;
413
414 // Stub can use ip0 (== x16) to calculate address
415 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
416 StubAddr++;
417 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
418 StubAddr++;
419 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
420 StubAddr++;
421 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
422 StubAddr++;
423 *StubAddr = 0xd61f0200; // br ip0
424
425 return Addr;
426 } else if (Arch == Triple::arm) {
Akira Hatanaka111174b2012-08-17 21:28:04 +0000427 // TODO: There is only ARM far stub now. We should add the Thumb stub,
428 // and stubs for branches Thumb - ARM and ARM - Thumb.
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000429 uint32_t *StubAddr = (uint32_t*)Addr;
430 *StubAddr = 0xe51ff004; // ldr pc,<label>
431 return (uint8_t*)++StubAddr;
NAKAMURA Takumif97efd92012-12-04 00:08:14 +0000432 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
Akira Hatanaka111174b2012-08-17 21:28:04 +0000433 uint32_t *StubAddr = (uint32_t*)Addr;
434 // 0: 3c190000 lui t9,%hi(addr).
435 // 4: 27390000 addiu t9,t9,%lo(addr).
436 // 8: 03200008 jr t9.
437 // c: 00000000 nop.
438 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
439 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
440
441 *StubAddr = LuiT9Instr;
442 StubAddr++;
443 *StubAddr = AdduiT9Instr;
444 StubAddr++;
445 *StubAddr = JrT9Instr;
446 StubAddr++;
447 *StubAddr = NopInstr;
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000448 return Addr;
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000449 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
Adhemerval Zanella5fc11b32012-10-25 13:13:48 +0000450 // PowerPC64 stub: the address points to a function descriptor
451 // instead of the function itself. Load the function address
452 // on r11 and sets it to control register. Also loads the function
453 // TOC in r2 and environment pointer to r11.
454 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
455 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
456 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
457 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
458 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
459 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
460 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
461 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
462 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
463 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
464 writeInt32BE(Addr+40, 0x4E800420); // bctr
Andrew Kaylor0eece8d2012-11-01 19:49:21 +0000465
Adhemerval Zanella5fc11b32012-10-25 13:13:48 +0000466 return Addr;
Richard Sandifordca044082013-05-03 14:15:35 +0000467 } else if (Arch == Triple::systemz) {
468 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
469 writeInt16BE(Addr+2, 0x0000);
470 writeInt16BE(Addr+4, 0x0004);
471 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
472 // 8-byte address stored at Addr + 8
473 return Addr;
Andrew Kaylor4612fed2013-08-19 23:27:43 +0000474 } else if (Arch == Triple::x86_64) {
475 *Addr = 0xFF; // jmp
476 *(Addr+1) = 0x25; // rip
477 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
Akira Hatanaka111174b2012-08-17 21:28:04 +0000478 }
479 return Addr;
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000480}
481
482// Assign an address to a symbol name and resolve all the relocations
483// associated with it.
484void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
485 uint64_t Addr) {
486 // The address to use for relocation resolution is not
487 // the address of the local section buffer. We must be doing
Andrew Kaylora714efc2012-11-05 20:57:16 +0000488 // a remote execution environment of some sort. Relocations can't
489 // be applied until all the sections have been moved. The client must
490 // trigger this with a call to MCJIT::finalize() or
491 // RuntimeDyld::resolveRelocations().
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000492 //
493 // Addr is a uint64_t because we can't assume the pointer width
494 // of the target is the same as that of the host. Just use a generic
495 // "big enough" type.
496 Sections[SectionID].LoadAddress = Addr;
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000497}
498
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000499void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
500 uint64_t Value) {
501 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindolaf1f1c622013-04-29 17:24:34 +0000502 const RelocationEntry &RE = Relocs[i];
503 // Ignore relocations for sections that were not loaded
504 if (Sections[RE.SectionID].Address == 0)
505 continue;
506 resolveRelocation(RE, Value);
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000507 }
508}
509
Eli Benderskyb92e1cf2012-04-30 12:15:58 +0000510void RuntimeDyldImpl::resolveExternalSymbols() {
Andrew Kaylorea395922013-10-01 01:47:35 +0000511 while(!ExternalSymbolRelocations.empty()) {
512 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
513
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000514 StringRef Name = i->first();
Andrew Kaylorea395922013-10-01 01:47:35 +0000515 if (Name.size() == 0) {
516 // This is an absolute symbol, use an address of zero.
517 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
Andrew Kaylorcfb4a992013-11-11 19:55:10 +0000518 RelocationList &Relocs = i->second;
Andrew Kaylorea395922013-10-01 01:47:35 +0000519 resolveRelocationList(Relocs, 0);
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000520 } else {
Andrew Kaylorea395922013-10-01 01:47:35 +0000521 uint64_t Addr = 0;
522 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
523 if (Loc == GlobalSymbolTable.end()) {
524 // This is an external symbol, try to get its address from
525 // MemoryManager.
526 Addr = MemMgr->getSymbolAddress(Name.data());
Andrew Kaylorcfb4a992013-11-11 19:55:10 +0000527 // The call to getSymbolAddress may have caused additional modules to
528 // be loaded, which may have added new entries to the
529 // ExternalSymbolRelocations map. Consquently, we need to update our
530 // iterator. This is also why retrieval of the relocation list
531 // associated with this symbol is deferred until below this point.
532 // New entries may have been added to the relocation list.
533 i = ExternalSymbolRelocations.find(Name);
Andrew Kaylorea395922013-10-01 01:47:35 +0000534 } else {
535 // We found the symbol in our global table. It was probably in a
536 // Module that we loaded previously.
Yaron Kerenc9802882013-10-19 09:04:26 +0000537 SymbolLoc SymLoc = Loc->second;
Andrew Kaylorea395922013-10-01 01:47:35 +0000538 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
539 }
540
541 // FIXME: Implement error handling that doesn't kill the host program!
542 if (!Addr)
543 report_fatal_error("Program used external function '" + Name +
544 "' which could not be resolved!");
545
546 updateGOTEntries(Name, Addr);
547 DEBUG(dbgs() << "Resolving relocations Name: " << Name
548 << "\t" << format("0x%lx", Addr)
549 << "\n");
Andrew Kaylorcfb4a992013-11-11 19:55:10 +0000550 // This list may have been updated when we called getSymbolAddress, so
551 // don't change this code to get the list earlier.
552 RelocationList &Relocs = i->second;
Andrew Kaylorea395922013-10-01 01:47:35 +0000553 resolveRelocationList(Relocs, Addr);
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000554 }
Andrew Kaylorea395922013-10-01 01:47:35 +0000555
Andrew Kaylorcfb4a992013-11-11 19:55:10 +0000556 ExternalSymbolRelocations.erase(i);
Danil Malyshev70d22cc2012-03-30 16:45:19 +0000557 }
558}
559
560
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000561//===----------------------------------------------------------------------===//
562// RuntimeDyld class implementation
Danil Malyshev72510f22011-07-13 07:57:58 +0000563RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
Andrew Kaylora342cb92012-11-15 23:50:01 +0000564 // FIXME: There's a potential issue lurking here if a single instance of
565 // RuntimeDyld is used to load multiple objects. The current implementation
566 // associates a single memory manager with a RuntimeDyld instance. Even
567 // though the public class spawns a new 'impl' instance for each load,
568 // they share a single memory manager. This can become a problem when page
569 // permissions are applied.
Danil Malyshev72510f22011-07-13 07:57:58 +0000570 Dyld = 0;
571 MM = mm;
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000572}
573
574RuntimeDyld::~RuntimeDyld() {
575 delete Dyld;
576}
577
Lang Hames173c69f2014-01-08 04:09:09 +0000578ObjectImage *RuntimeDyld::loadObject(ObjectFile *InputObject) {
579 if (!Dyld) {
580 if (InputObject->isELF())
581 Dyld = new RuntimeDyldELF(MM);
582 else if (InputObject->isMachO())
583 Dyld = new RuntimeDyldMachO(MM);
584 else
585 report_fatal_error("Incompatible object format!");
586 } else {
587 if (!Dyld->isCompatibleFile(InputObject))
588 report_fatal_error("Incompatible object format!");
589 }
590
591 return Dyld->loadObject(InputObject);
592}
593
Andrew Kayloradc70562012-10-02 21:18:39 +0000594ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
Danil Malyshev72510f22011-07-13 07:57:58 +0000595 if (!Dyld) {
Rafael Espindola8de86072013-06-11 18:01:14 +0000596 sys::fs::file_magic Type =
597 sys::fs::identify_magic(InputBuffer->getBuffer());
598 switch (Type) {
599 case sys::fs::file_magic::elf_relocatable:
600 case sys::fs::file_magic::elf_executable:
601 case sys::fs::file_magic::elf_shared_object:
602 case sys::fs::file_magic::elf_core:
603 Dyld = new RuntimeDyldELF(MM);
604 break;
605 case sys::fs::file_magic::macho_object:
606 case sys::fs::file_magic::macho_executable:
607 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
608 case sys::fs::file_magic::macho_core:
609 case sys::fs::file_magic::macho_preload_executable:
610 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
611 case sys::fs::file_magic::macho_dynamic_linker:
612 case sys::fs::file_magic::macho_bundle:
613 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
614 case sys::fs::file_magic::macho_dsym_companion:
615 Dyld = new RuntimeDyldMachO(MM);
616 break;
617 case sys::fs::file_magic::unknown:
618 case sys::fs::file_magic::bitcode:
619 case sys::fs::file_magic::archive:
620 case sys::fs::file_magic::coff_object:
Rui Ueyamae448f9e2013-11-15 21:22:02 +0000621 case sys::fs::file_magic::coff_import_library:
Rafael Espindola8de86072013-06-11 18:01:14 +0000622 case sys::fs::file_magic::pecoff_executable:
Alexey Samsonove6388e62013-06-18 15:03:28 +0000623 case sys::fs::file_magic::macho_universal_binary:
Rui Ueyamafc149a62013-10-15 22:45:38 +0000624 case sys::fs::file_magic::windows_resource:
Rafael Espindola8de86072013-06-11 18:01:14 +0000625 report_fatal_error("Incompatible object format!");
Eli Bendersky4c647582012-01-16 08:56:09 +0000626 }
Danil Malyshev72510f22011-07-13 07:57:58 +0000627 } else {
Eli Bendersky4c647582012-01-16 08:56:09 +0000628 if (!Dyld->isCompatibleFormat(InputBuffer))
Danil Malyshev72510f22011-07-13 07:57:58 +0000629 report_fatal_error("Incompatible object format!");
630 }
631
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000632 return Dyld->loadObject(InputBuffer);
633}
634
Jim Grosbach18b81c52011-04-08 17:31:24 +0000635void *RuntimeDyld::getSymbolAddress(StringRef Name) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000636 if (!Dyld)
637 return NULL;
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000638 return Dyld->getSymbolAddress(Name);
639}
640
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000641uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
Andrew Kaylorea395922013-10-01 01:47:35 +0000642 if (!Dyld)
643 return 0;
Jim Grosbachdc1123f2012-09-05 16:50:40 +0000644 return Dyld->getSymbolLoadAddress(Name);
645}
646
Jim Grosbach733d3052011-04-12 21:20:41 +0000647void RuntimeDyld::resolveRelocations() {
648 Dyld->resolveRelocations();
649}
650
Jim Grosbacheff0a402012-01-16 22:26:39 +0000651void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
652 uint64_t Addr) {
653 Dyld->reassignSectionAddress(SectionID, Addr);
Jim Grosbach733d3052011-04-12 21:20:41 +0000654}
655
Jim Grosbach6d613972012-09-13 21:50:06 +0000656void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
Jim Grosbach0ddb3a42012-01-16 23:50:55 +0000657 uint64_t TargetAddress) {
658 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
659}
660
Jim Grosbach5cc5eef2011-03-22 18:22:27 +0000661StringRef RuntimeDyld::getErrorString() {
Jim Grosbach40411cc2011-03-22 18:19:42 +0000662 return Dyld->getErrorString();
663}
664
Andrew Kaylor7bb13442013-10-11 21:25:48 +0000665void RuntimeDyld::registerEHFrames() {
Andrew Kaylorc442a762013-10-16 00:14:21 +0000666 if (Dyld)
667 Dyld->registerEHFrames();
668}
669
670void RuntimeDyld::deregisterEHFrames() {
671 if (Dyld)
672 Dyld->deregisterEHFrames();
Rafael Espindolafa5942b2013-05-05 20:43:10 +0000673}
674
Jim Grosbachf016b0a2011-03-21 22:15:52 +0000675} // end namespace llvm