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/MathExtras.h"
21 #include "llvm/Support/Path.h"
24 using namespace llvm::object;
26 // Empty out-of-line virtual destructor as the key function.
27 RTDyldMemoryManager::~RTDyldMemoryManager() {}
28 void RTDyldMemoryManager::registerEHFrames(StringRef SectionData) {}
29 RuntimeDyldImpl::~RuntimeDyldImpl() {}
33 StringRef RuntimeDyldImpl::getEHFrameSection() {
37 // Resolve the relocations for all symbols we currently know about.
38 void RuntimeDyldImpl::resolveRelocations() {
39 // First, resolve relocations associated with external symbols.
40 resolveExternalSymbols();
42 // Just iterate over the sections we have and resolve all the relocations
43 // in them. Gross overkill, but it gets the job done.
44 for (int i = 0, e = Sections.size(); i != e; ++i) {
45 uint64_t Addr = Sections[i].LoadAddress;
46 DEBUG(dbgs() << "Resolving relocations Section #" << i
47 << "\t" << format("%p", (uint8_t *)Addr)
49 resolveRelocationList(Relocations[i], Addr);
53 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
54 uint64_t TargetAddress) {
55 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
56 if (Sections[i].Address == LocalAddress) {
57 reassignSectionAddress(i, TargetAddress);
61 llvm_unreachable("Attempting to remap address of unknown section!");
64 // Subclasses can implement this method to create specialized image instances.
65 // The caller owns the pointer that is returned.
66 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
67 return new ObjectImageCommon(InputBuffer);
70 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
71 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
73 report_fatal_error("Unable to create object image from memory buffer!");
75 Arch = (Triple::ArchType)obj->getArch();
77 // Symbols found in this object
78 StringMap<SymbolLoc> LocalSymbols;
79 // Used sections from the object file
80 ObjSectionToIDMap LocalSections;
82 // Common symbols requiring allocation, with their sizes and alignments
83 CommonSymbolMap CommonSymbols;
84 // Maximum required total memory to allocate all common symbols
85 uint64_t CommonSize = 0;
89 DEBUG(dbgs() << "Parse symbols:\n");
90 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
91 i != e; i.increment(err)) {
93 object::SymbolRef::Type SymType;
95 Check(i->getType(SymType));
96 Check(i->getName(Name));
99 Check(i->getFlags(flags));
101 bool isCommon = flags & SymbolRef::SF_Common;
103 // Add the common symbols to a list. We'll allocate them all below.
105 Check(i->getAlignment(Align));
107 Check(i->getSize(Size));
108 CommonSize += Size + Align;
109 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
111 if (SymType == object::SymbolRef::ST_Function ||
112 SymType == object::SymbolRef::ST_Data ||
113 SymType == object::SymbolRef::ST_Unknown) {
115 StringRef SectionData;
117 section_iterator si = obj->end_sections();
118 Check(i->getFileOffset(FileOffset));
119 Check(i->getSection(si));
120 if (si == obj->end_sections()) continue;
121 Check(si->getContents(SectionData));
122 Check(si->isText(IsCode));
123 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
124 (uintptr_t)FileOffset;
125 uintptr_t SectOffset = (uintptr_t)(SymPtr -
126 (const uint8_t*)SectionData.begin());
127 unsigned SectionID = findOrEmitSection(*obj, *si, IsCode, LocalSections);
128 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
129 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
130 << " flags: " << flags
131 << " SID: " << SectionID
132 << " Offset: " << format("%p", SectOffset));
133 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
136 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
139 // Allocate common symbols
141 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
143 // Parse and process relocations
144 DEBUG(dbgs() << "Parse relocations:\n");
145 for (section_iterator si = obj->begin_sections(),
146 se = obj->end_sections(); si != se; si.increment(err)) {
148 bool isFirstRelocation = true;
149 unsigned SectionID = 0;
152 for (relocation_iterator i = si->begin_relocations(),
153 e = si->end_relocations(); i != e; i.increment(err)) {
156 // If it's the first relocation in this section, find its SectionID
157 if (isFirstRelocation) {
158 SectionID = findOrEmitSection(*obj, *si, true, LocalSections);
159 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
160 isFirstRelocation = false;
163 processRelocationRef(SectionID, *i, *obj, LocalSections, LocalSymbols,
171 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
172 const CommonSymbolMap &CommonSymbols,
174 SymbolTableMap &SymbolTable) {
175 // Allocate memory for the section
176 unsigned SectionID = Sections.size();
177 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
180 report_fatal_error("Unable to allocate memory for common symbols!");
182 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
183 memset(Addr, 0, TotalSize);
185 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
186 << " new addr: " << format("%p", Addr)
187 << " DataSize: " << TotalSize
190 // Assign the address of each symbol
191 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
192 itEnd = CommonSymbols.end(); it != itEnd; it++) {
193 uint64_t Size = it->second.first;
194 uint64_t Align = it->second.second;
196 it->first.getName(Name);
198 // This symbol has an alignment requirement.
199 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
201 Offset += AlignOffset;
202 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
203 format("%p\n", Addr));
205 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
206 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
212 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
213 const SectionRef &Section,
216 unsigned StubBufSize = 0,
217 StubSize = getMaxStubSize();
220 for (relocation_iterator i = Section.begin_relocations(),
221 e = Section.end_relocations(); i != e; i.increment(err), Check(err))
222 StubBufSize += StubSize;
225 uint64_t Alignment64;
226 Check(Section.getContents(data));
227 Check(Section.getAlignment(Alignment64));
229 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
236 Check(Section.isRequiredForExecution(IsRequired));
237 Check(Section.isVirtual(IsVirtual));
238 Check(Section.isZeroInit(IsZeroInit));
239 Check(Section.isReadOnlyData(IsReadOnly));
240 Check(Section.getSize(DataSize));
241 Check(Section.getName(Name));
243 unsigned StubAlignment = getStubAlignment();
244 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
245 if (StubAlignment > EndAlignment)
246 StubBufSize += StubAlignment - EndAlignment;
250 unsigned SectionID = Sections.size();
252 const char *pData = 0;
254 // Some sections, such as debug info, don't need to be loaded for execution.
255 // Leave those where they are.
257 Allocate = DataSize + StubBufSize;
259 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
260 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, IsReadOnly);
262 report_fatal_error("Unable to allocate section memory!");
264 // Virtual sections have no data in the object image, so leave pData = 0
268 // Zero-initialize or copy the data from the image
269 if (IsZeroInit || IsVirtual)
270 memset(Addr, 0, DataSize);
272 memcpy(Addr, pData, DataSize);
274 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
276 << " obj addr: " << format("%p", pData)
277 << " new addr: " << format("%p", Addr)
278 << " DataSize: " << DataSize
279 << " StubBufSize: " << StubBufSize
280 << " Allocate: " << Allocate
282 Obj.updateSectionAddress(Section, (uint64_t)Addr);
285 // Even if we didn't load the section, we need to record an entry for it
286 // to handle later processing (and by 'handle' I mean don't do anything
287 // with these sections).
290 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
292 << " obj addr: " << format("%p", data.data())
294 << " DataSize: " << DataSize
295 << " StubBufSize: " << StubBufSize
296 << " Allocate: " << Allocate
300 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
304 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
305 const SectionRef &Section,
307 ObjSectionToIDMap &LocalSections) {
309 unsigned SectionID = 0;
310 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
311 if (i != LocalSections.end())
312 SectionID = i->second;
314 SectionID = emitSection(Obj, Section, IsCode);
315 LocalSections[Section] = SectionID;
320 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
321 unsigned SectionID) {
322 Relocations[SectionID].push_back(RE);
325 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
326 StringRef SymbolName) {
327 // Relocation by symbol. If the symbol is found in the global symbol table,
328 // create an appropriate section relocation. Otherwise, add it to
329 // ExternalSymbolRelocations.
330 SymbolTableMap::const_iterator Loc =
331 GlobalSymbolTable.find(SymbolName);
332 if (Loc == GlobalSymbolTable.end()) {
333 ExternalSymbolRelocations[SymbolName].push_back(RE);
335 // Copy the RE since we want to modify its addend.
336 RelocationEntry RECopy = RE;
337 RECopy.Addend += Loc->second.second;
338 Relocations[Loc->second.first].push_back(RECopy);
342 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
343 if (Arch == Triple::aarch64) {
344 // This stub has to be able to access the full address space,
345 // since symbol lookup won't necessarily find a handy, in-range,
346 // PLT stub for functions which could be anywhere.
347 uint32_t *StubAddr = (uint32_t*)Addr;
349 // Stub can use ip0 (== x16) to calculate address
350 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
352 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
354 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
356 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
358 *StubAddr = 0xd61f0200; // br ip0
361 } else if (Arch == Triple::arm) {
362 // TODO: There is only ARM far stub now. We should add the Thumb stub,
363 // and stubs for branches Thumb - ARM and ARM - Thumb.
364 uint32_t *StubAddr = (uint32_t*)Addr;
365 *StubAddr = 0xe51ff004; // ldr pc,<label>
366 return (uint8_t*)++StubAddr;
367 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
368 uint32_t *StubAddr = (uint32_t*)Addr;
369 // 0: 3c190000 lui t9,%hi(addr).
370 // 4: 27390000 addiu t9,t9,%lo(addr).
371 // 8: 03200008 jr t9.
373 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
374 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
376 *StubAddr = LuiT9Instr;
378 *StubAddr = AdduiT9Instr;
380 *StubAddr = JrT9Instr;
382 *StubAddr = NopInstr;
384 } else if (Arch == Triple::ppc64) {
385 // PowerPC64 stub: the address points to a function descriptor
386 // instead of the function itself. Load the function address
387 // on r11 and sets it to control register. Also loads the function
388 // TOC in r2 and environment pointer to r11.
389 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
390 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
391 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
392 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
393 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
394 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
395 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
396 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
397 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
398 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
399 writeInt32BE(Addr+40, 0x4E800420); // bctr
402 } else if (Arch == Triple::systemz) {
403 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
404 writeInt16BE(Addr+2, 0x0000);
405 writeInt16BE(Addr+4, 0x0004);
406 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
407 // 8-byte address stored at Addr + 8
413 // Assign an address to a symbol name and resolve all the relocations
414 // associated with it.
415 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
417 // The address to use for relocation resolution is not
418 // the address of the local section buffer. We must be doing
419 // a remote execution environment of some sort. Relocations can't
420 // be applied until all the sections have been moved. The client must
421 // trigger this with a call to MCJIT::finalize() or
422 // RuntimeDyld::resolveRelocations().
424 // Addr is a uint64_t because we can't assume the pointer width
425 // of the target is the same as that of the host. Just use a generic
426 // "big enough" type.
427 Sections[SectionID].LoadAddress = Addr;
430 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
432 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
433 const RelocationEntry &RE = Relocs[i];
434 // Ignore relocations for sections that were not loaded
435 if (Sections[RE.SectionID].Address == 0)
437 resolveRelocation(RE, Value);
441 void RuntimeDyldImpl::resolveExternalSymbols() {
442 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin(),
443 e = ExternalSymbolRelocations.end();
444 for (; i != e; i++) {
445 StringRef Name = i->first();
446 RelocationList &Relocs = i->second;
447 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
448 if (Loc == GlobalSymbolTable.end()) {
449 if (Name.size() == 0) {
450 // This is an absolute symbol, use an address of zero.
451 DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
452 resolveRelocationList(Relocs, 0);
454 // This is an external symbol, try to get its address from
456 uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
458 DEBUG(dbgs() << "Resolving relocations Name: " << Name
459 << "\t" << format("%p", Addr)
461 resolveRelocationList(Relocs, (uintptr_t)Addr);
464 report_fatal_error("Expected external symbol");
470 //===----------------------------------------------------------------------===//
471 // RuntimeDyld class implementation
472 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
473 // FIXME: There's a potential issue lurking here if a single instance of
474 // RuntimeDyld is used to load multiple objects. The current implementation
475 // associates a single memory manager with a RuntimeDyld instance. Even
476 // though the public class spawns a new 'impl' instance for each load,
477 // they share a single memory manager. This can become a problem when page
478 // permissions are applied.
483 RuntimeDyld::~RuntimeDyld() {
487 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
489 sys::LLVMFileType type = sys::IdentifyFileType(
490 InputBuffer->getBufferStart(),
491 static_cast<unsigned>(InputBuffer->getBufferSize()));
493 case sys::ELF_Relocatable_FileType:
494 case sys::ELF_Executable_FileType:
495 case sys::ELF_SharedObject_FileType:
496 case sys::ELF_Core_FileType:
497 Dyld = new RuntimeDyldELF(MM);
499 case sys::Mach_O_Object_FileType:
500 case sys::Mach_O_Executable_FileType:
501 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
502 case sys::Mach_O_Core_FileType:
503 case sys::Mach_O_PreloadExecutable_FileType:
504 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
505 case sys::Mach_O_DynamicLinker_FileType:
506 case sys::Mach_O_Bundle_FileType:
507 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
508 case sys::Mach_O_DSYMCompanion_FileType:
509 Dyld = new RuntimeDyldMachO(MM);
511 case sys::Unknown_FileType:
512 case sys::Bitcode_FileType:
513 case sys::Archive_FileType:
514 case sys::COFF_FileType:
515 report_fatal_error("Incompatible object format!");
518 if (!Dyld->isCompatibleFormat(InputBuffer))
519 report_fatal_error("Incompatible object format!");
522 return Dyld->loadObject(InputBuffer);
525 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
526 return Dyld->getSymbolAddress(Name);
529 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
530 return Dyld->getSymbolLoadAddress(Name);
533 void RuntimeDyld::resolveRelocations() {
534 Dyld->resolveRelocations();
537 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
539 Dyld->reassignSectionAddress(SectionID, Addr);
542 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
543 uint64_t TargetAddress) {
544 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
547 StringRef RuntimeDyld::getErrorString() {
548 return Dyld->getErrorString();
551 StringRef RuntimeDyld::getEHFrameSection() {
552 return Dyld->getEHFrameSection();
555 } // end namespace llvm