1 //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation of the MC-JIT runtime dynamic linker.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dyld"
15 #include "llvm/ExecutionEngine/RuntimeDyld.h"
16 #include "ObjectImageCommon.h"
17 #include "RuntimeDyldELF.h"
18 #include "RuntimeDyldImpl.h"
19 #include "RuntimeDyldMachO.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/Path.h"
24 using namespace llvm::object;
26 // Empty out-of-line virtual destructor as the key function.
27 RTDyldMemoryManager::~RTDyldMemoryManager() {}
28 RuntimeDyldImpl::~RuntimeDyldImpl() {}
32 // Resolve the relocations for all symbols we currently know about.
33 void RuntimeDyldImpl::resolveRelocations() {
34 // First, resolve relocations associated with external symbols.
35 resolveExternalSymbols();
37 // Just iterate over the sections we have and resolve all the relocations
38 // in them. Gross overkill, but it gets the job done.
39 for (int i = 0, e = Sections.size(); i != e; ++i) {
40 uint64_t Addr = Sections[i].LoadAddress;
41 DEBUG(dbgs() << "Resolving relocations Section #" << i
42 << "\t" << format("%p", (uint8_t *)Addr)
44 resolveRelocationList(Relocations[i], Addr);
48 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
49 uint64_t TargetAddress) {
50 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
51 if (Sections[i].Address == LocalAddress) {
52 reassignSectionAddress(i, TargetAddress);
56 llvm_unreachable("Attempting to remap address of unknown section!");
59 // Subclasses can implement this method to create specialized image instances.
60 // The caller owns the pointer that is returned.
61 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
62 return new ObjectImageCommon(InputBuffer);
65 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
66 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
68 report_fatal_error("Unable to create object image from memory buffer!");
70 Arch = (Triple::ArchType)obj->getArch();
72 // Symbols found in this object
73 StringMap<SymbolLoc> LocalSymbols;
74 // Used sections from the object file
75 ObjSectionToIDMap LocalSections;
77 // Common symbols requiring allocation, with their sizes and alignments
78 CommonSymbolMap CommonSymbols;
79 // Maximum required total memory to allocate all common symbols
80 uint64_t CommonSize = 0;
84 DEBUG(dbgs() << "Parse symbols:\n");
85 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
86 i != e; i.increment(err)) {
88 object::SymbolRef::Type SymType;
90 Check(i->getType(SymType));
91 Check(i->getName(Name));
94 Check(i->getFlags(flags));
96 bool isCommon = flags & SymbolRef::SF_Common;
98 // Add the common symbols to a list. We'll allocate them all below.
100 Check(i->getAlignment(Align));
102 Check(i->getSize(Size));
103 CommonSize += Size + Align;
104 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
106 if (SymType == object::SymbolRef::ST_Function ||
107 SymType == object::SymbolRef::ST_Data ||
108 SymType == object::SymbolRef::ST_Unknown) {
110 StringRef SectionData;
112 section_iterator si = obj->end_sections();
113 Check(i->getFileOffset(FileOffset));
114 Check(i->getSection(si));
115 if (si == obj->end_sections()) continue;
116 Check(si->getContents(SectionData));
117 Check(si->isText(IsCode));
118 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
119 (uintptr_t)FileOffset;
120 uintptr_t SectOffset = (uintptr_t)(SymPtr -
121 (const uint8_t*)SectionData.begin());
122 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
123 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
124 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
125 << " flags: " << flags
126 << " SID: " << SectionID
127 << " Offset: " << format("%p", SectOffset));
128 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
131 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
134 // Allocate common symbols
136 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
138 // Parse and process relocations
139 DEBUG(dbgs() << "Parse relocations:\n");
140 for (section_iterator si = obj->begin_sections(),
141 se = obj->end_sections(); si != se; si.increment(err)) {
143 bool isFirstRelocation = true;
144 unsigned SectionID = 0;
147 for (relocation_iterator i = si->begin_relocations(),
148 e = si->end_relocations(); i != e; i.increment(err)) {
151 // If it's the first relocation in this section, find its SectionID
152 if (isFirstRelocation) {
153 SectionID = findOrEmitSection(*obj, *si, true, LocalSections);
154 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
155 isFirstRelocation = false;
158 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
166 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
167 const CommonSymbolMap &CommonSymbols,
169 SymbolTableMap &SymbolTable) {
170 // Allocate memory for the section
171 unsigned SectionID = Sections.size();
172 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
175 report_fatal_error("Unable to allocate memory for common symbols!");
177 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, TotalSize, 0));
178 memset(Addr, 0, TotalSize);
180 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
181 << " new addr: " << format("%p", Addr)
182 << " DataSize: " << TotalSize
185 // Assign the address of each symbol
186 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
187 itEnd = CommonSymbols.end(); it != itEnd; it++) {
188 uint64_t Size = it->second.first;
189 uint64_t Align = it->second.second;
191 it->first.getName(Name);
193 // This symbol has an alignment requirement.
194 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
196 Offset += AlignOffset;
197 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
198 format("%p\n", Addr));
200 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
201 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
207 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
208 const SectionRef &Section,
211 unsigned StubBufSize = 0,
212 StubSize = getMaxStubSize();
215 for (relocation_iterator i = Section.begin_relocations(),
216 e = Section.end_relocations(); i != e; i.increment(err), Check(err))
217 StubBufSize += StubSize;
220 uint64_t Alignment64;
221 Check(Section.getContents(data));
222 Check(Section.getAlignment(Alignment64));
224 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
231 Check(Section.isRequiredForExecution(IsRequired));
232 Check(Section.isVirtual(IsVirtual));
233 Check(Section.isZeroInit(IsZeroInit));
234 Check(Section.isReadOnlyData(IsReadOnly));
235 Check(Section.getSize(DataSize));
236 Check(Section.getName(Name));
239 unsigned SectionID = Sections.size();
241 const char *pData = 0;
243 // Some sections, such as debug info, don't need to be loaded for execution.
244 // Leave those where they are.
246 Allocate = DataSize + StubBufSize;
248 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
249 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, IsReadOnly);
251 report_fatal_error("Unable to allocate section memory!");
253 // Virtual sections have no data in the object image, so leave pData = 0
257 // Zero-initialize or copy the data from the image
258 if (IsZeroInit || IsVirtual)
259 memset(Addr, 0, DataSize);
261 memcpy(Addr, pData, DataSize);
263 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
265 << " obj addr: " << format("%p", pData)
266 << " new addr: " << format("%p", Addr)
267 << " DataSize: " << DataSize
268 << " StubBufSize: " << StubBufSize
269 << " Allocate: " << Allocate
271 Obj.updateSectionAddress(Section, (uint64_t)Addr);
274 // Even if we didn't load the section, we need to record an entry for it
275 // to handle later processing (and by 'handle' I mean don't do anything
276 // with these sections).
279 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
281 << " obj addr: " << format("%p", data.data())
283 << " DataSize: " << DataSize
284 << " StubBufSize: " << StubBufSize
285 << " Allocate: " << Allocate
289 Sections.push_back(SectionEntry(Name, Addr, Allocate, DataSize,
294 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
295 const SectionRef &Section,
297 ObjSectionToIDMap &LocalSections) {
299 unsigned SectionID = 0;
300 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
301 if (i != LocalSections.end())
302 SectionID = i->second;
304 SectionID = emitSection(Obj, Section, IsCode);
305 LocalSections[Section] = SectionID;
310 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
311 unsigned SectionID) {
312 Relocations[SectionID].push_back(RE);
315 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
316 StringRef SymbolName) {
317 // Relocation by symbol. If the symbol is found in the global symbol table,
318 // create an appropriate section relocation. Otherwise, add it to
319 // ExternalSymbolRelocations.
320 SymbolTableMap::const_iterator Loc =
321 GlobalSymbolTable.find(SymbolName);
322 if (Loc == GlobalSymbolTable.end()) {
323 ExternalSymbolRelocations[SymbolName].push_back(RE);
325 // Copy the RE since we want to modify its addend.
326 RelocationEntry RECopy = RE;
327 RECopy.Addend += Loc->second.second;
328 Relocations[Loc->second.first].push_back(RECopy);
332 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
333 if (Arch == Triple::arm) {
334 // TODO: There is only ARM far stub now. We should add the Thumb stub,
335 // and stubs for branches Thumb - ARM and ARM - Thumb.
336 uint32_t *StubAddr = (uint32_t*)Addr;
337 *StubAddr = 0xe51ff004; // ldr pc,<label>
338 return (uint8_t*)++StubAddr;
339 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
340 uint32_t *StubAddr = (uint32_t*)Addr;
341 // 0: 3c190000 lui t9,%hi(addr).
342 // 4: 27390000 addiu t9,t9,%lo(addr).
343 // 8: 03200008 jr t9.
345 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
346 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
348 *StubAddr = LuiT9Instr;
350 *StubAddr = AdduiT9Instr;
352 *StubAddr = JrT9Instr;
354 *StubAddr = NopInstr;
356 } else if (Arch == Triple::ppc64) {
357 // PowerPC64 stub: the address points to a function descriptor
358 // instead of the function itself. Load the function address
359 // on r11 and sets it to control register. Also loads the function
360 // TOC in r2 and environment pointer to r11.
361 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
362 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
363 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
364 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
365 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
366 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
367 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
368 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
369 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
370 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
371 writeInt32BE(Addr+40, 0x4E800420); // bctr
378 // Assign an address to a symbol name and resolve all the relocations
379 // associated with it.
380 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
382 // The address to use for relocation resolution is not
383 // the address of the local section buffer. We must be doing
384 // a remote execution environment of some sort. Relocations can't
385 // be applied until all the sections have been moved. The client must
386 // trigger this with a call to MCJIT::finalize() or
387 // RuntimeDyld::resolveRelocations().
389 // Addr is a uint64_t because we can't assume the pointer width
390 // of the target is the same as that of the host. Just use a generic
391 // "big enough" type.
392 Sections[SectionID].LoadAddress = Addr;
395 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
397 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
398 const RelocationEntry &RE = Relocs[i];
399 // Ignore relocations for sections that were not loaded
400 if (Sections[RE.SectionID].Address == 0)
402 resolveRelocation(RE, Value);
406 void RuntimeDyldImpl::resolveExternalSymbols() {
407 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin(),
408 e = ExternalSymbolRelocations.end();
409 for (; i != e; i++) {
410 StringRef Name = i->first();
411 RelocationList &Relocs = i->second;
412 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
413 if (Loc == GlobalSymbolTable.end()) {
414 if (Name.size() == 0) {
415 // This is an absolute symbol, use an address of zero.
416 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
417 resolveRelocationList(Relocs, 0);
419 // This is an external symbol, try to get its address from
421 uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
423 DEBUG(dbgs() << "Resolving relocations Name: " << Name
424 << "\t" << format("%p", Addr)
426 resolveRelocationList(Relocs, (uintptr_t)Addr);
429 report_fatal_error("Expected external symbol");
435 //===----------------------------------------------------------------------===//
436 // RuntimeDyld class implementation
437 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
438 // FIXME: There's a potential issue lurking here if a single instance of
439 // RuntimeDyld is used to load multiple objects. The current implementation
440 // associates a single memory manager with a RuntimeDyld instance. Even
441 // though the public class spawns a new 'impl' instance for each load,
442 // they share a single memory manager. This can become a problem when page
443 // permissions are applied.
448 RuntimeDyld::~RuntimeDyld() {
452 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
454 sys::LLVMFileType type = sys::IdentifyFileType(
455 InputBuffer->getBufferStart(),
456 static_cast<unsigned>(InputBuffer->getBufferSize()));
458 case sys::ELF_Relocatable_FileType:
459 case sys::ELF_Executable_FileType:
460 case sys::ELF_SharedObject_FileType:
461 case sys::ELF_Core_FileType:
462 Dyld = new RuntimeDyldELF(MM);
464 case sys::Mach_O_Object_FileType:
465 case sys::Mach_O_Executable_FileType:
466 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
467 case sys::Mach_O_Core_FileType:
468 case sys::Mach_O_PreloadExecutable_FileType:
469 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
470 case sys::Mach_O_DynamicLinker_FileType:
471 case sys::Mach_O_Bundle_FileType:
472 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
473 case sys::Mach_O_DSYMCompanion_FileType:
474 Dyld = new RuntimeDyldMachO(MM);
476 case sys::Unknown_FileType:
477 case sys::Bitcode_FileType:
478 case sys::Archive_FileType:
479 case sys::COFF_FileType:
480 report_fatal_error("Incompatible object format!");
483 if (!Dyld->isCompatibleFormat(InputBuffer))
484 report_fatal_error("Incompatible object format!");
487 return Dyld->loadObject(InputBuffer);
490 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
491 return Dyld->getSymbolAddress(Name);
494 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
495 return Dyld->getSymbolLoadAddress(Name);
498 void RuntimeDyld::resolveRelocations() {
499 Dyld->resolveRelocations();
502 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
504 Dyld->reassignSectionAddress(SectionID, Addr);
507 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
508 uint64_t TargetAddress) {
509 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
512 StringRef RuntimeDyld::getErrorString() {
513 return Dyld->getErrorString();
516 } // end namespace llvm