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/FileSystem.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Object/ELF.h"
25 using namespace llvm::object;
27 // Empty out-of-line virtual destructor as the key function.
28 RuntimeDyldImpl::~RuntimeDyldImpl() {}
32 void RuntimeDyldImpl::registerEHFrames() {
35 void RuntimeDyldImpl::deregisterEHFrames() {
38 // Resolve the relocations for all symbols we currently know about.
39 void RuntimeDyldImpl::resolveRelocations() {
40 // First, resolve relocations associated with external symbols.
41 resolveExternalSymbols();
43 // Just iterate over the sections we have and resolve all the relocations
44 // in them. Gross overkill, but it gets the job done.
45 for (int i = 0, e = Sections.size(); i != e; ++i) {
46 // The Section here (Sections[i]) refers to the section in which the
47 // symbol for the relocation is located. The SectionID in the relocation
48 // entry provides the section to which the relocation will be applied.
49 uint64_t Addr = Sections[i].LoadAddress;
50 DEBUG(dbgs() << "Resolving relocations Section #" << i
51 << "\t" << format("%p", (uint8_t *)Addr)
53 resolveRelocationList(Relocations[i], Addr);
58 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
59 uint64_t TargetAddress) {
60 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
61 if (Sections[i].Address == LocalAddress) {
62 reassignSectionAddress(i, TargetAddress);
66 llvm_unreachable("Attempting to remap address of unknown section!");
69 // Subclasses can implement this method to create specialized image instances.
70 // The caller owns the pointer that is returned.
71 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
72 return new ObjectImageCommon(InputBuffer);
75 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
76 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
78 report_fatal_error("Unable to create object image from memory buffer!");
80 // Save information about our target
81 Arch = (Triple::ArchType)obj->getArch();
82 IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
84 // Symbols found in this object
85 StringMap<SymbolLoc> LocalSymbols;
86 // Used sections from the object file
87 ObjSectionToIDMap LocalSections;
89 // Common symbols requiring allocation, with their sizes and alignments
90 CommonSymbolMap CommonSymbols;
91 // Maximum required total memory to allocate all common symbols
92 uint64_t CommonSize = 0;
96 DEBUG(dbgs() << "Parse symbols:\n");
97 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
98 i != e; i.increment(err)) {
100 object::SymbolRef::Type SymType;
102 Check(i->getType(SymType));
103 Check(i->getName(Name));
106 Check(i->getFlags(flags));
108 bool isCommon = flags & SymbolRef::SF_Common;
110 // Add the common symbols to a list. We'll allocate them all below.
112 Check(i->getAlignment(Align));
114 Check(i->getSize(Size));
115 CommonSize += Size + Align;
116 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
118 if (SymType == object::SymbolRef::ST_Function ||
119 SymType == object::SymbolRef::ST_Data ||
120 SymType == object::SymbolRef::ST_Unknown) {
122 StringRef SectionData;
124 section_iterator si = obj->end_sections();
125 Check(i->getFileOffset(FileOffset));
126 Check(i->getSection(si));
127 if (si == obj->end_sections()) continue;
128 Check(si->getContents(SectionData));
129 Check(si->isText(IsCode));
130 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
131 (uintptr_t)FileOffset;
132 uintptr_t SectOffset = (uintptr_t)(SymPtr -
133 (const uint8_t*)SectionData.begin());
134 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
135 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
136 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
137 << " flags: " << flags
138 << " SID: " << SectionID
139 << " Offset: " << format("%p", SectOffset));
140 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
143 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
146 // Allocate common symbols
148 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
150 // Parse and process relocations
151 DEBUG(dbgs() << "Parse relocations:\n");
152 for (section_iterator si = obj->begin_sections(),
153 se = obj->end_sections(); si != se; si.increment(err)) {
155 bool isFirstRelocation = true;
156 unsigned SectionID = 0;
158 section_iterator RelocatedSection = si->getRelocatedSection();
160 for (relocation_iterator i = si->begin_relocations(),
161 e = si->end_relocations(); i != e; i.increment(err)) {
164 // If it's the first relocation in this section, find its SectionID
165 if (isFirstRelocation) {
167 findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
168 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
169 isFirstRelocation = false;
172 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
177 // Give the subclasses a chance to tie-up any loose ends.
178 finalizeLoad(LocalSections);
183 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
184 const CommonSymbolMap &CommonSymbols,
186 SymbolTableMap &SymbolTable) {
187 // Allocate memory for the section
188 unsigned SectionID = Sections.size();
189 uint8_t *Addr = MemMgr->allocateDataSection(
190 TotalSize, sizeof(void*), SectionID, StringRef(), false);
192 report_fatal_error("Unable to allocate memory for common symbols!");
194 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
195 memset(Addr, 0, TotalSize);
197 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
198 << " new addr: " << format("%p", Addr)
199 << " DataSize: " << TotalSize
202 // Assign the address of each symbol
203 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
204 itEnd = CommonSymbols.end(); it != itEnd; it++) {
205 uint64_t Size = it->second.first;
206 uint64_t Align = it->second.second;
208 it->first.getName(Name);
210 // This symbol has an alignment requirement.
211 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
213 Offset += AlignOffset;
214 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
215 format("%p\n", Addr));
217 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
218 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
224 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
225 const SectionRef &Section,
228 unsigned StubBufSize = 0,
229 StubSize = getMaxStubSize();
231 const ObjectFile *ObjFile = Obj.getObjectFile();
232 // FIXME: this is an inefficient way to handle this. We should computed the
233 // necessary section allocation size in loadObject by walking all the sections
236 for (section_iterator SI = ObjFile->begin_sections(),
237 SE = ObjFile->end_sections();
238 SI != SE; SI.increment(err), Check(err)) {
239 section_iterator RelSecI = SI->getRelocatedSection();
240 if (!(RelSecI == Section))
243 for (relocation_iterator I = SI->begin_relocations(),
244 E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
245 StubBufSize += StubSize;
251 uint64_t Alignment64;
252 Check(Section.getContents(data));
253 Check(Section.getAlignment(Alignment64));
255 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
262 Check(Section.isRequiredForExecution(IsRequired));
263 Check(Section.isVirtual(IsVirtual));
264 Check(Section.isZeroInit(IsZeroInit));
265 Check(Section.isReadOnlyData(IsReadOnly));
266 Check(Section.getSize(DataSize));
267 Check(Section.getName(Name));
269 unsigned StubAlignment = getStubAlignment();
270 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
271 if (StubAlignment > EndAlignment)
272 StubBufSize += StubAlignment - EndAlignment;
276 unsigned SectionID = Sections.size();
278 const char *pData = 0;
280 // Some sections, such as debug info, don't need to be loaded for execution.
281 // Leave those where they are.
283 Allocate = DataSize + StubBufSize;
285 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
286 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
289 report_fatal_error("Unable to allocate section memory!");
291 // Virtual sections have no data in the object image, so leave pData = 0
295 // Zero-initialize or copy the data from the image
296 if (IsZeroInit || IsVirtual)
297 memset(Addr, 0, DataSize);
299 memcpy(Addr, pData, DataSize);
301 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
303 << " obj addr: " << format("%p", pData)
304 << " new addr: " << format("%p", Addr)
305 << " DataSize: " << DataSize
306 << " StubBufSize: " << StubBufSize
307 << " Allocate: " << Allocate
309 Obj.updateSectionAddress(Section, (uint64_t)Addr);
312 // Even if we didn't load the section, we need to record an entry for it
313 // to handle later processing (and by 'handle' I mean don't do anything
314 // with these sections).
317 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
319 << " obj addr: " << format("%p", data.data())
321 << " DataSize: " << DataSize
322 << " StubBufSize: " << StubBufSize
323 << " Allocate: " << Allocate
327 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
331 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
332 const SectionRef &Section,
334 ObjSectionToIDMap &LocalSections) {
336 unsigned SectionID = 0;
337 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
338 if (i != LocalSections.end())
339 SectionID = i->second;
341 SectionID = emitSection(Obj, Section, IsCode);
342 LocalSections[Section] = SectionID;
347 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
348 unsigned SectionID) {
349 Relocations[SectionID].push_back(RE);
352 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
353 StringRef SymbolName) {
354 // Relocation by symbol. If the symbol is found in the global symbol table,
355 // create an appropriate section relocation. Otherwise, add it to
356 // ExternalSymbolRelocations.
357 SymbolTableMap::const_iterator Loc =
358 GlobalSymbolTable.find(SymbolName);
359 if (Loc == GlobalSymbolTable.end()) {
360 ExternalSymbolRelocations[SymbolName].push_back(RE);
362 // Copy the RE since we want to modify its addend.
363 RelocationEntry RECopy = RE;
364 RECopy.Addend += Loc->second.second;
365 Relocations[Loc->second.first].push_back(RECopy);
369 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
370 if (Arch == Triple::aarch64) {
371 // This stub has to be able to access the full address space,
372 // since symbol lookup won't necessarily find a handy, in-range,
373 // PLT stub for functions which could be anywhere.
374 uint32_t *StubAddr = (uint32_t*)Addr;
376 // Stub can use ip0 (== x16) to calculate address
377 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
379 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
381 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
383 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
385 *StubAddr = 0xd61f0200; // br ip0
388 } else if (Arch == Triple::arm) {
389 // TODO: There is only ARM far stub now. We should add the Thumb stub,
390 // and stubs for branches Thumb - ARM and ARM - Thumb.
391 uint32_t *StubAddr = (uint32_t*)Addr;
392 *StubAddr = 0xe51ff004; // ldr pc,<label>
393 return (uint8_t*)++StubAddr;
394 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
395 uint32_t *StubAddr = (uint32_t*)Addr;
396 // 0: 3c190000 lui t9,%hi(addr).
397 // 4: 27390000 addiu t9,t9,%lo(addr).
398 // 8: 03200008 jr t9.
400 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
401 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
403 *StubAddr = LuiT9Instr;
405 *StubAddr = AdduiT9Instr;
407 *StubAddr = JrT9Instr;
409 *StubAddr = NopInstr;
411 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
412 // PowerPC64 stub: the address points to a function descriptor
413 // instead of the function itself. Load the function address
414 // on r11 and sets it to control register. Also loads the function
415 // TOC in r2 and environment pointer to r11.
416 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
417 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
418 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
419 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
420 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
421 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
422 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
423 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
424 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
425 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
426 writeInt32BE(Addr+40, 0x4E800420); // bctr
429 } else if (Arch == Triple::systemz) {
430 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
431 writeInt16BE(Addr+2, 0x0000);
432 writeInt16BE(Addr+4, 0x0004);
433 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
434 // 8-byte address stored at Addr + 8
436 } else if (Arch == Triple::x86_64) {
438 *(Addr+1) = 0x25; // rip
439 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
444 // Assign an address to a symbol name and resolve all the relocations
445 // associated with it.
446 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
448 // The address to use for relocation resolution is not
449 // the address of the local section buffer. We must be doing
450 // a remote execution environment of some sort. Relocations can't
451 // be applied until all the sections have been moved. The client must
452 // trigger this with a call to MCJIT::finalize() or
453 // RuntimeDyld::resolveRelocations().
455 // Addr is a uint64_t because we can't assume the pointer width
456 // of the target is the same as that of the host. Just use a generic
457 // "big enough" type.
458 Sections[SectionID].LoadAddress = Addr;
461 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
463 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
464 const RelocationEntry &RE = Relocs[i];
465 // Ignore relocations for sections that were not loaded
466 if (Sections[RE.SectionID].Address == 0)
468 resolveRelocation(RE, Value);
472 void RuntimeDyldImpl::resolveExternalSymbols() {
473 while(!ExternalSymbolRelocations.empty()) {
474 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
476 StringRef Name = i->first();
477 RelocationList &Relocs = i->second;
478 if (Name.size() == 0) {
479 // This is an absolute symbol, use an address of zero.
480 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
481 resolveRelocationList(Relocs, 0);
484 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
485 if (Loc == GlobalSymbolTable.end()) {
486 // This is an external symbol, try to get its address from
488 Addr = MemMgr->getSymbolAddress(Name.data());
490 // We found the symbol in our global table. It was probably in a
491 // Module that we loaded previously.
492 SymbolLoc SymLoc = GlobalSymbolTable.lookup(Name);
493 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
496 // FIXME: Implement error handling that doesn't kill the host program!
498 report_fatal_error("Program used external function '" + Name +
499 "' which could not be resolved!");
501 updateGOTEntries(Name, Addr);
502 DEBUG(dbgs() << "Resolving relocations Name: " << Name
503 << "\t" << format("0x%lx", Addr)
505 resolveRelocationList(Relocs, Addr);
508 ExternalSymbolRelocations.erase(i->first());
513 //===----------------------------------------------------------------------===//
514 // RuntimeDyld class implementation
515 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
516 // FIXME: There's a potential issue lurking here if a single instance of
517 // RuntimeDyld is used to load multiple objects. The current implementation
518 // associates a single memory manager with a RuntimeDyld instance. Even
519 // though the public class spawns a new 'impl' instance for each load,
520 // they share a single memory manager. This can become a problem when page
521 // permissions are applied.
526 RuntimeDyld::~RuntimeDyld() {
530 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
532 sys::fs::file_magic Type =
533 sys::fs::identify_magic(InputBuffer->getBuffer());
535 case sys::fs::file_magic::elf_relocatable:
536 case sys::fs::file_magic::elf_executable:
537 case sys::fs::file_magic::elf_shared_object:
538 case sys::fs::file_magic::elf_core:
539 Dyld = new RuntimeDyldELF(MM);
541 case sys::fs::file_magic::macho_object:
542 case sys::fs::file_magic::macho_executable:
543 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
544 case sys::fs::file_magic::macho_core:
545 case sys::fs::file_magic::macho_preload_executable:
546 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
547 case sys::fs::file_magic::macho_dynamic_linker:
548 case sys::fs::file_magic::macho_bundle:
549 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
550 case sys::fs::file_magic::macho_dsym_companion:
551 Dyld = new RuntimeDyldMachO(MM);
553 case sys::fs::file_magic::unknown:
554 case sys::fs::file_magic::bitcode:
555 case sys::fs::file_magic::archive:
556 case sys::fs::file_magic::coff_object:
557 case sys::fs::file_magic::pecoff_executable:
558 case sys::fs::file_magic::macho_universal_binary:
559 case sys::fs::file_magic::windows_resource:
560 report_fatal_error("Incompatible object format!");
563 if (!Dyld->isCompatibleFormat(InputBuffer))
564 report_fatal_error("Incompatible object format!");
567 return Dyld->loadObject(InputBuffer);
570 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
573 return Dyld->getSymbolAddress(Name);
576 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
579 return Dyld->getSymbolLoadAddress(Name);
582 void RuntimeDyld::resolveRelocations() {
583 Dyld->resolveRelocations();
586 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
588 Dyld->reassignSectionAddress(SectionID, Addr);
591 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
592 uint64_t TargetAddress) {
593 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
596 StringRef RuntimeDyld::getErrorString() {
597 return Dyld->getErrorString();
600 void RuntimeDyld::registerEHFrames() {
602 Dyld->registerEHFrames();
605 void RuntimeDyld::deregisterEHFrames() {
607 Dyld->deregisterEHFrames();
610 } // end namespace llvm