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.
42 resolveExternalSymbols();
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 // Subclasses can implement this method to create specialized image instances.
63 // The caller owns the the pointer that is returned.
64 ObjectImage *RuntimeDyldImpl::createObjectImage(const MemoryBuffer *InputBuffer) {
65 ObjectFile *ObjFile = ObjectFile::createObjectFile(const_cast<MemoryBuffer*>
67 ObjectImage *Obj = new ObjectImage(ObjFile);
71 bool RuntimeDyldImpl::loadObject(const MemoryBuffer *InputBuffer) {
72 OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
74 report_fatal_error("Unable to create object image from memory buffer!");
76 Arch = (Triple::ArchType)obj->getArch();
78 LocalSymbolMap LocalSymbols; // Functions and data symbols from the
80 ObjSectionToIDMap LocalSections; // Used sections from the object file
81 CommonSymbolMap CommonSymbols; // Common symbols requiring allocation
82 uint64_t CommonSize = 0;
86 DEBUG(dbgs() << "Parse symbols:\n");
87 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
88 i != e; i.increment(err)) {
90 object::SymbolRef::Type SymType;
92 Check(i->getType(SymType));
93 Check(i->getName(Name));
96 Check(i->getFlags(flags));
98 bool isCommon = flags & SymbolRef::SF_Common;
100 // Add the common symbols to a list. We'll allocate them all below.
102 Check(i->getSize(Size));
104 CommonSymbols[*i] = Size;
106 if (SymType == object::SymbolRef::ST_Function ||
107 SymType == object::SymbolRef::ST_Data) {
109 StringRef SectionData;
110 section_iterator si = obj->end_sections();
111 Check(i->getFileOffset(FileOffset));
112 Check(i->getSection(si));
113 if (si == obj->end_sections()) continue;
114 Check(si->getContents(SectionData));
115 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
116 (uintptr_t)FileOffset;
117 uintptr_t SectOffset = (uintptr_t)(SymPtr -
118 (const uint8_t*)SectionData.begin());
120 findOrEmitSection(*obj,
122 SymType == object::SymbolRef::ST_Function,
124 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
125 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
126 << " flags: " << flags
127 << " SID: " << SectionID
128 << " Offset: " << format("%p", SectOffset));
129 bool isGlobal = flags & SymbolRef::SF_Global;
131 SymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
134 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
137 // Allocate common symbols
139 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
141 // Parse and process relocations
142 DEBUG(dbgs() << "Parse relocations:\n");
143 for (section_iterator si = obj->begin_sections(),
144 se = obj->end_sections(); si != se; si.increment(err)) {
146 bool isFirstRelocation = true;
147 unsigned SectionID = 0;
150 for (relocation_iterator i = si->begin_relocations(),
151 e = si->end_relocations(); i != e; i.increment(err)) {
154 // If it's the first relocation in this section, find its SectionID
155 if (isFirstRelocation) {
156 SectionID = findOrEmitSection(*obj, *si, true, LocalSections);
157 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
158 isFirstRelocation = false;
161 ObjRelocationInfo RI;
162 RI.SectionID = SectionID;
163 Check(i->getAdditionalInfo(RI.AdditionalInfo));
164 Check(i->getOffset(RI.Offset));
165 Check(i->getSymbol(RI.Symbol));
166 Check(i->getType(RI.Type));
168 DEBUG(dbgs() << "\t\tAddend: " << RI.AdditionalInfo
169 << " Offset: " << format("%p", (uintptr_t)RI.Offset)
170 << " Type: " << (uint32_t)(RI.Type & 0xffffffffL)
172 processRelocationRef(RI, *obj, LocalSections, LocalSymbols, Stubs);
176 handleObjectLoaded(obj.take());
181 unsigned RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
182 const CommonSymbolMap &Map,
184 LocalSymbolMap &LocalSymbols) {
185 // Allocate memory for the section
186 unsigned SectionID = Sections.size();
187 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
190 report_fatal_error("Unable to allocate memory for common symbols!");
192 Sections.push_back(SectionEntry(Addr, TotalSize, TotalSize, 0));
193 memset(Addr, 0, TotalSize);
195 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
196 << " new addr: " << format("%p", Addr)
197 << " DataSize: " << TotalSize
200 // Assign the address of each symbol
201 for (CommonSymbolMap::const_iterator it = Map.begin(), itEnd = Map.end();
203 uint64_t Size = it->second;
205 it->first.getName(Name);
206 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
207 LocalSymbols[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;
237 Check(Section.isRequiredForExecution(IsRequired));
238 Check(Section.isVirtual(IsVirtual));
239 Check(Section.isZeroInit(IsZeroInit));
240 Check(Section.getSize(DataSize));
243 unsigned SectionID = Sections.size();
245 const char *pData = 0;
247 // Some sections, such as debug info, don't need to be loaded for execution.
248 // Leave those where they are.
250 Allocate = DataSize + StubBufSize;
252 ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
253 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID);
255 report_fatal_error("Unable to allocate section memory!");
257 // Virtual sections have no data in the object image, so leave pData = 0
261 // Zero-initialize or copy the data from the image
262 if (IsZeroInit || IsVirtual)
263 memset(Addr, 0, DataSize);
265 memcpy(Addr, pData, DataSize);
267 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
268 << " obj addr: " << format("%p", pData)
269 << " new addr: " << format("%p", Addr)
270 << " DataSize: " << DataSize
271 << " StubBufSize: " << StubBufSize
272 << " Allocate: " << Allocate
274 Obj.updateSectionAddress(Section, (uint64_t)Addr);
277 // Even if we didn't load the section, we need to record an entry for it
278 // to handle later processing (and by 'handle' I mean don't do anything
279 // with these sections).
282 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
283 << " obj addr: " << format("%p", data.data())
285 << " DataSize: " << DataSize
286 << " StubBufSize: " << StubBufSize
287 << " Allocate: " << Allocate
291 Sections.push_back(SectionEntry(Addr, Allocate, DataSize,(uintptr_t)pData));
295 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
296 const SectionRef &Section,
298 ObjSectionToIDMap &LocalSections) {
300 unsigned SectionID = 0;
301 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
302 if (i != LocalSections.end())
303 SectionID = i->second;
305 SectionID = emitSection(Obj, Section, IsCode);
306 LocalSections[Section] = SectionID;
311 void RuntimeDyldImpl::addRelocation(const RelocationValueRef &Value,
312 unsigned SectionID, uintptr_t Offset,
314 DEBUG(dbgs() << "addRelocation SymNamePtr: " << format("%p", Value.SymbolName)
315 << " SID: " << Value.SectionID
316 << " Addend: " << format("%p", Value.Addend)
317 << " Offset: " << format("%p", Offset)
318 << " RelType: " << format("%x", RelType)
321 if (Value.SymbolName == 0) {
322 Relocations[Value.SectionID].push_back(RelocationEntry(
328 // Relocation by symbol. If the symbol is found in the global symbol table,
329 // create an appropriate section relocation. Otherwise, add it to
330 // ExternalSymbolRelocations.
331 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
333 StringMap<SymbolLoc>::const_iterator Loc = SymbolTable.find(Value.SymbolName);
334 if (Loc == SymbolTable.end()) {
335 ExternalSymbolRelocations[Value.SymbolName].push_back(RE);
337 RE.Addend += Loc->second.second;
338 Relocations[Loc->second.first].push_back(RE);
343 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
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 if (Arch == Triple::arm) {
347 uint32_t *StubAddr = (uint32_t*)Addr;
348 *StubAddr = 0xe51ff004; // ldr pc,<label>
349 return (uint8_t*)++StubAddr;
355 // Assign an address to a symbol name and resolve all the relocations
356 // associated with it.
357 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
359 // The address to use for relocation resolution is not
360 // the address of the local section buffer. We must be doing
361 // a remote execution environment of some sort. Re-apply any
362 // relocations referencing this section with the given address.
364 // Addr is a uint64_t because we can't assume the pointer width
365 // of the target is the same as that of the host. Just use a generic
366 // "big enough" type.
367 Sections[SectionID].LoadAddress = Addr;
368 DEBUG(dbgs() << "Resolving relocations Section #" << SectionID
369 << "\t" << format("%p", (uint8_t *)Addr)
371 resolveRelocationList(Relocations[SectionID], Addr);
374 void RuntimeDyldImpl::resolveRelocationEntry(const RelocationEntry &RE,
376 // Ignore relocations for sections that were not loaded
377 if (Sections[RE.SectionID].Address != 0) {
378 uint8_t *Target = Sections[RE.SectionID].Address + RE.Offset;
379 DEBUG(dbgs() << "\tSectionID: " << RE.SectionID
380 << " + " << RE.Offset << " (" << format("%p", Target) << ")"
381 << " RelType: " << RE.RelType
382 << " Addend: " << RE.Addend
385 resolveRelocation(Target, Sections[RE.SectionID].LoadAddress + RE.Offset,
386 Value, RE.RelType, RE.Addend);
390 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
392 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
393 resolveRelocationEntry(Relocs[i], Value);
397 void RuntimeDyldImpl::resolveExternalSymbols() {
398 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin(),
399 e = ExternalSymbolRelocations.end();
400 for (; i != e; i++) {
401 StringRef Name = i->first();
402 RelocationList &Relocs = i->second;
403 StringMap<SymbolLoc>::const_iterator Loc = SymbolTable.find(Name);
404 if (Loc == SymbolTable.end()) {
405 // This is an external symbol, try to get it address from
407 uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
409 DEBUG(dbgs() << "Resolving relocations Name: " << Name
410 << "\t" << format("%p", Addr)
412 resolveRelocationList(Relocs, (uintptr_t)Addr);
414 report_fatal_error("Expected external symbol");
420 //===----------------------------------------------------------------------===//
421 // RuntimeDyld class implementation
422 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
427 RuntimeDyld::~RuntimeDyld() {
431 bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) {
433 sys::LLVMFileType type = sys::IdentifyFileType(
434 InputBuffer->getBufferStart(),
435 static_cast<unsigned>(InputBuffer->getBufferSize()));
437 case sys::ELF_Relocatable_FileType:
438 case sys::ELF_Executable_FileType:
439 case sys::ELF_SharedObject_FileType:
440 case sys::ELF_Core_FileType:
441 Dyld = new RuntimeDyldELF(MM);
443 case sys::Mach_O_Object_FileType:
444 case sys::Mach_O_Executable_FileType:
445 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
446 case sys::Mach_O_Core_FileType:
447 case sys::Mach_O_PreloadExecutable_FileType:
448 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
449 case sys::Mach_O_DynamicLinker_FileType:
450 case sys::Mach_O_Bundle_FileType:
451 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
452 case sys::Mach_O_DSYMCompanion_FileType:
453 Dyld = new RuntimeDyldMachO(MM);
455 case sys::Unknown_FileType:
456 case sys::Bitcode_FileType:
457 case sys::Archive_FileType:
458 case sys::COFF_FileType:
459 report_fatal_error("Incompatible object format!");
462 if (!Dyld->isCompatibleFormat(InputBuffer))
463 report_fatal_error("Incompatible object format!");
466 return Dyld->loadObject(InputBuffer);
469 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
470 return Dyld->getSymbolAddress(Name);
473 void RuntimeDyld::resolveRelocations() {
474 Dyld->resolveRelocations();
477 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
479 Dyld->reassignSectionAddress(SectionID, Addr);
482 void RuntimeDyld::mapSectionAddress(void *LocalAddress,
483 uint64_t TargetAddress) {
484 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
487 StringRef RuntimeDyld::getErrorString() {
488 return Dyld->getErrorString();
491 } // end namespace llvm