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::createObjectImageFromFile(ObjectFile *InputObject) {
86 return new ObjectImageCommon(InputObject);
89 ObjectImage *RuntimeDyldImpl::loadObject(ObjectFile *InputObject) {
90 return loadObject(createObjectImageFromFile(InputObject));
93 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
94 return loadObject(createObjectImage(InputBuffer));
97 ObjectImage *RuntimeDyldImpl::loadObject(ObjectImage *InputObject) {
98 MutexGuard locked(lock);
100 OwningPtr<ObjectImage> obj(InputObject);
104 // Save information about our target
105 Arch = (Triple::ArchType)obj->getArch();
106 IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
108 // Symbols found in this object
109 StringMap<SymbolLoc> LocalSymbols;
110 // Used sections from the object file
111 ObjSectionToIDMap LocalSections;
113 // Common symbols requiring allocation, with their sizes and alignments
114 CommonSymbolMap CommonSymbols;
115 // Maximum required total memory to allocate all common symbols
116 uint64_t CommonSize = 0;
120 DEBUG(dbgs() << "Parse symbols:\n");
121 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
122 i != e; i.increment(err)) {
124 object::SymbolRef::Type SymType;
126 Check(i->getType(SymType));
127 Check(i->getName(Name));
130 Check(i->getFlags(flags));
132 bool isCommon = flags & SymbolRef::SF_Common;
134 // Add the common symbols to a list. We'll allocate them all below.
136 Check(i->getAlignment(Align));
138 Check(i->getSize(Size));
139 CommonSize += Size + Align;
140 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
142 if (SymType == object::SymbolRef::ST_Function ||
143 SymType == object::SymbolRef::ST_Data ||
144 SymType == object::SymbolRef::ST_Unknown) {
146 StringRef SectionData;
148 section_iterator si = obj->end_sections();
149 Check(i->getFileOffset(FileOffset));
150 Check(i->getSection(si));
151 if (si == obj->end_sections()) continue;
152 Check(si->getContents(SectionData));
153 Check(si->isText(IsCode));
154 const uint8_t* SymPtr = (const uint8_t*)InputObject->getData().data() +
155 (uintptr_t)FileOffset;
156 uintptr_t SectOffset = (uintptr_t)(SymPtr -
157 (const uint8_t*)SectionData.begin());
158 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
159 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));
164 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
167 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
170 // Allocate common symbols
172 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
174 // Parse and process relocations
175 DEBUG(dbgs() << "Parse relocations:\n");
176 for (section_iterator si = obj->begin_sections(),
177 se = obj->end_sections(); si != se; si.increment(err)) {
179 bool isFirstRelocation = true;
180 unsigned SectionID = 0;
182 section_iterator RelocatedSection = si->getRelocatedSection();
184 for (relocation_iterator i = si->begin_relocations(),
185 e = si->end_relocations(); i != e; i.increment(err)) {
188 // If it's the first relocation in this section, find its SectionID
189 if (isFirstRelocation) {
191 findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
192 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
193 isFirstRelocation = false;
196 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
201 // Give the subclasses a chance to tie-up any loose ends.
202 finalizeLoad(LocalSections);
207 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
208 const CommonSymbolMap &CommonSymbols,
210 SymbolTableMap &SymbolTable) {
211 // Allocate memory for the section
212 unsigned SectionID = Sections.size();
213 uint8_t *Addr = MemMgr->allocateDataSection(
214 TotalSize, sizeof(void*), SectionID, StringRef(), false);
216 report_fatal_error("Unable to allocate memory for common symbols!");
218 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
219 memset(Addr, 0, TotalSize);
221 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
222 << " new addr: " << format("%p", Addr)
223 << " DataSize: " << TotalSize
226 // Assign the address of each symbol
227 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
228 itEnd = CommonSymbols.end(); it != itEnd; it++) {
229 uint64_t Size = it->second.first;
230 uint64_t Align = it->second.second;
232 it->first.getName(Name);
234 // This symbol has an alignment requirement.
235 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
237 Offset += AlignOffset;
238 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
239 format("%p\n", Addr));
241 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
242 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
248 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
249 const SectionRef &Section,
252 unsigned StubBufSize = 0,
253 StubSize = getMaxStubSize();
255 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
260 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))
267 for (relocation_iterator I = SI->begin_relocations(),
268 E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
269 StubBufSize += StubSize;
275 uint64_t Alignment64;
276 Check(Section.getContents(data));
277 Check(Section.getAlignment(Alignment64));
279 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
285 unsigned PaddingSize = 0;
287 Check(Section.isRequiredForExecution(IsRequired));
288 Check(Section.isVirtual(IsVirtual));
289 Check(Section.isZeroInit(IsZeroInit));
290 Check(Section.isReadOnlyData(IsReadOnly));
291 Check(Section.getSize(DataSize));
292 Check(Section.getName(Name));
294 unsigned StubAlignment = getStubAlignment();
295 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
296 if (StubAlignment > EndAlignment)
297 StubBufSize += StubAlignment - EndAlignment;
300 // 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")
307 unsigned SectionID = Sections.size();
309 const char *pData = 0;
311 // Some sections, such as debug info, don't need to be loaded for execution.
312 // Leave those where they are.
314 Allocate = DataSize + PaddingSize + StubBufSize;
316 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
317 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
320 report_fatal_error("Unable to allocate section memory!");
322 // Virtual sections have no data in the object image, so leave pData = 0
326 // Zero-initialize or copy the data from the image
327 if (IsZeroInit || IsVirtual)
328 memset(Addr, 0, DataSize);
330 memcpy(Addr, pData, DataSize);
332 // 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;
339 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
341 << " obj addr: " << format("%p", pData)
342 << " new addr: " << format("%p", Addr)
343 << " DataSize: " << DataSize
344 << " StubBufSize: " << StubBufSize
345 << " Allocate: " << Allocate
347 Obj.updateSectionAddress(Section, (uint64_t)Addr);
350 // Even if we didn't load the section, we need to record an entry for it
351 // to handle later processing (and by 'handle' I mean don't do anything
352 // with these sections).
355 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
357 << " obj addr: " << format("%p", data.data())
359 << " DataSize: " << DataSize
360 << " StubBufSize: " << StubBufSize
361 << " Allocate: " << Allocate
365 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
369 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
370 const SectionRef &Section,
372 ObjSectionToIDMap &LocalSections) {
374 unsigned SectionID = 0;
375 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
376 if (i != LocalSections.end())
377 SectionID = i->second;
379 SectionID = emitSection(Obj, Section, IsCode);
380 LocalSections[Section] = SectionID;
385 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
386 unsigned SectionID) {
387 Relocations[SectionID].push_back(RE);
390 void 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);
400 // 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);
407 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
408 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;
414 // Stub can use ip0 (== x16) to calculate address
415 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
417 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
419 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
421 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
423 *StubAddr = 0xd61f0200; // br ip0
426 } else if (Arch == Triple::arm) {
427 // TODO: There is only ARM far stub now. We should add the Thumb stub,
428 // and stubs for branches Thumb - ARM and ARM - Thumb.
429 uint32_t *StubAddr = (uint32_t*)Addr;
430 *StubAddr = 0xe51ff004; // ldr pc,<label>
431 return (uint8_t*)++StubAddr;
432 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
433 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.
438 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
439 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
441 *StubAddr = LuiT9Instr;
443 *StubAddr = AdduiT9Instr;
445 *StubAddr = JrT9Instr;
447 *StubAddr = NopInstr;
449 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
450 // 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
467 } 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
474 } else if (Arch == Triple::x86_64) {
476 *(Addr+1) = 0x25; // rip
477 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
482 // Assign an address to a symbol name and resolve all the relocations
483 // associated with it.
484 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
486 // The address to use for relocation resolution is not
487 // the address of the local section buffer. We must be doing
488 // 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().
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;
499 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
501 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
502 const RelocationEntry &RE = Relocs[i];
503 // Ignore relocations for sections that were not loaded
504 if (Sections[RE.SectionID].Address == 0)
506 resolveRelocation(RE, Value);
510 void RuntimeDyldImpl::resolveExternalSymbols() {
511 while(!ExternalSymbolRelocations.empty()) {
512 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
514 StringRef Name = i->first();
515 if (Name.size() == 0) {
516 // This is an absolute symbol, use an address of zero.
517 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
518 RelocationList &Relocs = i->second;
519 resolveRelocationList(Relocs, 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
526 Addr = MemMgr->getSymbolAddress(Name.data());
527 // 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);
535 // We found the symbol in our global table. It was probably in a
536 // Module that we loaded previously.
537 SymbolLoc SymLoc = Loc->second;
538 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
541 // FIXME: Implement error handling that doesn't kill the host program!
543 report_fatal_error("Program used external function '" + Name +
544 "' which could not be resolved!");
546 updateGOTEntries(Name, Addr);
547 DEBUG(dbgs() << "Resolving relocations Name: " << Name
548 << "\t" << format("0x%lx", Addr)
550 // 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;
553 resolveRelocationList(Relocs, Addr);
556 ExternalSymbolRelocations.erase(i);
561 //===----------------------------------------------------------------------===//
562 // RuntimeDyld class implementation
563 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
564 // 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.
574 RuntimeDyld::~RuntimeDyld() {
578 ObjectImage *RuntimeDyld::loadObject(ObjectFile *InputObject) {
580 if (InputObject->isELF())
581 Dyld = new RuntimeDyldELF(MM);
582 else if (InputObject->isMachO())
583 Dyld = new RuntimeDyldMachO(MM);
585 report_fatal_error("Incompatible object format!");
587 if (!Dyld->isCompatibleFile(InputObject))
588 report_fatal_error("Incompatible object format!");
591 return Dyld->loadObject(InputObject);
594 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
596 sys::fs::file_magic Type =
597 sys::fs::identify_magic(InputBuffer->getBuffer());
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);
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);
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:
621 case sys::fs::file_magic::coff_import_library:
622 case sys::fs::file_magic::pecoff_executable:
623 case sys::fs::file_magic::macho_universal_binary:
624 case sys::fs::file_magic::windows_resource:
625 report_fatal_error("Incompatible object format!");
628 if (!Dyld->isCompatibleFormat(InputBuffer))
629 report_fatal_error("Incompatible object format!");
632 return Dyld->loadObject(InputBuffer);
635 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
638 return Dyld->getSymbolAddress(Name);
641 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
644 return Dyld->getSymbolLoadAddress(Name);
647 void RuntimeDyld::resolveRelocations() {
648 Dyld->resolveRelocations();
651 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
653 Dyld->reassignSectionAddress(SectionID, Addr);
656 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
657 uint64_t TargetAddress) {
658 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
661 StringRef RuntimeDyld::getErrorString() {
662 return Dyld->getErrorString();
665 void RuntimeDyld::registerEHFrames() {
667 Dyld->registerEHFrames();
670 void RuntimeDyld::deregisterEHFrames() {
672 Dyld->deregisterEHFrames();
675 } // end namespace llvm