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 // Resolve the relocations for all symbols we currently know about.
36 void RuntimeDyldImpl::resolveRelocations() {
37 // First, resolve relocations associated with external symbols.
38 resolveExternalSymbols();
40 // Just iterate over the sections we have and resolve all the relocations
41 // in them. Gross overkill, but it gets the job done.
42 for (int i = 0, e = Sections.size(); i != e; ++i) {
43 // The Section here (Sections[i]) refers to the section in which the
44 // symbol for the relocation is located. The SectionID in the relocation
45 // entry provides the section to which the relocation will be applied.
46 uint64_t Addr = Sections[i].LoadAddress;
47 DEBUG(dbgs() << "Resolving relocations Section #" << i
48 << "\t" << format("%p", (uint8_t *)Addr)
50 resolveRelocationList(Relocations[i], Addr);
55 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
56 uint64_t TargetAddress) {
57 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
58 if (Sections[i].Address == LocalAddress) {
59 reassignSectionAddress(i, TargetAddress);
63 llvm_unreachable("Attempting to remap address of unknown section!");
66 // Subclasses can implement this method to create specialized image instances.
67 // The caller owns the pointer that is returned.
68 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
69 return new ObjectImageCommon(InputBuffer);
72 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
73 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
75 report_fatal_error("Unable to create object image from memory buffer!");
77 // Save information about our target
78 Arch = (Triple::ArchType)obj->getArch();
79 IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
81 // Symbols found in this object
82 StringMap<SymbolLoc> LocalSymbols;
83 // Used sections from the object file
84 ObjSectionToIDMap LocalSections;
86 // Common symbols requiring allocation, with their sizes and alignments
87 CommonSymbolMap CommonSymbols;
88 // Maximum required total memory to allocate all common symbols
89 uint64_t CommonSize = 0;
93 DEBUG(dbgs() << "Parse symbols:\n");
94 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
95 i != e; i.increment(err)) {
97 object::SymbolRef::Type SymType;
99 Check(i->getType(SymType));
100 Check(i->getName(Name));
103 Check(i->getFlags(flags));
105 bool isCommon = flags & SymbolRef::SF_Common;
107 // Add the common symbols to a list. We'll allocate them all below.
109 Check(i->getAlignment(Align));
111 Check(i->getSize(Size));
112 CommonSize += Size + Align;
113 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
115 if (SymType == object::SymbolRef::ST_Function ||
116 SymType == object::SymbolRef::ST_Data ||
117 SymType == object::SymbolRef::ST_Unknown) {
119 StringRef SectionData;
121 section_iterator si = obj->end_sections();
122 Check(i->getFileOffset(FileOffset));
123 Check(i->getSection(si));
124 if (si == obj->end_sections()) continue;
125 Check(si->getContents(SectionData));
126 Check(si->isText(IsCode));
127 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
128 (uintptr_t)FileOffset;
129 uintptr_t SectOffset = (uintptr_t)(SymPtr -
130 (const uint8_t*)SectionData.begin());
131 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
132 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
133 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
134 << " flags: " << flags
135 << " SID: " << SectionID
136 << " Offset: " << format("%p", SectOffset));
137 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
140 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
143 // Allocate common symbols
145 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
147 // Parse and process relocations
148 DEBUG(dbgs() << "Parse relocations:\n");
149 for (section_iterator si = obj->begin_sections(),
150 se = obj->end_sections(); si != se; si.increment(err)) {
152 bool isFirstRelocation = true;
153 unsigned SectionID = 0;
155 section_iterator RelocatedSection = si->getRelocatedSection();
157 for (relocation_iterator i = si->begin_relocations(),
158 e = si->end_relocations(); i != e; i.increment(err)) {
161 // If it's the first relocation in this section, find its SectionID
162 if (isFirstRelocation) {
164 findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
165 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
166 isFirstRelocation = false;
169 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
174 // Give the subclasses a chance to tie-up any loose ends.
175 finalizeLoad(LocalSections);
180 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
181 const CommonSymbolMap &CommonSymbols,
183 SymbolTableMap &SymbolTable) {
184 // Allocate memory for the section
185 unsigned SectionID = Sections.size();
186 uint8_t *Addr = MemMgr->allocateDataSection(
187 TotalSize, sizeof(void*), SectionID, StringRef(), false);
189 report_fatal_error("Unable to allocate memory for common symbols!");
191 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
192 memset(Addr, 0, TotalSize);
194 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
195 << " new addr: " << format("%p", Addr)
196 << " DataSize: " << TotalSize
199 // Assign the address of each symbol
200 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
201 itEnd = CommonSymbols.end(); it != itEnd; it++) {
202 uint64_t Size = it->second.first;
203 uint64_t Align = it->second.second;
205 it->first.getName(Name);
207 // This symbol has an alignment requirement.
208 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
210 Offset += AlignOffset;
211 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
212 format("%p\n", Addr));
214 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
215 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
221 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
222 const SectionRef &Section,
225 unsigned StubBufSize = 0,
226 StubSize = getMaxStubSize();
228 const ObjectFile *ObjFile = Obj.getObjectFile();
229 // FIXME: this is an inefficient way to handle this. We should computed the
230 // necessary section allocation size in loadObject by walking all the sections
233 for (section_iterator SI = ObjFile->begin_sections(),
234 SE = ObjFile->end_sections();
235 SI != SE; SI.increment(err), Check(err)) {
236 section_iterator RelSecI = SI->getRelocatedSection();
237 if (!(RelSecI == Section))
240 for (relocation_iterator I = SI->begin_relocations(),
241 E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
242 StubBufSize += StubSize;
248 uint64_t Alignment64;
249 Check(Section.getContents(data));
250 Check(Section.getAlignment(Alignment64));
252 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
259 Check(Section.isRequiredForExecution(IsRequired));
260 Check(Section.isVirtual(IsVirtual));
261 Check(Section.isZeroInit(IsZeroInit));
262 Check(Section.isReadOnlyData(IsReadOnly));
263 Check(Section.getSize(DataSize));
264 Check(Section.getName(Name));
266 unsigned StubAlignment = getStubAlignment();
267 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
268 if (StubAlignment > EndAlignment)
269 StubBufSize += StubAlignment - EndAlignment;
273 unsigned SectionID = Sections.size();
275 const char *pData = 0;
277 // Some sections, such as debug info, don't need to be loaded for execution.
278 // Leave those where they are.
280 Allocate = DataSize + StubBufSize;
282 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
283 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
286 report_fatal_error("Unable to allocate section memory!");
288 // Virtual sections have no data in the object image, so leave pData = 0
292 // Zero-initialize or copy the data from the image
293 if (IsZeroInit || IsVirtual)
294 memset(Addr, 0, DataSize);
296 memcpy(Addr, pData, DataSize);
298 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
300 << " obj addr: " << format("%p", pData)
301 << " new addr: " << format("%p", Addr)
302 << " DataSize: " << DataSize
303 << " StubBufSize: " << StubBufSize
304 << " Allocate: " << Allocate
306 Obj.updateSectionAddress(Section, (uint64_t)Addr);
309 // Even if we didn't load the section, we need to record an entry for it
310 // to handle later processing (and by 'handle' I mean don't do anything
311 // with these sections).
314 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
316 << " obj addr: " << format("%p", data.data())
318 << " DataSize: " << DataSize
319 << " StubBufSize: " << StubBufSize
320 << " Allocate: " << Allocate
324 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
328 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
329 const SectionRef &Section,
331 ObjSectionToIDMap &LocalSections) {
333 unsigned SectionID = 0;
334 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
335 if (i != LocalSections.end())
336 SectionID = i->second;
338 SectionID = emitSection(Obj, Section, IsCode);
339 LocalSections[Section] = SectionID;
344 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
345 unsigned SectionID) {
346 Relocations[SectionID].push_back(RE);
349 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
350 StringRef SymbolName) {
351 // Relocation by symbol. If the symbol is found in the global symbol table,
352 // create an appropriate section relocation. Otherwise, add it to
353 // ExternalSymbolRelocations.
354 SymbolTableMap::const_iterator Loc =
355 GlobalSymbolTable.find(SymbolName);
356 if (Loc == GlobalSymbolTable.end()) {
357 ExternalSymbolRelocations[SymbolName].push_back(RE);
359 // Copy the RE since we want to modify its addend.
360 RelocationEntry RECopy = RE;
361 RECopy.Addend += Loc->second.second;
362 Relocations[Loc->second.first].push_back(RECopy);
366 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
367 if (Arch == Triple::aarch64) {
368 // This stub has to be able to access the full address space,
369 // since symbol lookup won't necessarily find a handy, in-range,
370 // PLT stub for functions which could be anywhere.
371 uint32_t *StubAddr = (uint32_t*)Addr;
373 // Stub can use ip0 (== x16) to calculate address
374 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
376 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
378 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
380 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
382 *StubAddr = 0xd61f0200; // br ip0
385 } else if (Arch == Triple::arm) {
386 // TODO: There is only ARM far stub now. We should add the Thumb stub,
387 // and stubs for branches Thumb - ARM and ARM - Thumb.
388 uint32_t *StubAddr = (uint32_t*)Addr;
389 *StubAddr = 0xe51ff004; // ldr pc,<label>
390 return (uint8_t*)++StubAddr;
391 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
392 uint32_t *StubAddr = (uint32_t*)Addr;
393 // 0: 3c190000 lui t9,%hi(addr).
394 // 4: 27390000 addiu t9,t9,%lo(addr).
395 // 8: 03200008 jr t9.
397 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
398 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
400 *StubAddr = LuiT9Instr;
402 *StubAddr = AdduiT9Instr;
404 *StubAddr = JrT9Instr;
406 *StubAddr = NopInstr;
408 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
409 // PowerPC64 stub: the address points to a function descriptor
410 // instead of the function itself. Load the function address
411 // on r11 and sets it to control register. Also loads the function
412 // TOC in r2 and environment pointer to r11.
413 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
414 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
415 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
416 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
417 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
418 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
419 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
420 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
421 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
422 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
423 writeInt32BE(Addr+40, 0x4E800420); // bctr
426 } else if (Arch == Triple::systemz) {
427 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
428 writeInt16BE(Addr+2, 0x0000);
429 writeInt16BE(Addr+4, 0x0004);
430 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
431 // 8-byte address stored at Addr + 8
433 } else if (Arch == Triple::x86_64) {
435 *(Addr+1) = 0x25; // rip
436 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
441 // Assign an address to a symbol name and resolve all the relocations
442 // associated with it.
443 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
445 // The address to use for relocation resolution is not
446 // the address of the local section buffer. We must be doing
447 // a remote execution environment of some sort. Relocations can't
448 // be applied until all the sections have been moved. The client must
449 // trigger this with a call to MCJIT::finalize() or
450 // RuntimeDyld::resolveRelocations().
452 // Addr is a uint64_t because we can't assume the pointer width
453 // of the target is the same as that of the host. Just use a generic
454 // "big enough" type.
455 Sections[SectionID].LoadAddress = Addr;
458 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
460 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
461 const RelocationEntry &RE = Relocs[i];
462 // Ignore relocations for sections that were not loaded
463 if (Sections[RE.SectionID].Address == 0)
465 resolveRelocation(RE, Value);
469 void RuntimeDyldImpl::resolveExternalSymbols() {
470 while(!ExternalSymbolRelocations.empty()) {
471 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
473 StringRef Name = i->first();
474 RelocationList &Relocs = i->second;
475 if (Name.size() == 0) {
476 // This is an absolute symbol, use an address of zero.
477 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
478 resolveRelocationList(Relocs, 0);
481 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
482 if (Loc == GlobalSymbolTable.end()) {
483 // This is an external symbol, try to get its address from
485 Addr = MemMgr->getSymbolAddress(Name.data());
487 // We found the symbol in our global table. It was probably in a
488 // Module that we loaded previously.
489 SymbolLoc SymLoc = GlobalSymbolTable.lookup(Name);
490 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
493 // FIXME: Implement error handling that doesn't kill the host program!
495 report_fatal_error("Program used external function '" + Name +
496 "' which could not be resolved!");
498 updateGOTEntries(Name, Addr);
499 DEBUG(dbgs() << "Resolving relocations Name: " << Name
500 << "\t" << format("0x%lx", Addr)
502 resolveRelocationList(Relocs, Addr);
505 ExternalSymbolRelocations.erase(i->first());
510 //===----------------------------------------------------------------------===//
511 // RuntimeDyld class implementation
512 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
513 // FIXME: There's a potential issue lurking here if a single instance of
514 // RuntimeDyld is used to load multiple objects. The current implementation
515 // associates a single memory manager with a RuntimeDyld instance. Even
516 // though the public class spawns a new 'impl' instance for each load,
517 // they share a single memory manager. This can become a problem when page
518 // permissions are applied.
523 RuntimeDyld::~RuntimeDyld() {
527 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
529 sys::fs::file_magic Type =
530 sys::fs::identify_magic(InputBuffer->getBuffer());
532 case sys::fs::file_magic::elf_relocatable:
533 case sys::fs::file_magic::elf_executable:
534 case sys::fs::file_magic::elf_shared_object:
535 case sys::fs::file_magic::elf_core:
536 Dyld = new RuntimeDyldELF(MM);
538 case sys::fs::file_magic::macho_object:
539 case sys::fs::file_magic::macho_executable:
540 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
541 case sys::fs::file_magic::macho_core:
542 case sys::fs::file_magic::macho_preload_executable:
543 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
544 case sys::fs::file_magic::macho_dynamic_linker:
545 case sys::fs::file_magic::macho_bundle:
546 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
547 case sys::fs::file_magic::macho_dsym_companion:
548 Dyld = new RuntimeDyldMachO(MM);
550 case sys::fs::file_magic::unknown:
551 case sys::fs::file_magic::bitcode:
552 case sys::fs::file_magic::archive:
553 case sys::fs::file_magic::coff_object:
554 case sys::fs::file_magic::pecoff_executable:
555 case sys::fs::file_magic::macho_universal_binary:
556 case sys::fs::file_magic::windows_resource:
557 report_fatal_error("Incompatible object format!");
560 if (!Dyld->isCompatibleFormat(InputBuffer))
561 report_fatal_error("Incompatible object format!");
564 return Dyld->loadObject(InputBuffer);
567 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
570 return Dyld->getSymbolAddress(Name);
573 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
576 return Dyld->getSymbolLoadAddress(Name);
579 void RuntimeDyld::resolveRelocations() {
580 Dyld->resolveRelocations();
583 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
585 Dyld->reassignSectionAddress(SectionID, Addr);
588 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
589 uint64_t TargetAddress) {
590 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
593 StringRef RuntimeDyld::getErrorString() {
594 return Dyld->getErrorString();
597 void RuntimeDyld::registerEHFrames() {
598 return Dyld->registerEHFrames();
601 } // end namespace llvm