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 "ObjectImageCommon.h"
16 #include "RuntimeDyldImpl.h"
17 #include "RuntimeDyldELF.h"
18 #include "RuntimeDyldMachO.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/MathExtras.h"
23 using namespace llvm::object;
25 // Empty out-of-line virtual destructor as the key function.
26 RTDyldMemoryManager::~RTDyldMemoryManager() {}
27 RuntimeDyldImpl::~RuntimeDyldImpl() {}
31 // Resolve the relocations for all symbols we currently know about.
32 void RuntimeDyldImpl::resolveRelocations() {
33 // First, resolve relocations associated with external symbols.
34 resolveExternalSymbols();
36 // Just iterate over the sections we have and resolve all the relocations
37 // in them. Gross overkill, but it gets the job done.
38 for (int i = 0, e = Sections.size(); i != e; ++i) {
39 uint64_t Addr = Sections[i].LoadAddress;
40 DEBUG(dbgs() << "Resolving relocations Section #" << i
41 << "\t" << format("%p", (uint8_t *)Addr)
43 resolveRelocationList(Relocations[i], Addr);
47 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
48 uint64_t TargetAddress) {
49 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
50 if (Sections[i].Address == LocalAddress) {
51 reassignSectionAddress(i, TargetAddress);
55 llvm_unreachable("Attempting to remap address of unknown section!");
58 // Subclasses can implement this method to create specialized image instances.
59 // The caller owns the pointer that is returned.
60 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
61 return new ObjectImageCommon(InputBuffer);
64 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
65 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
67 report_fatal_error("Unable to create object image from memory buffer!");
69 Arch = (Triple::ArchType)obj->getArch();
71 // Symbols found in this object
72 StringMap<SymbolLoc> LocalSymbols;
73 // Used sections from the object file
74 ObjSectionToIDMap LocalSections;
76 // Common symbols requiring allocation, with their sizes and alignments
77 CommonSymbolMap CommonSymbols;
78 // Maximum required total memory to allocate all common symbols
79 uint64_t CommonSize = 0;
83 DEBUG(dbgs() << "Parse symbols:\n");
84 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
85 i != e; i.increment(err)) {
87 object::SymbolRef::Type SymType;
89 Check(i->getType(SymType));
90 Check(i->getName(Name));
93 Check(i->getFlags(flags));
95 bool isCommon = flags & SymbolRef::SF_Common;
97 // Add the common symbols to a list. We'll allocate them all below.
98 uint64_t Align = getCommonSymbolAlignment(*i);
100 Check(i->getSize(Size));
101 CommonSize += Size + Align;
102 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
104 if (SymType == object::SymbolRef::ST_Function ||
105 SymType == object::SymbolRef::ST_Data ||
106 SymType == object::SymbolRef::ST_Unknown) {
108 StringRef SectionData;
109 section_iterator si = obj->end_sections();
110 Check(i->getFileOffset(FileOffset));
111 Check(i->getSection(si));
112 if (si == obj->end_sections()) continue;
113 Check(si->getContents(SectionData));
114 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
115 (uintptr_t)FileOffset;
116 uintptr_t SectOffset = (uintptr_t)(SymPtr -
117 (const uint8_t*)SectionData.begin());
119 findOrEmitSection(*obj,
121 SymType == object::SymbolRef::ST_Function,
123 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
124 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
125 << " flags: " << flags
126 << " SID: " << SectionID
127 << " Offset: " << format("%p", SectOffset));
128 bool isGlobal = flags & SymbolRef::SF_Global;
130 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
133 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
136 // Allocate common symbols
138 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
140 // Parse and process relocations
141 DEBUG(dbgs() << "Parse relocations:\n");
142 for (section_iterator si = obj->begin_sections(),
143 se = obj->end_sections(); si != se; si.increment(err)) {
145 bool isFirstRelocation = true;
146 unsigned SectionID = 0;
149 for (relocation_iterator i = si->begin_relocations(),
150 e = si->end_relocations(); i != e; i.increment(err)) {
153 // If it's the first relocation in this section, find its SectionID
154 if (isFirstRelocation) {
155 SectionID = findOrEmitSection(*obj, *si, true, LocalSections);
156 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
157 isFirstRelocation = false;
160 ObjRelocationInfo RI;
161 RI.SectionID = SectionID;
162 Check(i->getAdditionalInfo(RI.AdditionalInfo));
163 Check(i->getOffset(RI.Offset));
164 Check(i->getSymbol(RI.Symbol));
165 Check(i->getType(RI.Type));
167 DEBUG(dbgs() << "\t\tAddend: " << RI.AdditionalInfo
168 << " Offset: " << format("%p", (uintptr_t)RI.Offset)
169 << " Type: " << (uint32_t)(RI.Type & 0xffffffffL)
171 processRelocationRef(RI, *obj, LocalSections, LocalSymbols, Stubs);
178 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
179 const CommonSymbolMap &CommonSymbols,
181 SymbolTableMap &SymbolTable) {
182 // Allocate memory for the section
183 unsigned SectionID = Sections.size();
184 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
187 report_fatal_error("Unable to allocate memory for common symbols!");
189 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, TotalSize, 0));
190 memset(Addr, 0, TotalSize);
192 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
193 << " new addr: " << format("%p", Addr)
194 << " DataSize: " << TotalSize
197 // Assign the address of each symbol
198 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
199 itEnd = CommonSymbols.end(); it != itEnd; it++) {
200 uint64_t Size = it->second.first;
201 uint64_t Align = it->second.second;
203 it->first.getName(Name);
205 // This symbol has an alignment requirement.
206 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
208 Offset += AlignOffset;
209 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
210 format("%p\n", Addr));
212 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
213 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
219 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
220 const SectionRef &Section,
223 unsigned StubBufSize = 0,
224 StubSize = getMaxStubSize();
227 for (relocation_iterator i = Section.begin_relocations(),
228 e = Section.end_relocations(); i != e; i.increment(err), Check(err))
229 StubBufSize += StubSize;
232 uint64_t Alignment64;
233 Check(Section.getContents(data));
234 Check(Section.getAlignment(Alignment64));
236 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
242 Check(Section.isRequiredForExecution(IsRequired));
243 Check(Section.isVirtual(IsVirtual));
244 Check(Section.isZeroInit(IsZeroInit));
245 Check(Section.getSize(DataSize));
246 Check(Section.getName(Name));
249 unsigned SectionID = Sections.size();
251 const char *pData = 0;
253 // Some sections, such as debug info, don't need to be loaded for execution.
254 // Leave those where they are.
256 Allocate = DataSize + StubBufSize;
258 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
259 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID);
261 report_fatal_error("Unable to allocate section memory!");
263 // Virtual sections have no data in the object image, so leave pData = 0
267 // Zero-initialize or copy the data from the image
268 if (IsZeroInit || IsVirtual)
269 memset(Addr, 0, DataSize);
271 memcpy(Addr, pData, DataSize);
273 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
275 << " obj addr: " << format("%p", pData)
276 << " new addr: " << format("%p", Addr)
277 << " DataSize: " << DataSize
278 << " StubBufSize: " << StubBufSize
279 << " Allocate: " << Allocate
281 Obj.updateSectionAddress(Section, (uint64_t)Addr);
284 // Even if we didn't load the section, we need to record an entry for it
285 // to handle later processing (and by 'handle' I mean don't do anything
286 // with these sections).
289 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
291 << " obj addr: " << format("%p", data.data())
293 << " DataSize: " << DataSize
294 << " StubBufSize: " << StubBufSize
295 << " Allocate: " << Allocate
299 Sections.push_back(SectionEntry(Name, Addr, Allocate, DataSize,
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::arm) {
344 // TODO: There is only ARM far stub now. We should add the Thumb stub,
345 // and stubs for branches Thumb - ARM and ARM - Thumb.
346 uint32_t *StubAddr = (uint32_t*)Addr;
347 *StubAddr = 0xe51ff004; // ldr pc,<label>
348 return (uint8_t*)++StubAddr;
349 } else if (Arch == Triple::mipsel) {
350 uint32_t *StubAddr = (uint32_t*)Addr;
351 // 0: 3c190000 lui t9,%hi(addr).
352 // 4: 27390000 addiu t9,t9,%lo(addr).
353 // 8: 03200008 jr t9.
355 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
356 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
358 *StubAddr = LuiT9Instr;
360 *StubAddr = AdduiT9Instr;
362 *StubAddr = JrT9Instr;
364 *StubAddr = NopInstr;
366 } else if (Arch == Triple::ppc64) {
367 // PowerPC64 stub: the address points to a function descriptor
368 // instead of the function itself. Load the function address
369 // on r11 and sets it to control register. Also loads the function
370 // TOC in r2 and environment pointer to r11.
371 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
372 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
373 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
374 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
375 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
376 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
377 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
378 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
379 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
380 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
381 writeInt32BE(Addr+40, 0x4E800420); // bctr
388 // Assign an address to a symbol name and resolve all the relocations
389 // associated with it.
390 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
392 // The address to use for relocation resolution is not
393 // the address of the local section buffer. We must be doing
394 // a remote execution environment of some sort. Relocations can't
395 // be applied until all the sections have been moved. The client must
396 // trigger this with a call to MCJIT::finalize() or
397 // RuntimeDyld::resolveRelocations().
399 // Addr is a uint64_t because we can't assume the pointer width
400 // of the target is the same as that of the host. Just use a generic
401 // "big enough" type.
402 Sections[SectionID].LoadAddress = Addr;
405 void RuntimeDyldImpl::resolveRelocationEntry(const RelocationEntry &RE,
407 // Ignore relocations for sections that were not loaded
408 if (Sections[RE.SectionID].Address != 0) {
409 DEBUG(dbgs() << "\tSectionID: " << RE.SectionID
410 << " + " << RE.Offset << " ("
411 << format("%p", Sections[RE.SectionID].Address + RE.Offset) << ")"
412 << " RelType: " << RE.RelType
413 << " Addend: " << RE.Addend
416 resolveRelocation(Sections[RE.SectionID], RE.Offset,
417 Value, RE.RelType, RE.Addend);
421 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
423 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
424 resolveRelocationEntry(Relocs[i], Value);
428 void RuntimeDyldImpl::resolveExternalSymbols() {
429 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin(),
430 e = ExternalSymbolRelocations.end();
431 for (; i != e; i++) {
432 StringRef Name = i->first();
433 RelocationList &Relocs = i->second;
434 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
435 if (Loc == GlobalSymbolTable.end()) {
436 // This is an external symbol, try to get it address from
438 uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
440 DEBUG(dbgs() << "Resolving relocations Name: " << Name
441 << "\t" << format("%p", Addr)
443 resolveRelocationList(Relocs, (uintptr_t)Addr);
445 report_fatal_error("Expected external symbol");
451 //===----------------------------------------------------------------------===//
452 // RuntimeDyld class implementation
453 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
458 RuntimeDyld::~RuntimeDyld() {
462 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
464 sys::LLVMFileType type = sys::IdentifyFileType(
465 InputBuffer->getBufferStart(),
466 static_cast<unsigned>(InputBuffer->getBufferSize()));
468 case sys::ELF_Relocatable_FileType:
469 case sys::ELF_Executable_FileType:
470 case sys::ELF_SharedObject_FileType:
471 case sys::ELF_Core_FileType:
472 Dyld = new RuntimeDyldELF(MM);
474 case sys::Mach_O_Object_FileType:
475 case sys::Mach_O_Executable_FileType:
476 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
477 case sys::Mach_O_Core_FileType:
478 case sys::Mach_O_PreloadExecutable_FileType:
479 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
480 case sys::Mach_O_DynamicLinker_FileType:
481 case sys::Mach_O_Bundle_FileType:
482 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
483 case sys::Mach_O_DSYMCompanion_FileType:
484 Dyld = new RuntimeDyldMachO(MM);
486 case sys::Unknown_FileType:
487 case sys::Bitcode_FileType:
488 case sys::Archive_FileType:
489 case sys::COFF_FileType:
490 report_fatal_error("Incompatible object format!");
493 if (!Dyld->isCompatibleFormat(InputBuffer))
494 report_fatal_error("Incompatible object format!");
497 return Dyld->loadObject(InputBuffer);
500 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
501 return Dyld->getSymbolAddress(Name);
504 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
505 return Dyld->getSymbolLoadAddress(Name);
508 void RuntimeDyld::resolveRelocations() {
509 Dyld->resolveRelocations();
512 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
514 Dyld->reassignSectionAddress(SectionID, Addr);
517 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
518 uint64_t TargetAddress) {
519 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
522 StringRef RuntimeDyld::getErrorString() {
523 return Dyld->getErrorString();
526 } // end namespace llvm