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"
22 using namespace llvm::object;
24 // Empty out-of-line virtual destructor as the key function.
25 RTDyldMemoryManager::~RTDyldMemoryManager() {}
26 RuntimeDyldImpl::~RuntimeDyldImpl() {}
31 // Helper for extensive error checking in debug builds.
32 error_code Check(error_code Err) {
34 report_fatal_error(Err.message());
38 } // end anonymous namespace
40 // Resolve the relocations for all symbols we currently know about.
41 void RuntimeDyldImpl::resolveRelocations() {
42 // First, resolve relocations associated with external symbols.
43 resolveExternalSymbols();
45 // Just iterate over the sections we have and resolve all the relocations
46 // in them. Gross overkill, but it gets the job done.
47 for (int i = 0, e = Sections.size(); i != e; ++i) {
48 reassignSectionAddress(i, Sections[i].LoadAddress);
52 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
53 uint64_t TargetAddress) {
54 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
55 if (Sections[i].Address == LocalAddress) {
56 reassignSectionAddress(i, TargetAddress);
60 llvm_unreachable("Attempting to remap address of unknown section!");
63 // Subclasses can implement this method to create specialized image instances.
64 // The caller owns the pointer that is returned.
65 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
66 return new ObjectImageCommon(InputBuffer);
69 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
70 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
72 report_fatal_error("Unable to create object image from memory buffer!");
74 Arch = (Triple::ArchType)obj->getArch();
76 // Symbols found in this object
77 StringMap<SymbolLoc> LocalSymbols;
78 // Used sections from the object file
79 ObjSectionToIDMap LocalSections;
81 // Common symbols requiring allocation, and the total size required to
82 // allocate all common symbols.
83 CommonSymbolMap CommonSymbols;
84 uint64_t CommonSize = 0;
88 DEBUG(dbgs() << "Parse symbols:\n");
89 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
90 i != e; i.increment(err)) {
92 object::SymbolRef::Type SymType;
94 Check(i->getType(SymType));
95 Check(i->getName(Name));
98 Check(i->getFlags(flags));
100 bool isCommon = flags & SymbolRef::SF_Common;
102 // Add the common symbols to a list. We'll allocate them all below.
104 Check(i->getSize(Size));
106 CommonSymbols[*i] = Size;
108 if (SymType == object::SymbolRef::ST_Function ||
109 SymType == object::SymbolRef::ST_Data ||
110 SymType == object::SymbolRef::ST_Unknown) {
112 StringRef SectionData;
113 section_iterator si = obj->end_sections();
114 Check(i->getFileOffset(FileOffset));
115 Check(i->getSection(si));
116 if (si == obj->end_sections()) continue;
117 Check(si->getContents(SectionData));
118 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
119 (uintptr_t)FileOffset;
120 uintptr_t SectOffset = (uintptr_t)(SymPtr -
121 (const uint8_t*)SectionData.begin());
123 findOrEmitSection(*obj,
125 SymType == object::SymbolRef::ST_Function,
127 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
128 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
129 << " flags: " << flags
130 << " SID: " << SectionID
131 << " Offset: " << format("%p", SectOffset));
132 bool isGlobal = flags & SymbolRef::SF_Global;
134 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
137 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
140 // Allocate common symbols
142 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
144 // Parse and process relocations
145 DEBUG(dbgs() << "Parse relocations:\n");
146 for (section_iterator si = obj->begin_sections(),
147 se = obj->end_sections(); si != se; si.increment(err)) {
149 bool isFirstRelocation = true;
150 unsigned SectionID = 0;
153 for (relocation_iterator i = si->begin_relocations(),
154 e = si->end_relocations(); i != e; i.increment(err)) {
157 // If it's the first relocation in this section, find its SectionID
158 if (isFirstRelocation) {
159 SectionID = findOrEmitSection(*obj, *si, true, LocalSections);
160 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
161 isFirstRelocation = false;
164 ObjRelocationInfo RI;
165 RI.SectionID = SectionID;
166 Check(i->getAdditionalInfo(RI.AdditionalInfo));
167 Check(i->getOffset(RI.Offset));
168 Check(i->getSymbol(RI.Symbol));
169 Check(i->getType(RI.Type));
171 DEBUG(dbgs() << "\t\tAddend: " << RI.AdditionalInfo
172 << " Offset: " << format("%p", (uintptr_t)RI.Offset)
173 << " Type: " << (uint32_t)(RI.Type & 0xffffffffL)
175 processRelocationRef(RI, *obj, LocalSections, LocalSymbols, Stubs);
182 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
183 const CommonSymbolMap &CommonSymbols,
185 SymbolTableMap &SymbolTable) {
186 // Allocate memory for the section
187 unsigned SectionID = Sections.size();
188 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
191 report_fatal_error("Unable to allocate memory for common symbols!");
193 Sections.push_back(SectionEntry(Addr, TotalSize, TotalSize, 0));
194 memset(Addr, 0, TotalSize);
196 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
197 << " new addr: " << format("%p", Addr)
198 << " DataSize: " << TotalSize
201 // Assign the address of each symbol
202 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
203 itEnd = CommonSymbols.end(); it != itEnd; it++) {
205 it->first.getName(Name);
206 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
207 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
208 uint64_t Size = it->second;
214 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
215 const SectionRef &Section,
218 unsigned StubBufSize = 0,
219 StubSize = getMaxStubSize();
222 for (relocation_iterator i = Section.begin_relocations(),
223 e = Section.end_relocations(); i != e; i.increment(err), Check(err))
224 StubBufSize += StubSize;
227 uint64_t Alignment64;
228 Check(Section.getContents(data));
229 Check(Section.getAlignment(Alignment64));
231 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
236 Check(Section.isRequiredForExecution(IsRequired));
237 Check(Section.isVirtual(IsVirtual));
238 Check(Section.isZeroInit(IsZeroInit));
239 Check(Section.getSize(DataSize));
242 unsigned SectionID = Sections.size();
244 const char *pData = 0;
246 // Some sections, such as debug info, don't need to be loaded for execution.
247 // Leave those where they are.
249 Allocate = DataSize + StubBufSize;
251 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
252 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID);
254 report_fatal_error("Unable to allocate section memory!");
256 // Virtual sections have no data in the object image, so leave pData = 0
260 // Zero-initialize or copy the data from the image
261 if (IsZeroInit || IsVirtual)
262 memset(Addr, 0, DataSize);
264 memcpy(Addr, pData, DataSize);
266 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
267 << " obj addr: " << format("%p", pData)
268 << " new addr: " << format("%p", Addr)
269 << " DataSize: " << DataSize
270 << " StubBufSize: " << StubBufSize
271 << " Allocate: " << Allocate
273 Obj.updateSectionAddress(Section, (uint64_t)Addr);
276 // Even if we didn't load the section, we need to record an entry for it
277 // to handle later processing (and by 'handle' I mean don't do anything
278 // with these sections).
281 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
282 << " obj addr: " << format("%p", data.data())
284 << " DataSize: " << DataSize
285 << " StubBufSize: " << StubBufSize
286 << " Allocate: " << Allocate
290 Sections.push_back(SectionEntry(Addr, Allocate, DataSize,(uintptr_t)pData));
294 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
295 const SectionRef &Section,
297 ObjSectionToIDMap &LocalSections) {
299 unsigned SectionID = 0;
300 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
301 if (i != LocalSections.end())
302 SectionID = i->second;
304 SectionID = emitSection(Obj, Section, IsCode);
305 LocalSections[Section] = SectionID;
310 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
311 unsigned SectionID) {
312 Relocations[SectionID].push_back(RE);
315 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
316 StringRef SymbolName) {
317 // Relocation by symbol. If the symbol is found in the global symbol table,
318 // create an appropriate section relocation. Otherwise, add it to
319 // ExternalSymbolRelocations.
320 SymbolTableMap::const_iterator Loc =
321 GlobalSymbolTable.find(SymbolName);
322 if (Loc == GlobalSymbolTable.end()) {
323 ExternalSymbolRelocations[SymbolName].push_back(RE);
325 // Copy the RE since we want to modify its addend.
326 RelocationEntry RECopy = RE;
327 RECopy.Addend += Loc->second.second;
328 Relocations[Loc->second.first].push_back(RECopy);
332 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
333 if (Arch == Triple::arm) {
334 // TODO: There is only ARM far stub now. We should add the Thumb stub,
335 // and stubs for branches Thumb - ARM and ARM - Thumb.
336 uint32_t *StubAddr = (uint32_t*)Addr;
337 *StubAddr = 0xe51ff004; // ldr pc,<label>
338 return (uint8_t*)++StubAddr;
339 } else if (Arch == Triple::mipsel) {
340 uint32_t *StubAddr = (uint32_t*)Addr;
341 // 0: 3c190000 lui t9,%hi(addr).
342 // 4: 27390000 addiu t9,t9,%lo(addr).
343 // 8: 03200008 jr t9.
345 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
346 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
348 *StubAddr = LuiT9Instr;
350 *StubAddr = AdduiT9Instr;
352 *StubAddr = JrT9Instr;
354 *StubAddr = NopInstr;
360 // Assign an address to a symbol name and resolve all the relocations
361 // associated with it.
362 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
364 // The address to use for relocation resolution is not
365 // the address of the local section buffer. We must be doing
366 // a remote execution environment of some sort. Re-apply any
367 // relocations referencing this section with the given address.
369 // Addr is a uint64_t because we can't assume the pointer width
370 // of the target is the same as that of the host. Just use a generic
371 // "big enough" type.
372 Sections[SectionID].LoadAddress = Addr;
373 DEBUG(dbgs() << "Resolving relocations Section #" << SectionID
374 << "\t" << format("%p", (uint8_t *)Addr)
376 resolveRelocationList(Relocations[SectionID], Addr);
379 void RuntimeDyldImpl::resolveRelocationEntry(const RelocationEntry &RE,
381 // Ignore relocations for sections that were not loaded
382 if (Sections[RE.SectionID].Address != 0) {
383 uint8_t *Target = Sections[RE.SectionID].Address + RE.Offset;
384 DEBUG(dbgs() << "\tSectionID: " << RE.SectionID
385 << " + " << RE.Offset << " (" << format("%p", Target) << ")"
386 << " RelType: " << RE.RelType
387 << " Addend: " << RE.Addend
390 resolveRelocation(Target, Sections[RE.SectionID].LoadAddress + RE.Offset,
391 Value, RE.RelType, RE.Addend);
395 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
397 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
398 resolveRelocationEntry(Relocs[i], Value);
402 void RuntimeDyldImpl::resolveExternalSymbols() {
403 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin(),
404 e = ExternalSymbolRelocations.end();
405 for (; i != e; i++) {
406 StringRef Name = i->first();
407 RelocationList &Relocs = i->second;
408 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
409 if (Loc == GlobalSymbolTable.end()) {
410 // This is an external symbol, try to get it address from
412 uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
414 DEBUG(dbgs() << "Resolving relocations Name: " << Name
415 << "\t" << format("%p", Addr)
417 resolveRelocationList(Relocs, (uintptr_t)Addr);
419 report_fatal_error("Expected external symbol");
425 //===----------------------------------------------------------------------===//
426 // RuntimeDyld class implementation
427 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
432 RuntimeDyld::~RuntimeDyld() {
436 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
438 sys::LLVMFileType type = sys::IdentifyFileType(
439 InputBuffer->getBufferStart(),
440 static_cast<unsigned>(InputBuffer->getBufferSize()));
442 case sys::ELF_Relocatable_FileType:
443 case sys::ELF_Executable_FileType:
444 case sys::ELF_SharedObject_FileType:
445 case sys::ELF_Core_FileType:
446 Dyld = new RuntimeDyldELF(MM);
448 case sys::Mach_O_Object_FileType:
449 case sys::Mach_O_Executable_FileType:
450 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
451 case sys::Mach_O_Core_FileType:
452 case sys::Mach_O_PreloadExecutable_FileType:
453 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
454 case sys::Mach_O_DynamicLinker_FileType:
455 case sys::Mach_O_Bundle_FileType:
456 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
457 case sys::Mach_O_DSYMCompanion_FileType:
458 Dyld = new RuntimeDyldMachO(MM);
460 case sys::Unknown_FileType:
461 case sys::Bitcode_FileType:
462 case sys::Archive_FileType:
463 case sys::COFF_FileType:
464 report_fatal_error("Incompatible object format!");
467 if (!Dyld->isCompatibleFormat(InputBuffer))
468 report_fatal_error("Incompatible object format!");
471 return Dyld->loadObject(InputBuffer);
474 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
475 return Dyld->getSymbolAddress(Name);
478 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
479 return Dyld->getSymbolLoadAddress(Name);
482 void RuntimeDyld::resolveRelocations() {
483 Dyld->resolveRelocations();
486 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
488 Dyld->reassignSectionAddress(SectionID, Addr);
491 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
492 uint64_t TargetAddress) {
493 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
496 StringRef RuntimeDyld::getErrorString() {
497 return Dyld->getErrorString();
500 } // end namespace llvm