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 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 // Symbols found in this object
79 StringMap<SymbolLoc> LocalSymbols;
80 // Used sections from the object file
81 ObjSectionToIDMap LocalSections;
83 // Common symbols requiring allocation, and the total size required to
84 // allocate all common symbols.
85 CommonSymbolMap CommonSymbols;
86 uint64_t CommonSize = 0;
90 DEBUG(dbgs() << "Parse symbols:\n");
91 for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
92 i != e; i.increment(err)) {
94 object::SymbolRef::Type SymType;
96 Check(i->getType(SymType));
97 Check(i->getName(Name));
100 Check(i->getFlags(flags));
102 bool isCommon = flags & SymbolRef::SF_Common;
104 // Add the common symbols to a list. We'll allocate them all below.
106 Check(i->getSize(Size));
108 CommonSymbols[*i] = Size;
110 if (SymType == object::SymbolRef::ST_Function ||
111 SymType == object::SymbolRef::ST_Data) {
113 StringRef SectionData;
114 section_iterator si = obj->end_sections();
115 Check(i->getFileOffset(FileOffset));
116 Check(i->getSection(si));
117 if (si == obj->end_sections()) continue;
118 Check(si->getContents(SectionData));
119 const uint8_t* SymPtr = (const uint8_t*)InputBuffer->getBufferStart() +
120 (uintptr_t)FileOffset;
121 uintptr_t SectOffset = (uintptr_t)(SymPtr -
122 (const uint8_t*)SectionData.begin());
124 findOrEmitSection(*obj,
126 SymType == object::SymbolRef::ST_Function,
128 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
129 DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
130 << " flags: " << flags
131 << " SID: " << SectionID
132 << " Offset: " << format("%p", SectOffset));
133 bool isGlobal = flags & SymbolRef::SF_Global;
135 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
138 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
141 // Allocate common symbols
143 emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
145 // Parse and process relocations
146 DEBUG(dbgs() << "Parse relocations:\n");
147 for (section_iterator si = obj->begin_sections(),
148 se = obj->end_sections(); si != se; si.increment(err)) {
150 bool isFirstRelocation = true;
151 unsigned SectionID = 0;
154 for (relocation_iterator i = si->begin_relocations(),
155 e = si->end_relocations(); i != e; i.increment(err)) {
158 // If it's the first relocation in this section, find its SectionID
159 if (isFirstRelocation) {
160 SectionID = findOrEmitSection(*obj, *si, true, LocalSections);
161 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
162 isFirstRelocation = false;
165 ObjRelocationInfo RI;
166 RI.SectionID = SectionID;
167 Check(i->getAdditionalInfo(RI.AdditionalInfo));
168 Check(i->getOffset(RI.Offset));
169 Check(i->getSymbol(RI.Symbol));
170 Check(i->getType(RI.Type));
172 DEBUG(dbgs() << "\t\tAddend: " << RI.AdditionalInfo
173 << " Offset: " << format("%p", (uintptr_t)RI.Offset)
174 << " Type: " << (uint32_t)(RI.Type & 0xffffffffL)
176 processRelocationRef(RI, *obj, LocalSections, LocalSymbols, Stubs);
180 handleObjectLoaded(obj.take());
185 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
186 const CommonSymbolMap &CommonSymbols,
188 SymbolTableMap &SymbolTable) {
189 // Allocate memory for the section
190 unsigned SectionID = Sections.size();
191 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
194 report_fatal_error("Unable to allocate memory for common symbols!");
196 Sections.push_back(SectionEntry(Addr, TotalSize, TotalSize, 0));
197 memset(Addr, 0, TotalSize);
199 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
200 << " new addr: " << format("%p", Addr)
201 << " DataSize: " << TotalSize
204 // Assign the address of each symbol
205 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
206 itEnd = CommonSymbols.end(); it != itEnd; it++) {
208 it->first.getName(Name);
209 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
210 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
211 uint64_t Size = it->second;
217 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
218 const SectionRef &Section,
221 unsigned StubBufSize = 0,
222 StubSize = getMaxStubSize();
225 for (relocation_iterator i = Section.begin_relocations(),
226 e = Section.end_relocations(); i != e; i.increment(err), Check(err))
227 StubBufSize += StubSize;
230 uint64_t Alignment64;
231 Check(Section.getContents(data));
232 Check(Section.getAlignment(Alignment64));
234 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
239 Check(Section.isRequiredForExecution(IsRequired));
240 Check(Section.isVirtual(IsVirtual));
241 Check(Section.isZeroInit(IsZeroInit));
242 Check(Section.getSize(DataSize));
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
270 << " obj addr: " << format("%p", pData)
271 << " new addr: " << format("%p", Addr)
272 << " DataSize: " << DataSize
273 << " StubBufSize: " << StubBufSize
274 << " Allocate: " << Allocate
276 Obj.updateSectionAddress(Section, (uint64_t)Addr);
279 // Even if we didn't load the section, we need to record an entry for it
280 // to handle later processing (and by 'handle' I mean don't do anything
281 // with these sections).
284 DEBUG(dbgs() << "emitSection SectionID: " << SectionID
285 << " obj addr: " << format("%p", data.data())
287 << " DataSize: " << DataSize
288 << " StubBufSize: " << StubBufSize
289 << " Allocate: " << Allocate
293 Sections.push_back(SectionEntry(Addr, Allocate, DataSize,(uintptr_t)pData));
297 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
298 const SectionRef &Section,
300 ObjSectionToIDMap &LocalSections) {
302 unsigned SectionID = 0;
303 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
304 if (i != LocalSections.end())
305 SectionID = i->second;
307 SectionID = emitSection(Obj, Section, IsCode);
308 LocalSections[Section] = SectionID;
313 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
314 unsigned SectionID) {
315 Relocations[SectionID].push_back(RE);
318 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
319 StringRef SymbolName) {
320 // Relocation by symbol. If the symbol is found in the global symbol table,
321 // create an appropriate section relocation. Otherwise, add it to
322 // ExternalSymbolRelocations.
323 SymbolTableMap::const_iterator Loc =
324 GlobalSymbolTable.find(SymbolName);
325 if (Loc == GlobalSymbolTable.end()) {
326 ExternalSymbolRelocations[SymbolName].push_back(RE);
328 // Copy the RE since we want to modify its addend.
329 RelocationEntry RECopy = RE;
330 RECopy.Addend += Loc->second.second;
331 Relocations[Loc->second.first].push_back(RECopy);
335 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
336 // TODO: There is only ARM far stub now. We should add the Thumb stub,
337 // and stubs for branches Thumb - ARM and ARM - Thumb.
338 if (Arch == Triple::arm) {
339 uint32_t *StubAddr = (uint32_t*)Addr;
340 *StubAddr = 0xe51ff004; // ldr pc,<label>
341 return (uint8_t*)++StubAddr;
347 // Assign an address to a symbol name and resolve all the relocations
348 // associated with it.
349 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
351 // The address to use for relocation resolution is not
352 // the address of the local section buffer. We must be doing
353 // a remote execution environment of some sort. Re-apply any
354 // relocations referencing this section with the given address.
356 // Addr is a uint64_t because we can't assume the pointer width
357 // of the target is the same as that of the host. Just use a generic
358 // "big enough" type.
359 Sections[SectionID].LoadAddress = Addr;
360 DEBUG(dbgs() << "Resolving relocations Section #" << SectionID
361 << "\t" << format("%p", (uint8_t *)Addr)
363 resolveRelocationList(Relocations[SectionID], Addr);
366 void RuntimeDyldImpl::resolveRelocationEntry(const RelocationEntry &RE,
368 // Ignore relocations for sections that were not loaded
369 if (Sections[RE.SectionID].Address != 0) {
370 uint8_t *Target = Sections[RE.SectionID].Address + RE.Offset;
371 DEBUG(dbgs() << "\tSectionID: " << RE.SectionID
372 << " + " << RE.Offset << " (" << format("%p", Target) << ")"
373 << " RelType: " << RE.RelType
374 << " Addend: " << RE.Addend
377 resolveRelocation(Target, Sections[RE.SectionID].LoadAddress + RE.Offset,
378 Value, RE.RelType, RE.Addend);
382 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
384 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
385 resolveRelocationEntry(Relocs[i], Value);
389 void RuntimeDyldImpl::resolveExternalSymbols() {
390 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin(),
391 e = ExternalSymbolRelocations.end();
392 for (; i != e; i++) {
393 StringRef Name = i->first();
394 RelocationList &Relocs = i->second;
395 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
396 if (Loc == GlobalSymbolTable.end()) {
397 // This is an external symbol, try to get it address from
399 uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
401 DEBUG(dbgs() << "Resolving relocations Name: " << Name
402 << "\t" << format("%p", Addr)
404 resolveRelocationList(Relocs, (uintptr_t)Addr);
406 report_fatal_error("Expected external symbol");
412 //===----------------------------------------------------------------------===//
413 // RuntimeDyld class implementation
414 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
419 RuntimeDyld::~RuntimeDyld() {
423 bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) {
425 sys::LLVMFileType type = sys::IdentifyFileType(
426 InputBuffer->getBufferStart(),
427 static_cast<unsigned>(InputBuffer->getBufferSize()));
429 case sys::ELF_Relocatable_FileType:
430 case sys::ELF_Executable_FileType:
431 case sys::ELF_SharedObject_FileType:
432 case sys::ELF_Core_FileType:
433 Dyld = new RuntimeDyldELF(MM);
435 case sys::Mach_O_Object_FileType:
436 case sys::Mach_O_Executable_FileType:
437 case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
438 case sys::Mach_O_Core_FileType:
439 case sys::Mach_O_PreloadExecutable_FileType:
440 case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
441 case sys::Mach_O_DynamicLinker_FileType:
442 case sys::Mach_O_Bundle_FileType:
443 case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
444 case sys::Mach_O_DSYMCompanion_FileType:
445 Dyld = new RuntimeDyldMachO(MM);
447 case sys::Unknown_FileType:
448 case sys::Bitcode_FileType:
449 case sys::Archive_FileType:
450 case sys::COFF_FileType:
451 report_fatal_error("Incompatible object format!");
454 if (!Dyld->isCompatibleFormat(InputBuffer))
455 report_fatal_error("Incompatible object format!");
458 return Dyld->loadObject(InputBuffer);
461 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
462 return Dyld->getSymbolAddress(Name);
465 void RuntimeDyld::resolveRelocations() {
466 Dyld->resolveRelocations();
469 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
471 Dyld->reassignSectionAddress(SectionID, Addr);
474 void RuntimeDyld::mapSectionAddress(void *LocalAddress,
475 uint64_t TargetAddress) {
476 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
479 StringRef RuntimeDyld::getErrorString() {
480 return Dyld->getErrorString();
483 } // end namespace llvm