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 reassignSectionAddress(i, Sections[i].LoadAddress);
43 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
44 uint64_t TargetAddress) {
45 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
46 if (Sections[i].Address == LocalAddress) {
47 reassignSectionAddress(i, TargetAddress);
51 llvm_unreachable("Attempting to remap address of unknown section!");
54 // Subclasses can implement this method to create specialized image instances.
55 // The caller owns the pointer that is returned.
56 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
57 return new ObjectImageCommon(InputBuffer);
60 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
61 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
63 report_fatal_error("Unable to create object image from memory buffer!");
65 Arch = (Triple::ArchType)obj->getArch();
67 // Symbols found in this object
68 StringMap<SymbolLoc> LocalSymbols;
69 // Used sections from the object file
70 ObjSectionToIDMap LocalSections;
72 // Common symbols requiring allocation, with their sizes and alignments
73 CommonSymbolMap CommonSymbols;
74 // Maximum required total memory to allocate all common symbols
75 uint64_t CommonSize = 0;
79 DEBUG(dbgs() << "Parse symbols:\n");
80 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
81 i != e; i.increment(err)) {
83 object::SymbolRef::Type SymType;
85 Check(i->getType(SymType));
86 Check(i->getName(Name));
89 Check(i->getFlags(flags));
91 bool isCommon = flags & SymbolRef::SF_Common;
93 // Add the common symbols to a list. We'll allocate them all below.
94 uint64_t Align = getCommonSymbolAlignment(*i);
96 Check(i->getSize(Size));
97 CommonSize += Size + Align;
98 CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
100 if (SymType == object::SymbolRef::ST_Function ||
101 SymType == object::SymbolRef::ST_Data ||
102 SymType == object::SymbolRef::ST_Unknown) {
104 StringRef SectionData;
105 section_iterator si = obj->end_sections();
106 Check(i->getFileOffset(FileOffset));
107 Check(i->getSection(si));
108 if (si == obj->end_sections()) continue;
109 Check(si->getContents(SectionData));
110 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
111 (uintptr_t)FileOffset;
112 uintptr_t SectOffset = (uintptr_t)(SymPtr -
113 (const uint8_t*)SectionData.begin());
115 findOrEmitSection(*obj,
117 SymType == object::SymbolRef::ST_Function,
119 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
120 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
121 << " flags: " << flags
122 << " SID: " << SectionID
123 << " Offset: " << format("%p", SectOffset));
124 bool isGlobal = flags & SymbolRef::SF_Global;
126 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
129 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
132 // Allocate common symbols
134 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
136 // Parse and process relocations
137 DEBUG(dbgs() << "Parse relocations:\n");
138 for (section_iterator si = obj->begin_sections(),
139 se = obj->end_sections(); si != se; si.increment(err)) {
141 bool isFirstRelocation = true;
142 unsigned SectionID = 0;
145 for (relocation_iterator i = si->begin_relocations(),
146 e = si->end_relocations(); i != e; i.increment(err)) {
149 // If it's the first relocation in this section, find its SectionID
150 if (isFirstRelocation) {
151 SectionID = findOrEmitSection(*obj, *si, true, LocalSections);
152 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
153 isFirstRelocation = false;
156 ObjRelocationInfo RI;
157 RI.SectionID = SectionID;
158 Check(i->getAdditionalInfo(RI.AdditionalInfo));
159 Check(i->getOffset(RI.Offset));
160 Check(i->getSymbol(RI.Symbol));
161 Check(i->getType(RI.Type));
163 DEBUG(dbgs() << "\t\tAddend: " << RI.AdditionalInfo
164 << " Offset: " << format("%p", (uintptr_t)RI.Offset)
165 << " Type: " << (uint32_t)(RI.Type & 0xffffffffL)
167 processRelocationRef(RI, *obj, LocalSections, LocalSymbols, Stubs);
174 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
175 const CommonSymbolMap &CommonSymbols,
177 SymbolTableMap &SymbolTable) {
178 // Allocate memory for the section
179 unsigned SectionID = Sections.size();
180 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
183 report_fatal_error("Unable to allocate memory for common symbols!");
185 Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, TotalSize, 0));
186 memset(Addr, 0, TotalSize);
188 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
189 << " new addr: " << format("%p", Addr)
190 << " DataSize: " << TotalSize
193 // Assign the address of each symbol
194 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
195 itEnd = CommonSymbols.end(); it != itEnd; it++) {
196 uint64_t Size = it->second.first;
197 uint64_t Align = it->second.second;
199 it->first.getName(Name);
201 // This symbol has an alignment requirement.
202 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
204 Offset += AlignOffset;
205 DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
206 format("0x%x\n", Addr));
208 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
209 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
215 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
216 const SectionRef &Section,
219 unsigned StubBufSize = 0,
220 StubSize = getMaxStubSize();
223 for (relocation_iterator i = Section.begin_relocations(),
224 e = Section.end_relocations(); i != e; i.increment(err), Check(err))
225 StubBufSize += StubSize;
228 uint64_t Alignment64;
229 Check(Section.getContents(data));
230 Check(Section.getAlignment(Alignment64));
232 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
238 Check(Section.isRequiredForExecution(IsRequired));
239 Check(Section.isVirtual(IsVirtual));
240 Check(Section.isZeroInit(IsZeroInit));
241 Check(Section.getSize(DataSize));
242 Check(Section.getName(Name));
245 unsigned SectionID = Sections.size();
247 const char *pData = 0;
249 // Some sections, such as debug info, don't need to be loaded for execution.
250 // Leave those where they are.
252 Allocate = DataSize + StubBufSize;
254 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
255 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID);
257 report_fatal_error("Unable to allocate section memory!");
259 // Virtual sections have no data in the object image, so leave pData = 0
263 // Zero-initialize or copy the data from the image
264 if (IsZeroInit || IsVirtual)
265 memset(Addr, 0, DataSize);
267 memcpy(Addr, pData, DataSize);
269 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
271 << " obj addr: " << format("%p", pData)
272 << " new addr: " << format("%p", Addr)
273 << " DataSize: " << DataSize
274 << " StubBufSize: " << StubBufSize
275 << " Allocate: " << Allocate
277 Obj.updateSectionAddress(Section, (uint64_t)Addr);
280 // Even if we didn't load the section, we need to record an entry for it
281 // to handle later processing (and by 'handle' I mean don't do anything
282 // with these sections).
285 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
287 << " obj addr: " << format("%p", data.data())
289 << " DataSize: " << DataSize
290 << " StubBufSize: " << StubBufSize
291 << " Allocate: " << Allocate
295 Sections.push_back(SectionEntry(Name, Addr, Allocate, DataSize,
300 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
301 const SectionRef &Section,
303 ObjSectionToIDMap &LocalSections) {
305 unsigned SectionID = 0;
306 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
307 if (i != LocalSections.end())
308 SectionID = i->second;
310 SectionID = emitSection(Obj, Section, IsCode);
311 LocalSections[Section] = SectionID;
316 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
317 unsigned SectionID) {
318 Relocations[SectionID].push_back(RE);
321 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
322 StringRef SymbolName) {
323 // Relocation by symbol. If the symbol is found in the global symbol table,
324 // create an appropriate section relocation. Otherwise, add it to
325 // ExternalSymbolRelocations.
326 SymbolTableMap::const_iterator Loc =
327 GlobalSymbolTable.find(SymbolName);
328 if (Loc == GlobalSymbolTable.end()) {
329 ExternalSymbolRelocations[SymbolName].push_back(RE);
331 // Copy the RE since we want to modify its addend.
332 RelocationEntry RECopy = RE;
333 RECopy.Addend += Loc->second.second;
334 Relocations[Loc->second.first].push_back(RECopy);
338 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
339 if (Arch == Triple::arm) {
340 // TODO: There is only ARM far stub now. We should add the Thumb stub,
341 // and stubs for branches Thumb - ARM and ARM - Thumb.
342 uint32_t *StubAddr = (uint32_t*)Addr;
343 *StubAddr = 0xe51ff004; // ldr pc,<label>
344 return (uint8_t*)++StubAddr;
345 } else if (Arch == Triple::mipsel) {
346 uint32_t *StubAddr = (uint32_t*)Addr;
347 // 0: 3c190000 lui t9,%hi(addr).
348 // 4: 27390000 addiu t9,t9,%lo(addr).
349 // 8: 03200008 jr t9.
351 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
352 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
354 *StubAddr = LuiT9Instr;
356 *StubAddr = AdduiT9Instr;
358 *StubAddr = JrT9Instr;
360 *StubAddr = NopInstr;
362 } else if (Arch == Triple::ppc64) {
363 // PowerPC64 stub: the address points to a function descriptor
364 // instead of the function itself. Load the function address
365 // on r11 and sets it to control register. Also loads the function
366 // TOC in r2 and environment pointer to r11.
367 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
368 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
369 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
370 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
371 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
372 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
373 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
374 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
375 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
376 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
377 writeInt32BE(Addr+40, 0x4E800420); // bctr
384 // Assign an address to a symbol name and resolve all the relocations
385 // associated with it.
386 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
388 // The address to use for relocation resolution is not
389 // the address of the local section buffer. We must be doing
390 // a remote execution environment of some sort. Re-apply any
391 // relocations referencing this section with the given address.
393 // Addr is a uint64_t because we can't assume the pointer width
394 // of the target is the same as that of the host. Just use a generic
395 // "big enough" type.
396 Sections[SectionID].LoadAddress = Addr;
397 DEBUG(dbgs() << "Resolving relocations Section #" << SectionID
398 << "\t" << format("%p", (uint8_t *)Addr)
400 resolveRelocationList(Relocations[SectionID], Addr);
403 void RuntimeDyldImpl::resolveRelocationEntry(const RelocationEntry &RE,
405 // Ignore relocations for sections that were not loaded
406 if (Sections[RE.SectionID].Address != 0) {
407 uint8_t *Target = Sections[RE.SectionID].Address + RE.Offset;
408 DEBUG(dbgs() << "\tSectionID: " << RE.SectionID
409 << " + " << RE.Offset << " (" << format("%p", Target) << ")"
410 << " RelType: " << RE.RelType
411 << " Addend: " << RE.Addend
414 resolveRelocation(Target, Sections[RE.SectionID].LoadAddress + RE.Offset,
415 Value, RE.RelType, RE.Addend);
419 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
421 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
422 resolveRelocationEntry(Relocs[i], Value);
426 void RuntimeDyldImpl::resolveExternalSymbols() {
427 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin(),
428 e = ExternalSymbolRelocations.end();
429 for (; i != e; i++) {
430 StringRef Name = i->first();
431 RelocationList &Relocs = i->second;
432 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
433 if (Loc == GlobalSymbolTable.end()) {
434 // This is an external symbol, try to get it address from
436 uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
438 DEBUG(dbgs() << "Resolving relocations Name: " << Name
439 << "\t" << format("%p", Addr)
441 resolveRelocationList(Relocs, (uintptr_t)Addr);
443 report_fatal_error("Expected external symbol");
449 //===----------------------------------------------------------------------===//
450 // RuntimeDyld class implementation
451 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
456 RuntimeDyld::~RuntimeDyld() {
460 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
462 sys::LLVMFileType type = sys::IdentifyFileType(
463 InputBuffer->getBufferStart(),
464 static_cast<unsigned>(InputBuffer->getBufferSize()));
466 case sys::ELF_Relocatable_FileType:
467 case sys::ELF_Executable_FileType:
468 case sys::ELF_SharedObject_FileType:
469 case sys::ELF_Core_FileType:
470 Dyld = new RuntimeDyldELF(MM);
472 case sys::Mach_O_Object_FileType:
473 case sys::Mach_O_Executable_FileType:
474 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
475 case sys::Mach_O_Core_FileType:
476 case sys::Mach_O_PreloadExecutable_FileType:
477 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
478 case sys::Mach_O_DynamicLinker_FileType:
479 case sys::Mach_O_Bundle_FileType:
480 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
481 case sys::Mach_O_DSYMCompanion_FileType:
482 Dyld = new RuntimeDyldMachO(MM);
484 case sys::Unknown_FileType:
485 case sys::Bitcode_FileType:
486 case sys::Archive_FileType:
487 case sys::COFF_FileType:
488 report_fatal_error("Incompatible object format!");
491 if (!Dyld->isCompatibleFormat(InputBuffer))
492 report_fatal_error("Incompatible object format!");
495 return Dyld->loadObject(InputBuffer);
498 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
499 return Dyld->getSymbolAddress(Name);
502 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
503 return Dyld->getSymbolLoadAddress(Name);
506 void RuntimeDyld::resolveRelocations() {
507 Dyld->resolveRelocations();
510 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
512 Dyld->reassignSectionAddress(SectionID, Addr);
515 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
516 uint64_t TargetAddress) {
517 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
520 StringRef RuntimeDyld::getErrorString() {
521 return Dyld->getErrorString();
524 } // end namespace llvm