RuntimeDyld: Fix up r169178. MSVC doesn't like "or".
[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 "llvm/ExecutionEngine/RuntimeDyld.h"
16 #include "ObjectImageCommon.h"
17 #include "RuntimeDyldELF.h"
18 #include "RuntimeDyldImpl.h"
19 #include "RuntimeDyldMachO.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/Path.h"
22
23 using namespace llvm;
24 using namespace llvm::object;
25
26 // Empty out-of-line virtual destructor as the key function.
27 RTDyldMemoryManager::~RTDyldMemoryManager() {}
28 RuntimeDyldImpl::~RuntimeDyldImpl() {}
29
30 namespace llvm {
31
32 // Resolve the relocations for all symbols we currently know about.
33 void RuntimeDyldImpl::resolveRelocations() {
34   // First, resolve relocations associated with external symbols.
35   resolveExternalSymbols();
36
37   // Just iterate over the sections we have and resolve all the relocations
38   // in them. Gross overkill, but it gets the job done.
39   for (int i = 0, e = Sections.size(); i != e; ++i) {
40     uint64_t Addr = Sections[i].LoadAddress;
41     DEBUG(dbgs() << "Resolving relocations Section #" << i
42             << "\t" << format("%p", (uint8_t *)Addr)
43             << "\n");
44     resolveRelocationList(Relocations[i], Addr);
45   }
46 }
47
48 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
49                                         uint64_t TargetAddress) {
50   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
51     if (Sections[i].Address == LocalAddress) {
52       reassignSectionAddress(i, TargetAddress);
53       return;
54     }
55   }
56   llvm_unreachable("Attempting to remap address of unknown section!");
57 }
58
59 // Subclasses can implement this method to create specialized image instances.
60 // The caller owns the pointer that is returned.
61 ObjectImage *RuntimeDyldImpl::createObjectImage(ObjectBuffer *InputBuffer) {
62   return new ObjectImageCommon(InputBuffer);
63 }
64
65 ObjectImage *RuntimeDyldImpl::loadObject(ObjectBuffer *InputBuffer) {
66   OwningPtr<ObjectImage> obj(createObjectImage(InputBuffer));
67   if (!obj)
68     report_fatal_error("Unable to create object image from memory buffer!");
69
70   Arch = (Triple::ArchType)obj->getArch();
71
72   // Symbols found in this object
73   StringMap<SymbolLoc> LocalSymbols;
74   // Used sections from the object file
75   ObjSectionToIDMap LocalSections;
76
77   // Common symbols requiring allocation, with their sizes and alignments
78   CommonSymbolMap CommonSymbols;
79   // Maximum required total memory to allocate all common symbols
80   uint64_t CommonSize = 0;
81
82   error_code err;
83   // Parse symbols
84   DEBUG(dbgs() << "Parse symbols:\n");
85   for (symbol_iterator i = obj->begin_symbols(), e = obj->end_symbols();
86        i != e; i.increment(err)) {
87     Check(err);
88     object::SymbolRef::Type SymType;
89     StringRef Name;
90     Check(i->getType(SymType));
91     Check(i->getName(Name));
92
93     uint32_t flags;
94     Check(i->getFlags(flags));
95
96     bool isCommon = flags & SymbolRef::SF_Common;
97     if (isCommon) {
98       // Add the common symbols to a list.  We'll allocate them all below.
99       uint64_t Align = getCommonSymbolAlignment(*i);
100       uint64_t Size = 0;
101       Check(i->getSize(Size));
102       CommonSize += Size + Align;
103       CommonSymbols[*i] = CommonSymbolInfo(Size, Align);
104     } else {
105       if (SymType == object::SymbolRef::ST_Function ||
106           SymType == object::SymbolRef::ST_Data ||
107           SymType == object::SymbolRef::ST_Unknown) {
108         uint64_t FileOffset;
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());
119         unsigned SectionID =
120           findOrEmitSection(*obj,
121                             *si,
122                             SymType == object::SymbolRef::ST_Function,
123                             LocalSections);
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         GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
130       }
131     }
132     DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
133   }
134
135   // Allocate common symbols
136   if (CommonSize != 0)
137     emitCommonSymbols(*obj, CommonSymbols, CommonSize, LocalSymbols);
138
139   // Parse and process relocations
140   DEBUG(dbgs() << "Parse relocations:\n");
141   for (section_iterator si = obj->begin_sections(),
142        se = obj->end_sections(); si != se; si.increment(err)) {
143     Check(err);
144     bool isFirstRelocation = true;
145     unsigned SectionID = 0;
146     StubMap Stubs;
147
148     for (relocation_iterator i = si->begin_relocations(),
149          e = si->end_relocations(); i != e; i.increment(err)) {
150       Check(err);
151
152       // If it's the first relocation in this section, find its SectionID
153       if (isFirstRelocation) {
154         SectionID = findOrEmitSection(*obj, *si, true, LocalSections);
155         DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
156         isFirstRelocation = false;
157       }
158
159       ObjRelocationInfo RI;
160       RI.SectionID = SectionID;
161       Check(i->getAdditionalInfo(RI.AdditionalInfo));
162       Check(i->getOffset(RI.Offset));
163       Check(i->getSymbol(RI.Symbol));
164       Check(i->getType(RI.Type));
165
166       DEBUG(dbgs() << "\t\tAddend: " << RI.AdditionalInfo
167                    << " Offset: " << format("%p", (uintptr_t)RI.Offset)
168                    << " Type: " << (uint32_t)(RI.Type & 0xffffffffL)
169                    << "\n");
170       processRelocationRef(RI, *obj, LocalSections, LocalSymbols, Stubs);
171     }
172   }
173
174   return obj.take();
175 }
176
177 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
178                                         const CommonSymbolMap &CommonSymbols,
179                                         uint64_t TotalSize,
180                                         SymbolTableMap &SymbolTable) {
181   // Allocate memory for the section
182   unsigned SectionID = Sections.size();
183   uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void*),
184                                               SectionID, false);
185   if (!Addr)
186     report_fatal_error("Unable to allocate memory for common symbols!");
187   uint64_t Offset = 0;
188   Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, TotalSize, 0));
189   memset(Addr, 0, TotalSize);
190
191   DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
192                << " new addr: " << format("%p", Addr)
193                << " DataSize: " << TotalSize
194                << "\n");
195
196   // Assign the address of each symbol
197   for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
198        itEnd = CommonSymbols.end(); it != itEnd; it++) {
199     uint64_t Size = it->second.first;
200     uint64_t Align = it->second.second;
201     StringRef Name;
202     it->first.getName(Name);
203     if (Align) {
204       // This symbol has an alignment requirement.
205       uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
206       Addr += AlignOffset;
207       Offset += AlignOffset;
208       DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
209                       format("%p\n", Addr));
210     }
211     Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
212     SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
213     Offset += Size;
214     Addr += Size;
215   }
216 }
217
218 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
219                                       const SectionRef &Section,
220                                       bool IsCode) {
221
222   unsigned StubBufSize = 0,
223            StubSize = getMaxStubSize();
224   error_code err;
225   if (StubSize > 0) {
226     for (relocation_iterator i = Section.begin_relocations(),
227          e = Section.end_relocations(); i != e; i.increment(err), Check(err))
228       StubBufSize += StubSize;
229   }
230   StringRef data;
231   uint64_t Alignment64;
232   Check(Section.getContents(data));
233   Check(Section.getAlignment(Alignment64));
234
235   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
236   bool IsRequired;
237   bool IsVirtual;
238   bool IsZeroInit;
239   bool IsReadOnly;
240   uint64_t DataSize;
241   StringRef Name;
242   Check(Section.isRequiredForExecution(IsRequired));
243   Check(Section.isVirtual(IsVirtual));
244   Check(Section.isZeroInit(IsZeroInit));
245   Check(Section.isReadOnlyData(IsReadOnly));
246   Check(Section.getSize(DataSize));
247   Check(Section.getName(Name));
248
249   unsigned Allocate;
250   unsigned SectionID = Sections.size();
251   uint8_t *Addr;
252   const char *pData = 0;
253
254   // Some sections, such as debug info, don't need to be loaded for execution.
255   // Leave those where they are.
256   if (IsRequired) {
257     Allocate = DataSize + StubBufSize;
258     Addr = IsCode
259       ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
260       : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, IsReadOnly);
261     if (!Addr)
262       report_fatal_error("Unable to allocate section memory!");
263
264     // Virtual sections have no data in the object image, so leave pData = 0
265     if (!IsVirtual)
266       pData = data.data();
267
268     // Zero-initialize or copy the data from the image
269     if (IsZeroInit || IsVirtual)
270       memset(Addr, 0, DataSize);
271     else
272       memcpy(Addr, pData, DataSize);
273
274     DEBUG(dbgs() << "emitSection SectionID: " << SectionID
275                  << " Name: " << Name
276                  << " obj addr: " << format("%p", pData)
277                  << " new addr: " << format("%p", Addr)
278                  << " DataSize: " << DataSize
279                  << " StubBufSize: " << StubBufSize
280                  << " Allocate: " << Allocate
281                  << "\n");
282     Obj.updateSectionAddress(Section, (uint64_t)Addr);
283   }
284   else {
285     // Even if we didn't load the section, we need to record an entry for it
286     // to handle later processing (and by 'handle' I mean don't do anything
287     // with these sections).
288     Allocate = 0;
289     Addr = 0;
290     DEBUG(dbgs() << "emitSection SectionID: " << SectionID
291                  << " Name: " << Name
292                  << " obj addr: " << format("%p", data.data())
293                  << " new addr: 0"
294                  << " DataSize: " << DataSize
295                  << " StubBufSize: " << StubBufSize
296                  << " Allocate: " << Allocate
297                  << "\n");
298   }
299
300   Sections.push_back(SectionEntry(Name, Addr, Allocate, DataSize,
301                                   (uintptr_t)pData));
302   return SectionID;
303 }
304
305 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
306                                             const SectionRef &Section,
307                                             bool IsCode,
308                                             ObjSectionToIDMap &LocalSections) {
309
310   unsigned SectionID = 0;
311   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
312   if (i != LocalSections.end())
313     SectionID = i->second;
314   else {
315     SectionID = emitSection(Obj, Section, IsCode);
316     LocalSections[Section] = SectionID;
317   }
318   return SectionID;
319 }
320
321 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
322                                               unsigned SectionID) {
323   Relocations[SectionID].push_back(RE);
324 }
325
326 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
327                                              StringRef SymbolName) {
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   SymbolTableMap::const_iterator Loc =
332       GlobalSymbolTable.find(SymbolName);
333   if (Loc == GlobalSymbolTable.end()) {
334     ExternalSymbolRelocations[SymbolName].push_back(RE);
335   } else {
336     // Copy the RE since we want to modify its addend.
337     RelocationEntry RECopy = RE;
338     RECopy.Addend += Loc->second.second;
339     Relocations[Loc->second.first].push_back(RECopy);
340   }
341 }
342
343 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
344   if (Arch == Triple::arm) {
345     // TODO: There is only ARM far stub now. We should add the Thumb stub,
346     // and stubs for branches Thumb - ARM and ARM - Thumb.
347     uint32_t *StubAddr = (uint32_t*)Addr;
348     *StubAddr = 0xe51ff004; // ldr pc,<label>
349     return (uint8_t*)++StubAddr;
350   } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
351     uint32_t *StubAddr = (uint32_t*)Addr;
352     // 0:   3c190000        lui     t9,%hi(addr).
353     // 4:   27390000        addiu   t9,t9,%lo(addr).
354     // 8:   03200008        jr      t9.
355     // c:   00000000        nop.
356     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
357     const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
358
359     *StubAddr = LuiT9Instr;
360     StubAddr++;
361     *StubAddr = AdduiT9Instr;
362     StubAddr++;
363     *StubAddr = JrT9Instr;
364     StubAddr++;
365     *StubAddr = NopInstr;
366     return Addr;
367   } else if (Arch == Triple::ppc64) {
368     // PowerPC64 stub: the address points to a function descriptor
369     // instead of the function itself. Load the function address
370     // on r11 and sets it to control register. Also loads the function
371     // TOC in r2 and environment pointer to r11.
372     writeInt32BE(Addr,    0x3D800000); // lis   r12, highest(addr)
373     writeInt32BE(Addr+4,  0x618C0000); // ori   r12, higher(addr)
374     writeInt32BE(Addr+8,  0x798C07C6); // sldi  r12, r12, 32
375     writeInt32BE(Addr+12, 0x658C0000); // oris  r12, r12, h(addr)
376     writeInt32BE(Addr+16, 0x618C0000); // ori   r12, r12, l(addr)
377     writeInt32BE(Addr+20, 0xF8410028); // std   r2,  40(r1)
378     writeInt32BE(Addr+24, 0xE96C0000); // ld    r11, 0(r12)
379     writeInt32BE(Addr+28, 0xE84C0008); // ld    r2,  0(r12)
380     writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
381     writeInt32BE(Addr+36, 0xE96C0010); // ld    r11, 16(r2)
382     writeInt32BE(Addr+40, 0x4E800420); // bctr
383
384     return Addr;
385   }
386   return Addr;
387 }
388
389 // Assign an address to a symbol name and resolve all the relocations
390 // associated with it.
391 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
392                                              uint64_t Addr) {
393   // The address to use for relocation resolution is not
394   // the address of the local section buffer. We must be doing
395   // a remote execution environment of some sort. Relocations can't
396   // be applied until all the sections have been moved.  The client must
397   // trigger this with a call to MCJIT::finalize() or
398   // RuntimeDyld::resolveRelocations().
399   //
400   // Addr is a uint64_t because we can't assume the pointer width
401   // of the target is the same as that of the host. Just use a generic
402   // "big enough" type.
403   Sections[SectionID].LoadAddress = Addr;
404 }
405
406 void RuntimeDyldImpl::resolveRelocationEntry(const RelocationEntry &RE,
407                                              uint64_t Value) {
408   // Ignore relocations for sections that were not loaded
409   if (Sections[RE.SectionID].Address != 0) {
410     DEBUG(dbgs() << "\tSectionID: " << RE.SectionID
411           << " + " << RE.Offset << " ("
412           << format("%p", Sections[RE.SectionID].Address + RE.Offset) << ")"
413           << " RelType: " << RE.RelType
414           << " Addend: " << RE.Addend
415           << "\n");
416
417     resolveRelocation(Sections[RE.SectionID], RE.Offset,
418                       Value, RE.RelType, RE.Addend);
419   }
420 }
421
422 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
423                                             uint64_t Value) {
424   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
425     resolveRelocationEntry(Relocs[i], Value);
426   }
427 }
428
429 void RuntimeDyldImpl::resolveExternalSymbols() {
430   StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin(),
431                                       e = ExternalSymbolRelocations.end();
432   for (; i != e; i++) {
433     StringRef Name = i->first();
434     RelocationList &Relocs = i->second;
435     SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
436     if (Loc == GlobalSymbolTable.end()) {
437       // This is an external symbol, try to get it address from
438       // MemoryManager.
439       uint8_t *Addr = (uint8_t*) MemMgr->getPointerToNamedFunction(Name.data(),
440                                                                    true);
441       DEBUG(dbgs() << "Resolving relocations Name: " << Name
442               << "\t" << format("%p", Addr)
443               << "\n");
444       resolveRelocationList(Relocs, (uintptr_t)Addr);
445     } else {
446       report_fatal_error("Expected external symbol");
447     }
448   }
449 }
450
451
452 //===----------------------------------------------------------------------===//
453 // RuntimeDyld class implementation
454 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
455   // FIXME: There's a potential issue lurking here if a single instance of
456   // RuntimeDyld is used to load multiple objects.  The current implementation
457   // associates a single memory manager with a RuntimeDyld instance.  Even
458   // though the public class spawns a new 'impl' instance for each load,
459   // they share a single memory manager.  This can become a problem when page
460   // permissions are applied.
461   Dyld = 0;
462   MM = mm;
463 }
464
465 RuntimeDyld::~RuntimeDyld() {
466   delete Dyld;
467 }
468
469 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
470   if (!Dyld) {
471     sys::LLVMFileType type = sys::IdentifyFileType(
472             InputBuffer->getBufferStart(),
473             static_cast<unsigned>(InputBuffer->getBufferSize()));
474     switch (type) {
475       case sys::ELF_Relocatable_FileType:
476       case sys::ELF_Executable_FileType:
477       case sys::ELF_SharedObject_FileType:
478       case sys::ELF_Core_FileType:
479         Dyld = new RuntimeDyldELF(MM);
480         break;
481       case sys::Mach_O_Object_FileType:
482       case sys::Mach_O_Executable_FileType:
483       case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
484       case sys::Mach_O_Core_FileType:
485       case sys::Mach_O_PreloadExecutable_FileType:
486       case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
487       case sys::Mach_O_DynamicLinker_FileType:
488       case sys::Mach_O_Bundle_FileType:
489       case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
490       case sys::Mach_O_DSYMCompanion_FileType:
491         Dyld = new RuntimeDyldMachO(MM);
492         break;
493       case sys::Unknown_FileType:
494       case sys::Bitcode_FileType:
495       case sys::Archive_FileType:
496       case sys::COFF_FileType:
497         report_fatal_error("Incompatible object format!");
498     }
499   } else {
500     if (!Dyld->isCompatibleFormat(InputBuffer))
501       report_fatal_error("Incompatible object format!");
502   }
503
504   return Dyld->loadObject(InputBuffer);
505 }
506
507 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
508   return Dyld->getSymbolAddress(Name);
509 }
510
511 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
512   return Dyld->getSymbolLoadAddress(Name);
513 }
514
515 void RuntimeDyld::resolveRelocations() {
516   Dyld->resolveRelocations();
517 }
518
519 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
520                                          uint64_t Addr) {
521   Dyld->reassignSectionAddress(SectionID, Addr);
522 }
523
524 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
525                                     uint64_t TargetAddress) {
526   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
527 }
528
529 StringRef RuntimeDyld::getErrorString() {
530   return Dyld->getErrorString();
531 }
532
533 } // end namespace llvm