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 "JITRegistrar.h"
17 #include "ObjectImageCommon.h"
18 #include "RuntimeDyldELF.h"
19 #include "RuntimeDyldImpl.h"
20 #include "RuntimeDyldMachO.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/MutexGuard.h"
24 #include "llvm/Object/ELF.h"
27 using namespace llvm::object;
29 // Empty out-of-line virtual destructor as the key function.
30 RuntimeDyldImpl::~RuntimeDyldImpl() {}
32 // Pin the JITRegistrar's and ObjectImage*'s vtables to this file.
33 void JITRegistrar::anchor() {}
34 void ObjectImage::anchor() {}
35 void ObjectImageCommon::anchor() {}
39 void RuntimeDyldImpl::registerEHFrames() {
42 void RuntimeDyldImpl::deregisterEHFrames() {
45 // Resolve the relocations for all symbols we currently know about.
46 void RuntimeDyldImpl::resolveRelocations() {
47 MutexGuard locked(lock);
49 // First, resolve relocations associated with external symbols.
50 resolveExternalSymbols();
52 // 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) {
55 // 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.
58 uint64_t Addr = Sections[i].LoadAddress;
59 DEBUG(dbgs() << "Resolving relocations Section #" << i
60 << "\t" << format("%p", (uint8_t *)Addr)
62 resolveRelocationList(Relocations[i], Addr);
67 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
68 uint64_t TargetAddress) {
69 MutexGuard locked(lock);
70 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
71 if (Sections[i].Address == LocalAddress) {
72 reassignSectionAddress(i, TargetAddress);
76 llvm_unreachable("Attempting to remap address of unknown section!");
79 // Subclasses can implement this method to create specialized image instances.
80 // The caller owns the pointer that is returned.
81 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
82 return new ObjectImageCommon(InputBuffer);
85 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
86 MutexGuard locked(lock);
88 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
90 report_fatal_error("Unable to create object image from memory buffer!");
92 // Save information about our target
93 Arch = (Triple::ArchType)obj->getArch();
94 IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
96 // Symbols found in this object
97 StringMap<SymbolLoc> LocalSymbols;
98 // Used sections from the object file
99 ObjSectionToIDMap LocalSections;
101 // Common symbols requiring allocation, with their sizes and alignments
102 CommonSymbolMap CommonSymbols;
103 // Maximum required total memory to allocate all common symbols
104 uint64_t CommonSize = 0;
108 DEBUG(dbgs() << "Parse symbols:\n");
109 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
110 i != e; i.increment(err)) {
112 object::SymbolRef::Type SymType;
114 Check(i->getType(SymType));
115 Check(i->getName(Name));
118 Check(i->getFlags(flags));
120 bool isCommon = flags & SymbolRef::SF_Common;
122 // Add the common symbols to a list. We'll allocate them all below.
124 Check(i->getAlignment(Align));
126 Check(i->getSize(Size));
127 CommonSize += Size + Align;
128 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
130 if (SymType == object::SymbolRef::ST_Function ||
131 SymType == object::SymbolRef::ST_Data ||
132 SymType == object::SymbolRef::ST_Unknown) {
134 StringRef SectionData;
136 section_iterator si = obj->end_sections();
137 Check(i->getFileOffset(FileOffset));
138 Check(i->getSection(si));
139 if (si == obj->end_sections()) continue;
140 Check(si->getContents(SectionData));
141 Check(si->isText(IsCode));
142 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
143 (uintptr_t)FileOffset;
144 uintptr_t SectOffset = (uintptr_t)(SymPtr -
145 (const uint8_t*)SectionData.begin());
146 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
147 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));
152 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
155 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
158 // Allocate common symbols
160 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
162 // Parse and process relocations
163 DEBUG(dbgs() << "Parse relocations:\n");
164 for (section_iterator si = obj->begin_sections(),
165 se = obj->end_sections(); si != se; si.increment(err)) {
167 bool isFirstRelocation = true;
168 unsigned SectionID = 0;
170 section_iterator RelocatedSection = si->getRelocatedSection();
172 for (relocation_iterator i = si->begin_relocations(),
173 e = si->end_relocations(); i != e; i.increment(err)) {
176 // If it's the first relocation in this section, find its SectionID
177 if (isFirstRelocation) {
179 findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
180 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
181 isFirstRelocation = false;
184 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
189 // Give the subclasses a chance to tie-up any loose ends.
190 finalizeLoad(LocalSections);
195 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
196 const CommonSymbolMap &CommonSymbols,
198 SymbolTableMap &SymbolTable) {
199 // Allocate memory for the section
200 unsigned SectionID = Sections.size();
201 uint8_t *Addr = MemMgr->allocateDataSection(
202 TotalSize, sizeof(void*), SectionID, StringRef(), false);
204 report_fatal_error("Unable to allocate memory for common symbols!");
206 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
207 memset(Addr, 0, TotalSize);
209 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
210 << " new addr: " << format("%p", Addr)
211 << " DataSize: " << TotalSize
214 // Assign the address of each symbol
215 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
216 itEnd = CommonSymbols.end(); it != itEnd; it++) {
217 uint64_t Size = it->second.first;
218 uint64_t Align = it->second.second;
220 it->first.getName(Name);
222 // This symbol has an alignment requirement.
223 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
225 Offset += AlignOffset;
226 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
227 format("%p\n", Addr));
229 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
230 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
236 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
237 const SectionRef &Section,
240 unsigned StubBufSize = 0,
241 StubSize = getMaxStubSize();
243 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
248 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))
255 for (relocation_iterator I = SI->begin_relocations(),
256 E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
257 StubBufSize += StubSize;
263 uint64_t Alignment64;
264 Check(Section.getContents(data));
265 Check(Section.getAlignment(Alignment64));
267 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
273 unsigned PaddingSize = 0;
275 Check(Section.isRequiredForExecution(IsRequired));
276 Check(Section.isVirtual(IsVirtual));
277 Check(Section.isZeroInit(IsZeroInit));
278 Check(Section.isReadOnlyData(IsReadOnly));
279 Check(Section.getSize(DataSize));
280 Check(Section.getName(Name));
282 unsigned StubAlignment = getStubAlignment();
283 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
284 if (StubAlignment > EndAlignment)
285 StubBufSize += StubAlignment - EndAlignment;
288 // 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")
295 unsigned SectionID = Sections.size();
297 const char *pData = 0;
299 // Some sections, such as debug info, don't need to be loaded for execution.
300 // Leave those where they are.
302 Allocate = DataSize + PaddingSize + StubBufSize;
304 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
305 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
308 report_fatal_error("Unable to allocate section memory!");
310 // Virtual sections have no data in the object image, so leave pData = 0
314 // Zero-initialize or copy the data from the image
315 if (IsZeroInit || IsVirtual)
316 memset(Addr, 0, DataSize);
318 memcpy(Addr, pData, DataSize);
320 // 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;
327 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
329 << " obj addr: " << format("%p", pData)
330 << " new addr: " << format("%p", Addr)
331 << " DataSize: " << DataSize
332 << " StubBufSize: " << StubBufSize
333 << " Allocate: " << Allocate
335 Obj.updateSectionAddress(Section, (uint64_t)Addr);
338 // Even if we didn't load the section, we need to record an entry for it
339 // to handle later processing (and by 'handle' I mean don't do anything
340 // with these sections).
343 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
345 << " obj addr: " << format("%p", data.data())
347 << " DataSize: " << DataSize
348 << " StubBufSize: " << StubBufSize
349 << " Allocate: " << Allocate
353 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
357 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
358 const SectionRef &Section,
360 ObjSectionToIDMap &LocalSections) {
362 unsigned SectionID = 0;
363 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
364 if (i != LocalSections.end())
365 SectionID = i->second;
367 SectionID = emitSection(Obj, Section, IsCode);
368 LocalSections[Section] = SectionID;
373 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
374 unsigned SectionID) {
375 Relocations[SectionID].push_back(RE);
378 void 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);
388 // 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);
395 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
396 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;
402 // Stub can use ip0 (== x16) to calculate address
403 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
405 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
407 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
409 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
411 *StubAddr = 0xd61f0200; // br ip0
414 } else if (Arch == Triple::arm) {
415 // TODO: There is only ARM far stub now. We should add the Thumb stub,
416 // and stubs for branches Thumb - ARM and ARM - Thumb.
417 uint32_t *StubAddr = (uint32_t*)Addr;
418 *StubAddr = 0xe51ff004; // ldr pc,<label>
419 return (uint8_t*)++StubAddr;
420 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
421 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.
426 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
427 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
429 *StubAddr = LuiT9Instr;
431 *StubAddr = AdduiT9Instr;
433 *StubAddr = JrT9Instr;
435 *StubAddr = NopInstr;
437 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
438 // 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
455 } 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
462 } else if (Arch == Triple::x86_64) {
464 *(Addr+1) = 0x25; // rip
465 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
470 // Assign an address to a symbol name and resolve all the relocations
471 // associated with it.
472 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
474 // The address to use for relocation resolution is not
475 // the address of the local section buffer. We must be doing
476 // 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().
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;
487 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
489 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
490 const RelocationEntry &RE = Relocs[i];
491 // Ignore relocations for sections that were not loaded
492 if (Sections[RE.SectionID].Address == 0)
494 resolveRelocation(RE, Value);
498 void RuntimeDyldImpl::resolveExternalSymbols() {
499 while(!ExternalSymbolRelocations.empty()) {
500 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
502 StringRef Name = i->first();
503 if (Name.size() == 0) {
504 // This is an absolute symbol, use an address of zero.
505 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
506 RelocationList &Relocs = i->second;
507 resolveRelocationList(Relocs, 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
514 Addr = MemMgr->getSymbolAddress(Name.data());
515 // 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);
523 // We found the symbol in our global table. It was probably in a
524 // Module that we loaded previously.
525 SymbolLoc SymLoc = Loc->second;
526 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
529 // FIXME: Implement error handling that doesn't kill the host program!
531 report_fatal_error("Program used external function '" + Name +
532 "' which could not be resolved!");
534 updateGOTEntries(Name, Addr);
535 DEBUG(dbgs() << "Resolving relocations Name: " << Name
536 << "\t" << format("0x%lx", Addr)
538 // 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;
541 resolveRelocationList(Relocs, Addr);
544 ExternalSymbolRelocations.erase(i);
549 //===----------------------------------------------------------------------===//
550 // RuntimeDyld class implementation
551 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
552 // 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.
562 RuntimeDyld::~RuntimeDyld() {
566 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
568 sys::fs::file_magic Type =
569 sys::fs::identify_magic(InputBuffer->getBuffer());
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);
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);
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:
593 case sys::fs::file_magic::coff_import_library:
594 case sys::fs::file_magic::pecoff_executable:
595 case sys::fs::file_magic::macho_universal_binary:
596 case sys::fs::file_magic::windows_resource:
597 report_fatal_error("Incompatible object format!");
600 if (!Dyld->isCompatibleFormat(InputBuffer))
601 report_fatal_error("Incompatible object format!");
604 return Dyld->loadObject(InputBuffer);
607 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
610 return Dyld->getSymbolAddress(Name);
613 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
616 return Dyld->getSymbolLoadAddress(Name);
619 void RuntimeDyld::resolveRelocations() {
620 Dyld->resolveRelocations();
623 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
625 Dyld->reassignSectionAddress(SectionID, Addr);
628 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
629 uint64_t TargetAddress) {
630 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
633 StringRef RuntimeDyld::getErrorString() {
634 return Dyld->getErrorString();
637 void RuntimeDyld::registerEHFrames() {
639 Dyld->registerEHFrames();
642 void RuntimeDyld::deregisterEHFrames() {
644 Dyld->deregisterEHFrames();
647 } // end namespace llvm