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/Support/MutexGuard.h"
23 #include "llvm/Object/ELF.h"
26 using namespace llvm::object;
28 // Empty out-of-line virtual destructor as the key function.
29 RuntimeDyldImpl::~RuntimeDyldImpl() {}
33 void RuntimeDyldImpl::registerEHFrames() {
36 void RuntimeDyldImpl::deregisterEHFrames() {
39 // Resolve the relocations for all symbols we currently know about.
40 void RuntimeDyldImpl::resolveRelocations() {
41 MutexGuard locked(lock);
43 // First, resolve relocations associated with external symbols.
44 resolveExternalSymbols();
46 // Just iterate over the sections we have and resolve all the relocations
47 // in them. Gross overkill, but it gets the job done.
48 for (int i = 0, e = Sections.size(); i != e; ++i) {
49 // The Section here (Sections[i]) refers to the section in which the
50 // symbol for the relocation is located. The SectionID in the relocation
51 // entry provides the section to which the relocation will be applied.
52 uint64_t Addr = Sections[i].LoadAddress;
53 DEBUG(dbgs() << "Resolving relocations Section #" << i
54 << "\t" << format("%p", (uint8_t *)Addr)
56 resolveRelocationList(Relocations[i], Addr);
61 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
62 uint64_t TargetAddress) {
63 MutexGuard locked(lock);
64 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
65 if (Sections[i].Address == LocalAddress) {
66 reassignSectionAddress(i, TargetAddress);
70 llvm_unreachable("Attempting to remap address of unknown section!");
73 // Subclasses can implement this method to create specialized image instances.
74 // The caller owns the pointer that is returned.
75 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
76 return new ObjectImageCommon(InputBuffer);
79 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
80 MutexGuard locked(lock);
82 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
84 report_fatal_error("Unable to create object image from memory buffer!");
86 // Save information about our target
87 Arch = (Triple::ArchType)obj->getArch();
88 IsTargetLittleEndian = obj->getObjectFile()->isLittleEndian();
90 // Symbols found in this object
91 StringMap<SymbolLoc> LocalSymbols;
92 // Used sections from the object file
93 ObjSectionToIDMap LocalSections;
95 // Common symbols requiring allocation, with their sizes and alignments
96 CommonSymbolMap CommonSymbols;
97 // Maximum required total memory to allocate all common symbols
98 uint64_t CommonSize = 0;
102 DEBUG(dbgs() << "Parse symbols:\n");
103 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
104 i != e; i.increment(err)) {
106 object::SymbolRef::Type SymType;
108 Check(i->getType(SymType));
109 Check(i->getName(Name));
112 Check(i->getFlags(flags));
114 bool isCommon = flags & SymbolRef::SF_Common;
116 // Add the common symbols to a list. We'll allocate them all below.
118 Check(i->getAlignment(Align));
120 Check(i->getSize(Size));
121 CommonSize += Size + Align;
122 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
124 if (SymType == object::SymbolRef::ST_Function ||
125 SymType == object::SymbolRef::ST_Data ||
126 SymType == object::SymbolRef::ST_Unknown) {
128 StringRef SectionData;
130 section_iterator si = obj->end_sections();
131 Check(i->getFileOffset(FileOffset));
132 Check(i->getSection(si));
133 if (si == obj->end_sections()) continue;
134 Check(si->getContents(SectionData));
135 Check(si->isText(IsCode));
136 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
137 (uintptr_t)FileOffset;
138 uintptr_t SectOffset = (uintptr_t)(SymPtr -
139 (const uint8_t*)SectionData.begin());
140 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
141 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
142 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
143 << " flags: " << flags
144 << " SID: " << SectionID
145 << " Offset: " << format("%p", SectOffset));
146 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
149 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
152 // Allocate common symbols
154 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
156 // Parse and process relocations
157 DEBUG(dbgs() << "Parse relocations:\n");
158 for (section_iterator si = obj->begin_sections(),
159 se = obj->end_sections(); si != se; si.increment(err)) {
161 bool isFirstRelocation = true;
162 unsigned SectionID = 0;
164 section_iterator RelocatedSection = si->getRelocatedSection();
166 for (relocation_iterator i = si->begin_relocations(),
167 e = si->end_relocations(); i != e; i.increment(err)) {
170 // If it's the first relocation in this section, find its SectionID
171 if (isFirstRelocation) {
173 findOrEmitSection(*obj, *RelocatedSection, true, LocalSections);
174 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
175 isFirstRelocation = false;
178 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
183 // Give the subclasses a chance to tie-up any loose ends.
184 finalizeLoad(LocalSections);
189 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
190 const CommonSymbolMap &CommonSymbols,
192 SymbolTableMap &SymbolTable) {
193 // Allocate memory for the section
194 unsigned SectionID = Sections.size();
195 uint8_t *Addr = MemMgr->allocateDataSection(
196 TotalSize, sizeof(void*), SectionID, StringRef(), false);
198 report_fatal_error("Unable to allocate memory for common symbols!");
200 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
201 memset(Addr, 0, TotalSize);
203 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
204 << " new addr: " << format("%p", Addr)
205 << " DataSize: " << TotalSize
208 // Assign the address of each symbol
209 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
210 itEnd = CommonSymbols.end(); it != itEnd; it++) {
211 uint64_t Size = it->second.first;
212 uint64_t Align = it->second.second;
214 it->first.getName(Name);
216 // This symbol has an alignment requirement.
217 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
219 Offset += AlignOffset;
220 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
221 format("%p\n", Addr));
223 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
224 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
230 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
231 const SectionRef &Section,
234 unsigned StubBufSize = 0,
235 StubSize = getMaxStubSize();
237 const ObjectFile *ObjFile = Obj.getObjectFile();
238 // FIXME: this is an inefficient way to handle this. We should computed the
239 // necessary section allocation size in loadObject by walking all the sections
242 for (section_iterator SI = ObjFile->begin_sections(),
243 SE = ObjFile->end_sections();
244 SI != SE; SI.increment(err), Check(err)) {
245 section_iterator RelSecI = SI->getRelocatedSection();
246 if (!(RelSecI == Section))
249 for (relocation_iterator I = SI->begin_relocations(),
250 E = SI->end_relocations(); I != E; I.increment(err), Check(err)) {
251 StubBufSize += StubSize;
257 uint64_t Alignment64;
258 Check(Section.getContents(data));
259 Check(Section.getAlignment(Alignment64));
261 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
267 unsigned PaddingSize = 0;
269 Check(Section.isRequiredForExecution(IsRequired));
270 Check(Section.isVirtual(IsVirtual));
271 Check(Section.isZeroInit(IsZeroInit));
272 Check(Section.isReadOnlyData(IsReadOnly));
273 Check(Section.getSize(DataSize));
274 Check(Section.getName(Name));
276 unsigned StubAlignment = getStubAlignment();
277 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
278 if (StubAlignment > EndAlignment)
279 StubBufSize += StubAlignment - EndAlignment;
282 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
283 // with zeroes added at the end. For MachO objects, this section has a
284 // slightly different name, so this won't have any effect for MachO objects.
285 if (Name == ".eh_frame")
289 unsigned SectionID = Sections.size();
291 const char *pData = 0;
293 // Some sections, such as debug info, don't need to be loaded for execution.
294 // Leave those where they are.
296 Allocate = DataSize + PaddingSize + StubBufSize;
298 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
299 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
302 report_fatal_error("Unable to allocate section memory!");
304 // Virtual sections have no data in the object image, so leave pData = 0
308 // Zero-initialize or copy the data from the image
309 if (IsZeroInit || IsVirtual)
310 memset(Addr, 0, DataSize);
312 memcpy(Addr, pData, DataSize);
314 // Fill in any extra bytes we allocated for padding
315 if (PaddingSize != 0) {
316 memset(Addr + DataSize, 0, PaddingSize);
317 // Update the DataSize variable so that the stub offset is set correctly.
318 DataSize += PaddingSize;
321 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
323 << " obj addr: " << format("%p", pData)
324 << " new addr: " << format("%p", Addr)
325 << " DataSize: " << DataSize
326 << " StubBufSize: " << StubBufSize
327 << " Allocate: " << Allocate
329 Obj.updateSectionAddress(Section, (uint64_t)Addr);
332 // Even if we didn't load the section, we need to record an entry for it
333 // to handle later processing (and by 'handle' I mean don't do anything
334 // with these sections).
337 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
339 << " obj addr: " << format("%p", data.data())
341 << " DataSize: " << DataSize
342 << " StubBufSize: " << StubBufSize
343 << " Allocate: " << Allocate
347 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
351 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
352 const SectionRef &Section,
354 ObjSectionToIDMap &LocalSections) {
356 unsigned SectionID = 0;
357 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
358 if (i != LocalSections.end())
359 SectionID = i->second;
361 SectionID = emitSection(Obj, Section, IsCode);
362 LocalSections[Section] = SectionID;
367 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
368 unsigned SectionID) {
369 Relocations[SectionID].push_back(RE);
372 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
373 StringRef SymbolName) {
374 // Relocation by symbol. If the symbol is found in the global symbol table,
375 // create an appropriate section relocation. Otherwise, add it to
376 // ExternalSymbolRelocations.
377 SymbolTableMap::const_iterator Loc =
378 GlobalSymbolTable.find(SymbolName);
379 if (Loc == GlobalSymbolTable.end()) {
380 ExternalSymbolRelocations[SymbolName].push_back(RE);
382 // Copy the RE since we want to modify its addend.
383 RelocationEntry RECopy = RE;
384 RECopy.Addend += Loc->second.second;
385 Relocations[Loc->second.first].push_back(RECopy);
389 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
390 if (Arch == Triple::aarch64) {
391 // This stub has to be able to access the full address space,
392 // since symbol lookup won't necessarily find a handy, in-range,
393 // PLT stub for functions which could be anywhere.
394 uint32_t *StubAddr = (uint32_t*)Addr;
396 // Stub can use ip0 (== x16) to calculate address
397 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
399 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
401 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
403 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
405 *StubAddr = 0xd61f0200; // br ip0
408 } else if (Arch == Triple::arm) {
409 // TODO: There is only ARM far stub now. We should add the Thumb stub,
410 // and stubs for branches Thumb - ARM and ARM - Thumb.
411 uint32_t *StubAddr = (uint32_t*)Addr;
412 *StubAddr = 0xe51ff004; // ldr pc,<label>
413 return (uint8_t*)++StubAddr;
414 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
415 uint32_t *StubAddr = (uint32_t*)Addr;
416 // 0: 3c190000 lui t9,%hi(addr).
417 // 4: 27390000 addiu t9,t9,%lo(addr).
418 // 8: 03200008 jr t9.
420 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
421 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
423 *StubAddr = LuiT9Instr;
425 *StubAddr = AdduiT9Instr;
427 *StubAddr = JrT9Instr;
429 *StubAddr = NopInstr;
431 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
432 // PowerPC64 stub: the address points to a function descriptor
433 // instead of the function itself. Load the function address
434 // on r11 and sets it to control register. Also loads the function
435 // TOC in r2 and environment pointer to r11.
436 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
437 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
438 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
439 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
440 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
441 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
442 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
443 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
444 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
445 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
446 writeInt32BE(Addr+40, 0x4E800420); // bctr
449 } else if (Arch == Triple::systemz) {
450 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
451 writeInt16BE(Addr+2, 0x0000);
452 writeInt16BE(Addr+4, 0x0004);
453 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
454 // 8-byte address stored at Addr + 8
456 } else if (Arch == Triple::x86_64) {
458 *(Addr+1) = 0x25; // rip
459 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
464 // Assign an address to a symbol name and resolve all the relocations
465 // associated with it.
466 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
468 // The address to use for relocation resolution is not
469 // the address of the local section buffer. We must be doing
470 // a remote execution environment of some sort. Relocations can't
471 // be applied until all the sections have been moved. The client must
472 // trigger this with a call to MCJIT::finalize() or
473 // RuntimeDyld::resolveRelocations().
475 // Addr is a uint64_t because we can't assume the pointer width
476 // of the target is the same as that of the host. Just use a generic
477 // "big enough" type.
478 Sections[SectionID].LoadAddress = Addr;
481 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
483 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
484 const RelocationEntry &RE = Relocs[i];
485 // Ignore relocations for sections that were not loaded
486 if (Sections[RE.SectionID].Address == 0)
488 resolveRelocation(RE, Value);
492 void RuntimeDyldImpl::resolveExternalSymbols() {
493 while(!ExternalSymbolRelocations.empty()) {
494 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
496 StringRef Name = i->first();
497 RelocationList &Relocs = i->second;
498 if (Name.size() == 0) {
499 // This is an absolute symbol, use an address of zero.
500 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
501 resolveRelocationList(Relocs, 0);
504 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
505 if (Loc == GlobalSymbolTable.end()) {
506 // This is an external symbol, try to get its address from
508 Addr = MemMgr->getSymbolAddress(Name.data());
510 // We found the symbol in our global table. It was probably in a
511 // Module that we loaded previously.
512 SymbolLoc SymLoc = Loc->second;
513 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
516 // FIXME: Implement error handling that doesn't kill the host program!
518 report_fatal_error("Program used external function '" + Name +
519 "' which could not be resolved!");
521 updateGOTEntries(Name, Addr);
522 DEBUG(dbgs() << "Resolving relocations Name: " << Name
523 << "\t" << format("0x%lx", Addr)
525 resolveRelocationList(Relocs, Addr);
528 ExternalSymbolRelocations.erase(i->first());
533 //===----------------------------------------------------------------------===//
534 // RuntimeDyld class implementation
535 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
536 // FIXME: There's a potential issue lurking here if a single instance of
537 // RuntimeDyld is used to load multiple objects. The current implementation
538 // associates a single memory manager with a RuntimeDyld instance. Even
539 // though the public class spawns a new 'impl' instance for each load,
540 // they share a single memory manager. This can become a problem when page
541 // permissions are applied.
546 RuntimeDyld::~RuntimeDyld() {
550 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
552 sys::fs::file_magic Type =
553 sys::fs::identify_magic(InputBuffer->getBuffer());
555 case sys::fs::file_magic::elf_relocatable:
556 case sys::fs::file_magic::elf_executable:
557 case sys::fs::file_magic::elf_shared_object:
558 case sys::fs::file_magic::elf_core:
559 Dyld = new RuntimeDyldELF(MM);
561 case sys::fs::file_magic::macho_object:
562 case sys::fs::file_magic::macho_executable:
563 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
564 case sys::fs::file_magic::macho_core:
565 case sys::fs::file_magic::macho_preload_executable:
566 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
567 case sys::fs::file_magic::macho_dynamic_linker:
568 case sys::fs::file_magic::macho_bundle:
569 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
570 case sys::fs::file_magic::macho_dsym_companion:
571 Dyld = new RuntimeDyldMachO(MM);
573 case sys::fs::file_magic::unknown:
574 case sys::fs::file_magic::bitcode:
575 case sys::fs::file_magic::archive:
576 case sys::fs::file_magic::coff_object:
577 case sys::fs::file_magic::pecoff_executable:
578 case sys::fs::file_magic::macho_universal_binary:
579 case sys::fs::file_magic::windows_resource:
580 report_fatal_error("Incompatible object format!");
583 if (!Dyld->isCompatibleFormat(InputBuffer))
584 report_fatal_error("Incompatible object format!");
587 return Dyld->loadObject(InputBuffer);
590 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
593 return Dyld->getSymbolAddress(Name);
596 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
599 return Dyld->getSymbolLoadAddress(Name);
602 void RuntimeDyld::resolveRelocations() {
603 Dyld->resolveRelocations();
606 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
608 Dyld->reassignSectionAddress(SectionID, Addr);
611 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
612 uint64_t TargetAddress) {
613 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
616 StringRef RuntimeDyld::getErrorString() {
617 return Dyld->getErrorString();
620 void RuntimeDyld::registerEHFrames() {
622 Dyld->registerEHFrames();
625 void RuntimeDyld::deregisterEHFrames() {
627 Dyld->deregisterEHFrames();
630 } // end namespace llvm