141836fc417c3b2595a75cb82a08402253c118c2
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyld.cpp
1 //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implementation of the MC-JIT runtime dynamic linker.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
21
22 using namespace llvm;
23 using namespace llvm::object;
24
25 // Empty out-of-line virtual destructor as the key function.
26 RTDyldMemoryManager::~RTDyldMemoryManager() {}
27 RuntimeDyldImpl::~RuntimeDyldImpl() {}
28
29 namespace llvm {
30
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();
35
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);
40   }
41 }
42
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);
48       return;
49     }
50   }
51   llvm_unreachable("Attempting to remap address of unknown section!");
52 }
53
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);
58 }
59
60 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
61   OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
62   if (!obj)
63     report_fatal_error("Unable to create object image from memory buffer!");
64
65   Arch = (Triple::ArchType)obj->getArch();
66
67   // Symbols found in this object
68   StringMap<SymbolLoc> LocalSymbols;
69   // Used sections from the object file
70   ObjSectionToIDMap LocalSections;
71
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;
76
77   error_code err;
78   // Parse symbols
79   DEBUG(dbgs() << "Parse symbols:\n");
80   for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
81        i != e; i.increment(err)) {
82     Check(err);
83     object::SymbolRef::Type SymType;
84     StringRef Name;
85     Check(i->getType(SymType));
86     Check(i->getName(Name));
87
88     uint32_t flags;
89     Check(i->getFlags(flags));
90
91     bool isCommon = flags & SymbolRef::SF_Common;
92     if (isCommon) {
93       // Add the common symbols to a list.  We'll allocate them all below.
94       uint64_t Align = getCommonSymbolAlignment(*i);
95       uint64_t Size = 0;
96       Check(i->getSize(Size));
97       CommonSize += Size + Align;
98       CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
99     } else {
100       if (SymType == object::SymbolRef::ST_Function ||
101           SymType == object::SymbolRef::ST_Data ||
102           SymType == object::SymbolRef::ST_Unknown) {
103         uint64_t FileOffset;
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());
114         unsigned SectionID =
115           findOrEmitSection(*obj,
116                             *si,
117                             SymType == object::SymbolRef::ST_Function,
118                             LocalSections);
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;
125         if (isGlobal)
126           GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
127       }
128     }
129     DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
130   }
131
132   // Allocate common symbols
133   if (CommonSize != 0)
134     emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
135
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)) {
140     Check(err);
141     bool isFirstRelocation = true;
142     unsigned SectionID = 0;
143     StubMap Stubs;
144
145     for (relocation_iterator i = si->begin_relocations(),
146          e = si->end_relocations(); i != e; i.increment(err)) {
147       Check(err);
148
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;
154       }
155
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));
162
163       DEBUG(dbgs() << "\t\tAddend: " << RI.AdditionalInfo
164                    << " Offset: " << format("%p", (uintptr_t)RI.Offset)
165                    << " Type: " << (uint32_t)(RI.Type & 0xffffffffL)
166                    << "\n");
167       processRelocationRef(RI, *obj, LocalSections, LocalSymbols, Stubs);
168     }
169   }
170
171   return obj.take();
172 }
173
174 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
175                                         const CommonSymbolMap &CommonSymbols,
176                                         uint64_t TotalSize,
177                                         SymbolTableMap &SymbolTable) {
178   // Allocate memory for the section
179   unsigned SectionID = Sections.size();
180   uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
181                                               SectionID);
182   if (!Addr)
183     report_fatal_error("Unable to allocate memory for common symbols!");
184   uint64_t Offset = 0;
185   Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, TotalSize, 0));
186   memset(Addr, 0, TotalSize);
187
188   DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
189                << " new addr: " << format("%p", Addr)
190                << " DataSize: " << TotalSize
191                << "\n");
192
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;
198     StringRef Name;
199     it->first.getName(Name);
200     if (Align) {
201       // This symbol has an alignment requirement.
202       uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
203       Addr += AlignOffset;
204       Offset += AlignOffset;
205       DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
206                       format("%p\n", Addr));
207     }
208     Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
209     SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
210     Offset += Size;
211     Addr += Size;
212   }
213 }
214
215 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
216                                       const SectionRef &Section,
217                                       bool IsCode) {
218
219   unsigned StubBufSize = 0,
220            StubSize = getMaxStubSize();
221   error_code err;
222   if (StubSize > 0) {
223     for (relocation_iterator i = Section.begin_relocations(),
224          e = Section.end_relocations(); i != e; i.increment(err), Check(err))
225       StubBufSize += StubSize;
226   }
227   StringRef data;
228   uint64_t Alignment64;
229   Check(Section.getContents(data));
230   Check(Section.getAlignment(Alignment64));
231
232   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
233   bool IsRequired;
234   bool IsVirtual;
235   bool IsZeroInit;
236   uint64_t DataSize;
237   StringRef Name;
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));
243
244   unsigned Allocate;
245   unsigned SectionID = Sections.size();
246   uint8_t *Addr;
247   const char *pData = 0;
248
249   // Some sections, such as debug info, don't need to be loaded for execution.
250   // Leave those where they are.
251   if (IsRequired) {
252     Allocate = DataSize + StubBufSize;
253     Addr = IsCode
254       ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
255       : MemMgr->allocateDataSection(Allocate, Alignment, SectionID);
256     if (!Addr)
257       report_fatal_error("Unable to allocate section memory!");
258
259     // Virtual sections have no data in the object image, so leave pData = 0
260     if (!IsVirtual)
261       pData = data.data();
262
263     // Zero-initialize or copy the data from the image
264     if (IsZeroInit || IsVirtual)
265       memset(Addr, 0, DataSize);
266     else
267       memcpy(Addr, pData, DataSize);
268
269     DEBUG(dbgs() << "emitSection SectionID: " << SectionID
270                  << " Name: " << Name
271                  << " obj addr: " << format("%p", pData)
272                  << " new addr: " << format("%p", Addr)
273                  << " DataSize: " << DataSize
274                  << " StubBufSize: " << StubBufSize
275                  << " Allocate: " << Allocate
276                  << "\n");
277     Obj.updateSectionAddress(Section, (uint64_t)Addr);
278   }
279   else {
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).
283     Allocate = 0;
284     Addr = 0;
285     DEBUG(dbgs() << "emitSection SectionID: " << SectionID
286                  << " Name: " << Name
287                  << " obj addr: " << format("%p", data.data())
288                  << " new addr: 0"
289                  << " DataSize: " << DataSize
290                  << " StubBufSize: " << StubBufSize
291                  << " Allocate: " << Allocate
292                  << "\n");
293   }
294
295   Sections.push_back(SectionEntry(Name, Addr, Allocate, DataSize,
296                                   (uintptr_t)pData));
297   return SectionID;
298 }
299
300 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
301                                             const SectionRef &Section,
302                                             bool IsCode,
303                                             ObjSectionToIDMap &LocalSections) {
304
305   unsigned SectionID = 0;
306   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
307   if (i != LocalSections.end())
308     SectionID = i->second;
309   else {
310     SectionID = emitSection(Obj, Section, IsCode);
311     LocalSections[Section] = SectionID;
312   }
313   return SectionID;
314 }
315
316 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
317                                               unsigned SectionID) {
318   Relocations[SectionID].push_back(RE);
319 }
320
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);
330   } else {
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);
335   }
336 }
337
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.
350     // c:   00000000        nop.
351     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
352     const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
353
354     *StubAddr = LuiT9Instr;
355     StubAddr++;
356     *StubAddr = AdduiT9Instr;
357     StubAddr++;
358     *StubAddr = JrT9Instr;
359     StubAddr++;
360     *StubAddr = NopInstr;
361     return Addr;
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
378
379     return Addr;
380   }
381   return Addr;
382 }
383
384 // Assign an address to a symbol name and resolve all the relocations
385 // associated with it.
386 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
387                                              uint64_t Addr) {
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.
392   //
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)
399           << "\n");
400   resolveRelocationList(Relocations[SectionID], Addr);
401 }
402
403 void RuntimeDyldImpl::resolveRelocationEntry(const RelocationEntry &RE,
404                                              uint64_t Value) {
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
412           << "\n");
413
414     resolveRelocation(Target, Sections[RE.SectionID].LoadAddress + RE.Offset,
415                       Value, RE.RelType, RE.Addend);
416   }
417 }
418
419 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
420                                             uint64_t Value) {
421   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
422     resolveRelocationEntry(Relocs[i], Value);
423   }
424 }
425
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
435       // MemoryManager.
436       uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
437                                                                    true);
438       DEBUG(dbgs() << "Resolving relocations Name: " << Name
439               << "\t" << format("%p", Addr)
440               << "\n");
441       resolveRelocationList(Relocs, (uintptr_t)Addr);
442     } else {
443       report_fatal_error("Expected external symbol");
444     }
445   }
446 }
447
448
449 //===----------------------------------------------------------------------===//
450 // RuntimeDyld class implementation
451 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
452   Dyld = 0;
453   MM = mm;
454 }
455
456 RuntimeDyld::~RuntimeDyld() {
457   delete Dyld;
458 }
459
460 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
461   if (!Dyld) {
462     sys::LLVMFileType type = sys::IdentifyFileType(
463             InputBuffer->getBufferStart(),
464             static_cast<unsigned>(InputBuffer->getBufferSize()));
465     switch (type) {
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);
471         break;
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);
483         break;
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!");
489     }
490   } else {
491     if (!Dyld->isCompatibleFormat(InputBuffer))
492       report_fatal_error("Incompatible object format!");
493   }
494
495   return Dyld->loadObject(InputBuffer);
496 }
497
498 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
499   return Dyld->getSymbolAddress(Name);
500 }
501
502 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
503   return Dyld->getSymbolLoadAddress(Name);
504 }
505
506 void RuntimeDyld::resolveRelocations() {
507   Dyld->resolveRelocations();
508 }
509
510 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
511                                          uint64_t Addr) {
512   Dyld->reassignSectionAddress(SectionID, Addr);
513 }
514
515 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
516                                     uint64_t TargetAddress) {
517   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
518 }
519
520 StringRef RuntimeDyld::getErrorString() {
521   return Dyld->getErrorString();
522 }
523
524 } // end namespace llvm