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 "RuntimeDyldImpl.h"
16 #include "RuntimeDyldELF.h"
17 #include "RuntimeDyldMachO.h"
18 #include "llvm/Support/Path.h"
21 using namespace llvm::object;
23 // Empty out-of-line virtual destructor as the key function.
24 RTDyldMemoryManager::~RTDyldMemoryManager() {}
25 RuntimeDyldImpl::~RuntimeDyldImpl() {}
30 // Helper for extensive error checking in debug builds.
31 error_code Check(error_code Err) {
33 report_fatal_error(Err.message());
37 } // end anonymous namespace
39 // Resolve the relocations for all symbols we currently know about.
40 void RuntimeDyldImpl::resolveRelocations() {
41 // First, resolve relocations associated with external symbols.
44 // Just iterate over the sections we have and resolve all the relocations
45 // in them. Gross overkill, but it gets the job done.
46 for (int i = 0, e = Sections.size(); i != e; ++i) {
47 reassignSectionAddress(i, Sections[i].LoadAddress);
51 void RuntimeDyldImpl::mapSectionAddress(void *LocalAddress,
52 uint64_t TargetAddress) {
53 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
54 if (Sections[i].Address == LocalAddress) {
55 reassignSectionAddress(i, TargetAddress);
59 llvm_unreachable("Attempting to remap address of unknown section!");
62 bool RuntimeDyldImpl::loadObject(const MemoryBuffer *InputBuffer) {
63 // FIXME: ObjectFile don't modify MemoryBuffer.
64 // It should use const MemoryBuffer as parameter.
65 OwningPtr<ObjectFile> obj(ObjectFile::createObjectFile(
66 const_cast<MemoryBuffer*>(InputBuffer)));
68 report_fatal_error("Unable to create object image from memory buffer!");
70 Arch = (Triple::ArchType)obj->getArch();
72 LocalSymbolMap LocalSymbols; // Functions and data symbols from the
74 ObjSectionToIDMap LocalSections; // Used sections from the object file
75 CommonSymbolMap CommonSymbols; // Common symbols requiring allocation
76 uint64_t CommonSize = 0;
80 DEBUG(dbgs() << "Parse symbols:\n");
81 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
82 i != e; i.increment(err)) {
84 object::SymbolRef::Type SymType;
86 Check(i->getType(SymType));
87 Check(i->getName(Name));
90 Check(i->getFlags(flags));
92 bool isCommon = flags & SymbolRef::SF_Common;
94 // Add the common symbols to a list. We'll allocate them all below.
96 Check(i->getSize(Size));
98 CommonSymbols[*i] = Size;
100 if (SymType == object::SymbolRef::ST_Function ||
101 SymType == object::SymbolRef::ST_Data) {
104 section_iterator si = obj->end_sections();
105 Check(i->getFileOffset(FileOffset));
106 Check(i->getSection(si));
107 if (si == obj->end_sections()) continue;
108 Check(si->getContents(sData));
109 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
110 (uintptr_t)FileOffset;
111 uintptr_t SectOffset = (uintptr_t)(SymPtr - (const uint8_t*)sData.begin());
113 findOrEmitSection(*si,
114 SymType == object::SymbolRef::ST_Function,
116 bool isGlobal = flags & SymbolRef::SF_Global;
117 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
118 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
119 << " flags: " << flags
120 << " SID: " << SectionID
121 << " Offset: " << format("%p", SectOffset));
123 SymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
126 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
129 // Allocate common symbols
131 emitCommonSymbols(CommonSymbols, CommonSize, LocalSymbols);
133 // Parse and proccess relocations
134 DEBUG(dbgs() << "Parse relocations:\n");
135 for (section_iterator si = obj->begin_sections(),
136 se = obj->end_sections(); si != se; si.increment(err)) {
138 bool isFirstRelocation = true;
139 unsigned SectionID = 0;
142 for (relocation_iterator i = si->begin_relocations(),
143 e = si->end_relocations(); i != e; i.increment(err)) {
146 // If it's first relocation in this section, find its SectionID
147 if (isFirstRelocation) {
148 SectionID = findOrEmitSection(*si, true, LocalSections);
149 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
150 isFirstRelocation = false;
153 ObjRelocationInfo RI;
154 RI.SectionID = SectionID;
155 Check(i->getAdditionalInfo(RI.AdditionalInfo));
156 Check(i->getOffset(RI.Offset));
157 Check(i->getSymbol(RI.Symbol));
158 Check(i->getType(RI.Type));
160 DEBUG(dbgs() << "\t\tAddend: " << RI.AdditionalInfo
161 << " Offset: " << format("%p", (uintptr_t)RI.Offset)
162 << " Type: " << (uint32_t)(RI.Type & 0xffffffffL)
164 processRelocationRef(RI, *obj, LocalSections, LocalSymbols, Stubs);
170 unsigned RuntimeDyldImpl::emitCommonSymbols(const CommonSymbolMap &Map,
172 LocalSymbolMap &LocalSymbols) {
173 // Allocate memory for the section
174 unsigned SectionID = Sections.size();
175 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
178 report_fatal_error("Unable to allocate memory for common symbols!");
180 Sections.push_back(SectionEntry(Addr, TotalSize, TotalSize, 0));
181 memset(Addr, 0, TotalSize);
183 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
184 << " new addr: " << format("%p", Addr)
185 << " DataSize: " << TotalSize
188 // Assign the address of each symbol
189 for (CommonSymbolMap::const_iterator it = Map.begin(), itEnd = Map.end();
191 uint64_t Size = it->second;
193 it->first.getName(Name);
194 LocalSymbols[Name.data()] = SymbolLoc(SectionID, Offset);
202 unsigned RuntimeDyldImpl::emitSection(const SectionRef &Section,
205 unsigned StubBufSize = 0,
206 StubSize = getMaxStubSize();
209 for (relocation_iterator i = Section.begin_relocations(),
210 e = Section.end_relocations(); i != e; i.increment(err), Check(err))
211 StubBufSize += StubSize;
214 uint64_t Alignment64;
215 Check(Section.getContents(data));
216 Check(Section.getAlignment(Alignment64));
218 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
223 Check(Section.isRequiredForExecution(IsRequired));
224 Check(Section.isVirtual(IsVirtual));
225 Check(Section.isZeroInit(IsZeroInit));
226 Check(Section.getSize(DataSize));
229 unsigned SectionID = Sections.size();
231 const char *pData = 0;
233 // Some sections, such as debug info, don't need to be loaded for execution.
234 // Leave those where they are.
236 Allocate = DataSize + StubBufSize;
238 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
239 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID);
241 report_fatal_error("Unable to allocate section memory!");
243 // Virtual sections have no data in the object image, so leave pData = 0
247 // Zero-initialize or copy the data from the image
248 if (IsZeroInit || IsVirtual)
249 memset(Addr, 0, DataSize);
251 memcpy(Addr, pData, DataSize);
253 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
254 << " obj addr: " << format("%p", pData)
255 << " new addr: " << format("%p", Addr)
256 << " DataSize: " << DataSize
257 << " StubBufSize: " << StubBufSize
258 << " Allocate: " << Allocate
262 // Even if we didn't load the section, we need to record an entry for it
263 // to handle later processing (and by 'handle' I mean don't do anything
264 // with these sections).
267 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
268 << " obj addr: " << format("%p", data.data())
270 << " DataSize: " << DataSize
271 << " StubBufSize: " << StubBufSize
272 << " Allocate: " << Allocate
276 Sections.push_back(SectionEntry(Addr, Allocate, DataSize,(uintptr_t)pData));
280 unsigned RuntimeDyldImpl::findOrEmitSection(const SectionRef &Section,
282 ObjSectionToIDMap &LocalSections) {
284 unsigned SectionID = 0;
285 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
286 if (i != LocalSections.end())
287 SectionID = i->second;
289 SectionID = emitSection(Section, IsCode);
290 LocalSections[Section] = SectionID;
295 void RuntimeDyldImpl::AddRelocation(const RelocationValueRef &Value,
296 unsigned SectionID, uintptr_t Offset,
298 DEBUG(dbgs() << "AddRelocation SymNamePtr: " << format("%p", Value.SymbolName)
299 << " SID: " << Value.SectionID
300 << " Addend: " << format("%p", Value.Addend)
301 << " Offset: " << format("%p", Offset)
302 << " RelType: " << format("%x", RelType)
305 if (Value.SymbolName == 0) {
306 Relocations[Value.SectionID].push_back(RelocationEntry(
312 SymbolRelocations[Value.SymbolName].push_back(RelocationEntry(
319 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
320 // TODO: There is only ARM far stub now. We should add the Thumb stub,
321 // and stubs for branches Thumb - ARM and ARM - Thumb.
322 if (Arch == Triple::arm) {
323 uint32_t *StubAddr = (uint32_t*)Addr;
324 *StubAddr = 0xe51ff004; // ldr pc,<label>
325 return (uint8_t*)++StubAddr;
331 // Assign an address to a symbol name and resolve all the relocations
332 // associated with it.
333 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
335 // The address to use for relocation resolution is not
336 // the address of the local section buffer. We must be doing
337 // a remote execution environment of some sort. Re-apply any
338 // relocations referencing this section with the given address.
340 // Addr is a uint64_t because we can't assume the pointer width
341 // of the target is the same as that of the host. Just use a generic
342 // "big enough" type.
343 Sections[SectionID].LoadAddress = Addr;
344 DEBUG(dbgs() << "Resolving relocations Section #" << SectionID
345 << "\t" << format("%p", (uint8_t *)Addr)
347 resolveRelocationList(Relocations[SectionID], Addr);
350 void RuntimeDyldImpl::resolveRelocationEntry(const RelocationEntry &RE,
352 // Ignore relocations for sections that were not loaded
353 if (Sections[RE.SectionID].Address != 0) {
354 uint8_t *Target = Sections[RE.SectionID].Address + RE.Offset;
355 DEBUG(dbgs() << "\tSectionID: " << RE.SectionID
356 << " + " << RE.Offset << " (" << format("%p", Target) << ")"
357 << " Data: " << RE.Data
358 << " Addend: " << RE.Addend
361 resolveRelocation(Target, Sections[RE.SectionID].LoadAddress + RE.Offset,
362 Value, RE.Data, RE.Addend);
366 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
368 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
369 resolveRelocationEntry(Relocs[i], Value);
373 // resolveSymbols - Resolve any relocations to the specified symbols if
374 // we know where it lives.
375 void RuntimeDyldImpl::resolveSymbols() {
376 StringMap<RelocationList>::iterator i = SymbolRelocations.begin(),
377 e = SymbolRelocations.end();
378 for (; i != e; i++) {
379 StringRef Name = i->first();
380 RelocationList &Relocs = i->second;
381 StringMap<SymbolLoc>::const_iterator Loc = SymbolTable.find(Name);
382 if (Loc == SymbolTable.end()) {
383 // This is an external symbol, try to get it address from
385 uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
387 DEBUG(dbgs() << "Resolving relocations Name: " << Name
388 << "\t" << format("%p", Addr)
390 resolveRelocationList(Relocs, (uintptr_t)Addr);
392 // Change the relocation to be section relative rather than symbol
393 // relative and move it to the resolved relocation list.
394 DEBUG(dbgs() << "Resolving symbol '" << Name << "'\n");
395 for (int i = 0, e = Relocs.size(); i != e; ++i) {
396 RelocationEntry Entry = Relocs[i];
397 Entry.Addend += Loc->second.second;
398 Relocations[Loc->second.first].push_back(Entry);
406 //===----------------------------------------------------------------------===//
407 // RuntimeDyld class implementation
408 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
413 RuntimeDyld::~RuntimeDyld() {
417 bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) {
419 sys::LLVMFileType type = sys::IdentifyFileType(
420 InputBuffer->getBufferStart(),
421 static_cast<unsigned>(InputBuffer->getBufferSize()));
423 case sys::ELF_Relocatable_FileType:
424 case sys::ELF_Executable_FileType:
425 case sys::ELF_SharedObject_FileType:
426 case sys::ELF_Core_FileType:
427 Dyld = new RuntimeDyldELF(MM);
429 case sys::Mach_O_Object_FileType:
430 case sys::Mach_O_Executable_FileType:
431 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
432 case sys::Mach_O_Core_FileType:
433 case sys::Mach_O_PreloadExecutable_FileType:
434 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
435 case sys::Mach_O_DynamicLinker_FileType:
436 case sys::Mach_O_Bundle_FileType:
437 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
438 case sys::Mach_O_DSYMCompanion_FileType:
439 Dyld = new RuntimeDyldMachO(MM);
441 case sys::Unknown_FileType:
442 case sys::Bitcode_FileType:
443 case sys::Archive_FileType:
444 case sys::COFF_FileType:
445 report_fatal_error("Incompatible object format!");
448 if (!Dyld->isCompatibleFormat(InputBuffer))
449 report_fatal_error("Incompatible object format!");
452 return Dyld->loadObject(InputBuffer);
455 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
456 return Dyld->getSymbolAddress(Name);
459 void RuntimeDyld::resolveRelocations() {
460 Dyld->resolveRelocations();
463 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
465 Dyld->reassignSectionAddress(SectionID, Addr);
468 void RuntimeDyld::mapSectionAddress(void *LocalAddress,
469 uint64_t TargetAddress) {
470 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
473 StringRef RuntimeDyld::getErrorString() {
474 return Dyld->getErrorString();
477 } // end namespace llvm