Make createObjectImage and createObjectImageFromFile static methods on the
[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 "JITRegistrar.h"
17 #include "ObjectImageCommon.h"
18 #include "RuntimeDyldELF.h"
19 #include "RuntimeDyldImpl.h"
20 #include "RuntimeDyldMachO.h"
21 #include "llvm/Object/ELF.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/MutexGuard.h"
24
25 using namespace llvm;
26 using namespace llvm::object;
27
28 // Empty out-of-line virtual destructor as the key function.
29 RuntimeDyldImpl::~RuntimeDyldImpl() {}
30
31 // Pin the JITRegistrar's and ObjectImage*'s vtables to this file.
32 void JITRegistrar::anchor() {}
33 void ObjectImage::anchor() {}
34 void ObjectImageCommon::anchor() {}
35
36 namespace llvm {
37
38 void RuntimeDyldImpl::registerEHFrames() {
39 }
40
41 void RuntimeDyldImpl::deregisterEHFrames() {
42 }
43
44 // Resolve the relocations for all symbols we currently know about.
45 void RuntimeDyldImpl::resolveRelocations() {
46   MutexGuard locked(lock);
47
48   // First, resolve relocations associated with external symbols.
49   resolveExternalSymbols();
50
51   // Just iterate over the sections we have and resolve all the relocations
52   // in them. Gross overkill, but it gets the job done.
53   for (int i = 0, e = Sections.size(); i != e; ++i) {
54     // The Section here (Sections[i]) refers to the section in which the
55     // symbol for the relocation is located.  The SectionID in the relocation
56     // entry provides the section to which the relocation will be applied.
57     uint64_t Addr = Sections[i].LoadAddress;
58     DEBUG(dbgs() << "Resolving relocations Section #" << i
59             << "\t" << format("%p", (uint8_t *)Addr)
60             << "\n");
61     resolveRelocationList(Relocations[i], Addr);
62     Relocations.erase(i);
63   }
64 }
65
66 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
67                                         uint64_t TargetAddress) {
68   MutexGuard locked(lock);
69   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
70     if (Sections[i].Address == LocalAddress) {
71       reassignSectionAddress(i, TargetAddress);
72       return;
73     }
74   }
75   llvm_unreachable("Attempting to remap address of unknown section!");
76 }
77
78 ObjectImage* RuntimeDyldImpl::loadObject(ObjectImage *InputObject) {
79   MutexGuard locked(lock);
80
81   std::unique_ptr<ObjectImage> Obj(InputObject);
82   if (!Obj)
83     return NULL;
84
85   // Save information about our target
86   Arch = (Triple::ArchType)Obj->getArch();
87   IsTargetLittleEndian = Obj->getObjectFile()->isLittleEndian();
88  
89   // Compute the memory size required to load all sections to be loaded
90   // and pass this information to the memory manager
91   if (MemMgr->needsToReserveAllocationSpace()) {
92     uint64_t CodeSize = 0, DataSizeRO = 0, DataSizeRW = 0;
93     computeTotalAllocSize(*Obj, CodeSize, DataSizeRO, DataSizeRW);
94     MemMgr->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
95   }
96   
97   // Symbols found in this object
98   StringMap<SymbolLoc> LocalSymbols;
99   // Used sections from the object file
100   ObjSectionToIDMap LocalSections;
101
102   // Common symbols requiring allocation, with their sizes and alignments
103   CommonSymbolMap CommonSymbols;
104   // Maximum required total memory to allocate all common symbols
105   uint64_t CommonSize = 0;
106
107   // Parse symbols
108   DEBUG(dbgs() << "Parse symbols:\n");
109   for (symbol_iterator I = Obj->begin_symbols(), E = Obj->end_symbols(); I != E;
110        ++I) {
111     object::SymbolRef::Type SymType;
112     StringRef Name;
113     Check(I->getType(SymType));
114     Check(I->getName(Name));
115
116     uint32_t Flags = I->getFlags();
117
118     bool IsCommon = Flags & SymbolRef::SF_Common;
119     if (IsCommon) {
120       // Add the common symbols to a list.  We'll allocate them all below.
121       uint32_t Align;
122       Check(I->getAlignment(Align));
123       uint64_t Size = 0;
124       Check(I->getSize(Size));
125       CommonSize += Size + Align;
126       CommonSymbols[*I] = CommonSymbolInfo(Size, Align);
127     } else {
128       if (SymType == object::SymbolRef::ST_Function ||
129           SymType == object::SymbolRef::ST_Data ||
130           SymType == object::SymbolRef::ST_Unknown) {
131         uint64_t FileOffset;
132         StringRef SectionData;
133         bool IsCode;
134         section_iterator SI = Obj->end_sections();
135         Check(I->getFileOffset(FileOffset));
136         Check(I->getSection(SI));
137         if (SI == Obj->end_sections()) continue;
138         Check(SI->getContents(SectionData));
139         Check(SI->isText(IsCode));
140         const uint8_t* SymPtr = (const uint8_t*)Obj->getData().data() +
141                                 (uintptr_t)FileOffset;
142         uintptr_t SectOffset = (uintptr_t)(SymPtr -
143                                            (const uint8_t*)SectionData.begin());
144         unsigned SectionID = findOrEmitSection(*Obj, *SI, IsCode, LocalSections);
145         LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
146         DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
147                      << " flags: " << Flags
148                      << " SID: " << SectionID
149                      << " Offset: " << format("%p", SectOffset));
150         GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
151       }
152     }
153     DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
154   }
155
156   // Allocate common symbols
157   if (CommonSize != 0)
158     emitCommonSymbols(*Obj, CommonSymbols, CommonSize, LocalSymbols);
159
160   // Parse and process relocations
161   DEBUG(dbgs() << "Parse relocations:\n");
162   for (section_iterator SI = Obj->begin_sections(), SE = Obj->end_sections();
163        SI != SE; ++SI) {
164     bool IsFirstRelocation = true;
165     unsigned SectionID = 0;
166     StubMap Stubs;
167     section_iterator RelocatedSection = SI->getRelocatedSection();
168
169     for (relocation_iterator I = SI->relocation_begin(),
170                              E = SI->relocation_end();
171          I != E; ++I) {
172       // If it's the first relocation in this section, find its SectionID
173       if (IsFirstRelocation) {
174         bool IsCode = false;
175         Check(RelocatedSection->isText(IsCode));
176         SectionID =
177             findOrEmitSection(*Obj, *RelocatedSection, IsCode, LocalSections);
178         DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
179         IsFirstRelocation = false;
180       }
181
182       processRelocationRef(SectionID, *I, *Obj, LocalSections, LocalSymbols,
183                            Stubs);
184     }
185   }
186
187   // Give the subclasses a chance to tie-up any loose ends.
188   finalizeLoad(LocalSections);
189
190   return Obj.release();
191 }
192
193 // A helper method for computeTotalAllocSize.
194 // Computes the memory size required to allocate sections with the given sizes, 
195 // assuming that all sections are allocated with the given alignment
196 static uint64_t computeAllocationSizeForSections(std::vector<uint64_t>& SectionSizes, 
197                                                  uint64_t Alignment) {
198   uint64_t TotalSize = 0;
199   for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
200     uint64_t AlignedSize = (SectionSizes[Idx] + Alignment - 1) / 
201                            Alignment * Alignment;
202     TotalSize += AlignedSize;
203   }
204   return TotalSize;
205 }
206
207 // Compute an upper bound of the memory size that is required to load all sections
208 void RuntimeDyldImpl::computeTotalAllocSize(ObjectImage &Obj, 
209     uint64_t& CodeSize, uint64_t& DataSizeRO, uint64_t& DataSizeRW) {
210   // Compute the size of all sections required for execution
211   std::vector<uint64_t> CodeSectionSizes;
212   std::vector<uint64_t> ROSectionSizes;
213   std::vector<uint64_t> RWSectionSizes;
214   uint64_t MaxAlignment = sizeof(void*);
215
216   // Collect sizes of all sections to be loaded; 
217   // also determine the max alignment of all sections
218   for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections(); 
219        SI != SE; ++SI) {
220     const SectionRef &Section = *SI;
221
222     bool IsRequired;
223     Check(Section.isRequiredForExecution(IsRequired));
224     
225     // Consider only the sections that are required to be loaded for execution
226     if (IsRequired) {
227       uint64_t DataSize = 0;
228       uint64_t Alignment64 = 0;
229       bool IsCode = false;
230       bool IsReadOnly = false;
231       StringRef Name;
232       Check(Section.getSize(DataSize));
233       Check(Section.getAlignment(Alignment64));
234       Check(Section.isText(IsCode));
235       Check(Section.isReadOnlyData(IsReadOnly));
236       Check(Section.getName(Name));
237       unsigned Alignment = (unsigned) Alignment64 & 0xffffffffL;
238       
239       uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
240       uint64_t SectionSize = DataSize + StubBufSize;
241       
242       // The .eh_frame section (at least on Linux) needs an extra four bytes padded
243       // with zeroes added at the end.  For MachO objects, this section has a
244       // slightly different name, so this won't have any effect for MachO objects.
245       if (Name == ".eh_frame")
246         SectionSize += 4;
247         
248       if (SectionSize > 0) {
249         // save the total size of the section
250         if (IsCode) {
251           CodeSectionSizes.push_back(SectionSize);
252         } else if (IsReadOnly) {
253           ROSectionSizes.push_back(SectionSize);
254         } else {
255           RWSectionSizes.push_back(SectionSize);
256         }
257         // update the max alignment
258         if (Alignment > MaxAlignment) {
259           MaxAlignment = Alignment;
260         }
261       }      
262     }
263   }
264
265   // Compute the size of all common symbols
266   uint64_t CommonSize = 0;
267   for (symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols();
268        I != E; ++I) {
269     uint32_t Flags = I->getFlags();
270     if (Flags & SymbolRef::SF_Common) {
271       // Add the common symbols to a list.  We'll allocate them all below.
272       uint64_t Size = 0;
273       Check(I->getSize(Size));
274       CommonSize += Size;
275     }
276   }
277   if (CommonSize != 0) {
278     RWSectionSizes.push_back(CommonSize);
279   }
280
281   // Compute the required allocation space for each different type of sections 
282   // (code, read-only data, read-write data) assuming that all sections are 
283   // allocated with the max alignment. Note that we cannot compute with the
284   // individual alignments of the sections, because then the required size 
285   // depends on the order, in which the sections are allocated.
286   CodeSize = computeAllocationSizeForSections(CodeSectionSizes, MaxAlignment);
287   DataSizeRO = computeAllocationSizeForSections(ROSectionSizes, MaxAlignment);
288   DataSizeRW = computeAllocationSizeForSections(RWSectionSizes, MaxAlignment);   
289 }
290
291 // compute stub buffer size for the given section
292 unsigned RuntimeDyldImpl::computeSectionStubBufSize(ObjectImage &Obj, 
293                                                     const SectionRef &Section) {
294   unsigned StubSize = getMaxStubSize();
295   if (StubSize == 0) {
296      return 0;
297   }
298   // FIXME: this is an inefficient way to handle this. We should computed the
299   // necessary section allocation size in loadObject by walking all the sections
300   // once.
301   unsigned StubBufSize = 0;
302   for (section_iterator SI = Obj.begin_sections(),
303                         SE = Obj.end_sections();
304        SI != SE; ++SI) {
305     section_iterator RelSecI = SI->getRelocatedSection();
306     if (!(RelSecI == Section))
307       continue;
308
309     for (relocation_iterator I = SI->relocation_begin(),
310                              E = SI->relocation_end();
311          I != E; ++I) {
312       StubBufSize += StubSize;
313     }
314   }
315   
316   // Get section data size and alignment
317   uint64_t Alignment64;
318   uint64_t DataSize;
319   Check(Section.getSize(DataSize));
320   Check(Section.getAlignment(Alignment64));
321
322   // Add stubbuf size alignment
323   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
324   unsigned StubAlignment = getStubAlignment();
325   unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
326   if (StubAlignment > EndAlignment)
327      StubBufSize += StubAlignment - EndAlignment;
328   return StubBufSize;
329 }
330
331 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
332                                         const CommonSymbolMap &CommonSymbols,
333                                         uint64_t TotalSize,
334                                         SymbolTableMap &SymbolTable) {
335   // Allocate memory for the section
336   unsigned SectionID = Sections.size();
337   uint8_t *Addr = MemMgr->allocateDataSection(
338     TotalSize, sizeof(void*), SectionID, StringRef(), false);
339   if (!Addr)
340     report_fatal_error("Unable to allocate memory for common symbols!");
341   uint64_t Offset = 0;
342   Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
343   memset(Addr, 0, TotalSize);
344
345   DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
346                << " new addr: " << format("%p", Addr)
347                << " DataSize: " << TotalSize
348                << "\n");
349
350   // Assign the address of each symbol
351   for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
352        itEnd = CommonSymbols.end(); it != itEnd; it++) {
353     uint64_t Size = it->second.first;
354     uint64_t Align = it->second.second;
355     StringRef Name;
356     it->first.getName(Name);
357     if (Align) {
358       // This symbol has an alignment requirement.
359       uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
360       Addr += AlignOffset;
361       Offset += AlignOffset;
362       DEBUG(dbgs() << "Allocating common symbol " << Name << " address " <<
363                       format("%p\n", Addr));
364     }
365     Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
366     SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
367     Offset += Size;
368     Addr += Size;
369   }
370 }
371
372 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
373                                       const SectionRef &Section,
374                                       bool IsCode) {
375
376   StringRef data;
377   uint64_t Alignment64;
378   Check(Section.getContents(data));
379   Check(Section.getAlignment(Alignment64));
380
381   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
382   bool IsRequired;
383   bool IsVirtual;
384   bool IsZeroInit;
385   bool IsReadOnly;
386   uint64_t DataSize;
387   unsigned PaddingSize = 0;
388   unsigned StubBufSize = 0;
389   StringRef Name;
390   Check(Section.isRequiredForExecution(IsRequired));
391   Check(Section.isVirtual(IsVirtual));
392   Check(Section.isZeroInit(IsZeroInit));
393   Check(Section.isReadOnlyData(IsReadOnly));
394   Check(Section.getSize(DataSize));
395   Check(Section.getName(Name));
396     
397   StubBufSize = computeSectionStubBufSize(Obj, Section); 
398
399   // The .eh_frame section (at least on Linux) needs an extra four bytes padded
400   // with zeroes added at the end.  For MachO objects, this section has a
401   // slightly different name, so this won't have any effect for MachO objects.
402   if (Name == ".eh_frame")
403     PaddingSize = 4;
404
405   uintptr_t Allocate;
406   unsigned SectionID = Sections.size();
407   uint8_t *Addr;
408   const char *pData = 0;
409
410   // Some sections, such as debug info, don't need to be loaded for execution.
411   // Leave those where they are.
412   if (IsRequired) {
413     Allocate = DataSize + PaddingSize + StubBufSize;
414     Addr = IsCode
415       ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID, Name)
416       : MemMgr->allocateDataSection(Allocate, Alignment, SectionID, Name,
417                                     IsReadOnly);
418     if (!Addr)
419       report_fatal_error("Unable to allocate section memory!");
420
421     // Virtual sections have no data in the object image, so leave pData = 0
422     if (!IsVirtual)
423       pData = data.data();
424
425     // Zero-initialize or copy the data from the image
426     if (IsZeroInit || IsVirtual)
427       memset(Addr, 0, DataSize);
428     else
429       memcpy(Addr, pData, DataSize);
430
431     // Fill in any extra bytes we allocated for padding
432     if (PaddingSize != 0) {
433       memset(Addr + DataSize, 0, PaddingSize);
434       // Update the DataSize variable so that the stub offset is set correctly.
435       DataSize += PaddingSize;
436     }
437
438     DEBUG(dbgs() << "emitSection SectionID: " << SectionID
439                  << " Name: " << Name
440                  << " obj addr: " << format("%p", pData)
441                  << " new addr: " << format("%p", Addr)
442                  << " DataSize: " << DataSize
443                  << " StubBufSize: " << StubBufSize
444                  << " Allocate: " << Allocate
445                  << "\n");
446     Obj.updateSectionAddress(Section, (uint64_t)Addr);
447   }
448   else {
449     // Even if we didn't load the section, we need to record an entry for it
450     // to handle later processing (and by 'handle' I mean don't do anything
451     // with these sections).
452     Allocate = 0;
453     Addr = 0;
454     DEBUG(dbgs() << "emitSection SectionID: " << SectionID
455                  << " Name: " << Name
456                  << " obj addr: " << format("%p", data.data())
457                  << " new addr: 0"
458                  << " DataSize: " << DataSize
459                  << " StubBufSize: " << StubBufSize
460                  << " Allocate: " << Allocate
461                  << "\n");
462   }
463
464   Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
465   return SectionID;
466 }
467
468 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
469                                             const SectionRef &Section,
470                                             bool IsCode,
471                                             ObjSectionToIDMap &LocalSections) {
472
473   unsigned SectionID = 0;
474   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
475   if (i != LocalSections.end())
476     SectionID = i->second;
477   else {
478     SectionID = emitSection(Obj, Section, IsCode);
479     LocalSections[Section] = SectionID;
480   }
481   return SectionID;
482 }
483
484 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
485                                               unsigned SectionID) {
486   Relocations[SectionID].push_back(RE);
487 }
488
489 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
490                                              StringRef SymbolName) {
491   // Relocation by symbol.  If the symbol is found in the global symbol table,
492   // create an appropriate section relocation.  Otherwise, add it to
493   // ExternalSymbolRelocations.
494   SymbolTableMap::const_iterator Loc =
495       GlobalSymbolTable.find(SymbolName);
496   if (Loc == GlobalSymbolTable.end()) {
497     ExternalSymbolRelocations[SymbolName].push_back(RE);
498   } else {
499     // Copy the RE since we want to modify its addend.
500     RelocationEntry RECopy = RE;
501     RECopy.Addend += Loc->second.second;
502     Relocations[Loc->second.first].push_back(RECopy);
503   }
504 }
505
506 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
507   if (Arch == Triple::aarch64) {
508     // This stub has to be able to access the full address space,
509     // since symbol lookup won't necessarily find a handy, in-range,
510     // PLT stub for functions which could be anywhere.
511     uint32_t *StubAddr = (uint32_t*)Addr;
512
513     // Stub can use ip0 (== x16) to calculate address
514     *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
515     StubAddr++;
516     *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
517     StubAddr++;
518     *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
519     StubAddr++;
520     *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
521     StubAddr++;
522     *StubAddr = 0xd61f0200; // br ip0
523
524     return Addr;
525   } else if (Arch == Triple::arm) {
526     // TODO: There is only ARM far stub now. We should add the Thumb stub,
527     // and stubs for branches Thumb - ARM and ARM - Thumb.
528     uint32_t *StubAddr = (uint32_t*)Addr;
529     *StubAddr = 0xe51ff004; // ldr pc,<label>
530     return (uint8_t*)++StubAddr;
531   } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
532     uint32_t *StubAddr = (uint32_t*)Addr;
533     // 0:   3c190000        lui     t9,%hi(addr).
534     // 4:   27390000        addiu   t9,t9,%lo(addr).
535     // 8:   03200008        jr      t9.
536     // c:   00000000        nop.
537     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
538     const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
539
540     *StubAddr = LuiT9Instr;
541     StubAddr++;
542     *StubAddr = AdduiT9Instr;
543     StubAddr++;
544     *StubAddr = JrT9Instr;
545     StubAddr++;
546     *StubAddr = NopInstr;
547     return Addr;
548   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
549     // PowerPC64 stub: the address points to a function descriptor
550     // instead of the function itself. Load the function address
551     // on r11 and sets it to control register. Also loads the function
552     // TOC in r2 and environment pointer to r11.
553     writeInt32BE(Addr,    0x3D800000); // lis   r12, highest(addr)
554     writeInt32BE(Addr+4,  0x618C0000); // ori   r12, higher(addr)
555     writeInt32BE(Addr+8,  0x798C07C6); // sldi  r12, r12, 32
556     writeInt32BE(Addr+12, 0x658C0000); // oris  r12, r12, h(addr)
557     writeInt32BE(Addr+16, 0x618C0000); // ori   r12, r12, l(addr)
558     writeInt32BE(Addr+20, 0xF8410028); // std   r2,  40(r1)
559     writeInt32BE(Addr+24, 0xE96C0000); // ld    r11, 0(r12)
560     writeInt32BE(Addr+28, 0xE84C0008); // ld    r2,  0(r12)
561     writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
562     writeInt32BE(Addr+36, 0xE96C0010); // ld    r11, 16(r2)
563     writeInt32BE(Addr+40, 0x4E800420); // bctr
564
565     return Addr;
566   } else if (Arch == Triple::systemz) {
567     writeInt16BE(Addr,    0xC418);     // lgrl %r1,.+8
568     writeInt16BE(Addr+2,  0x0000);
569     writeInt16BE(Addr+4,  0x0004);
570     writeInt16BE(Addr+6,  0x07F1);     // brc 15,%r1
571     // 8-byte address stored at Addr + 8
572     return Addr;
573   } else if (Arch == Triple::x86_64) {
574     *Addr      = 0xFF; // jmp
575     *(Addr+1)  = 0x25; // rip
576     // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
577   }
578   return Addr;
579 }
580
581 // Assign an address to a symbol name and resolve all the relocations
582 // associated with it.
583 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
584                                              uint64_t Addr) {
585   // The address to use for relocation resolution is not
586   // the address of the local section buffer. We must be doing
587   // a remote execution environment of some sort. Relocations can't
588   // be applied until all the sections have been moved.  The client must
589   // trigger this with a call to MCJIT::finalize() or
590   // RuntimeDyld::resolveRelocations().
591   //
592   // Addr is a uint64_t because we can't assume the pointer width
593   // of the target is the same as that of the host. Just use a generic
594   // "big enough" type.
595   Sections[SectionID].LoadAddress = Addr;
596 }
597
598 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
599                                             uint64_t Value) {
600   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
601     const RelocationEntry &RE = Relocs[i];
602     // Ignore relocations for sections that were not loaded
603     if (Sections[RE.SectionID].Address == 0)
604       continue;
605     resolveRelocation(RE, Value);
606   }
607 }
608
609 void RuntimeDyldImpl::resolveExternalSymbols() {
610   while(!ExternalSymbolRelocations.empty()) {
611     StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
612
613     StringRef Name = i->first();
614     if (Name.size() == 0) {
615       // This is an absolute symbol, use an address of zero.
616       DEBUG(dbgs() << "Resolving absolute relocations." << "\n");
617       RelocationList &Relocs = i->second;
618       resolveRelocationList(Relocs, 0);
619     } else {
620       uint64_t Addr = 0;
621       SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
622       if (Loc == GlobalSymbolTable.end()) {
623           // This is an external symbol, try to get its address from
624           // MemoryManager.
625           Addr = MemMgr->getSymbolAddress(Name.data());
626           // The call to getSymbolAddress may have caused additional modules to
627           // be loaded, which may have added new entries to the
628           // ExternalSymbolRelocations map.  Consquently, we need to update our
629           // iterator.  This is also why retrieval of the relocation list
630           // associated with this symbol is deferred until below this point.
631           // New entries may have been added to the relocation list.
632           i = ExternalSymbolRelocations.find(Name);
633       } else {
634         // We found the symbol in our global table.  It was probably in a
635         // Module that we loaded previously.
636         SymbolLoc SymLoc = Loc->second;
637         Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
638       }
639
640       // FIXME: Implement error handling that doesn't kill the host program!
641       if (!Addr)
642         report_fatal_error("Program used external function '" + Name +
643                           "' which could not be resolved!");
644
645       updateGOTEntries(Name, Addr);
646       DEBUG(dbgs() << "Resolving relocations Name: " << Name
647               << "\t" << format("0x%lx", Addr)
648               << "\n");
649       // This list may have been updated when we called getSymbolAddress, so
650       // don't change this code to get the list earlier.
651       RelocationList &Relocs = i->second;
652       resolveRelocationList(Relocs, Addr);
653     }
654
655     ExternalSymbolRelocations.erase(i);
656   }
657 }
658
659
660 //===----------------------------------------------------------------------===//
661 // RuntimeDyld class implementation
662 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
663   // FIXME: There's a potential issue lurking here if a single instance of
664   // RuntimeDyld is used to load multiple objects.  The current implementation
665   // associates a single memory manager with a RuntimeDyld instance.  Even
666   // though the public class spawns a new 'impl' instance for each load,
667   // they share a single memory manager.  This can become a problem when page
668   // permissions are applied.
669   Dyld = 0;
670   MM = mm;
671 }
672
673 RuntimeDyld::~RuntimeDyld() {
674   delete Dyld;
675 }
676
677 ObjectImage *RuntimeDyld::loadObject(ObjectFile *InputObject) {
678   std::unique_ptr<ObjectImage> InputImage;
679
680   if (InputObject->isELF()) {
681     InputImage.reset(RuntimeDyldELF::createObjectImageFromFile(InputObject));
682     if (!Dyld)
683       Dyld = new RuntimeDyldELF(MM);
684   } else if (InputObject->isMachO()) {
685     InputImage.reset(RuntimeDyldMachO::createObjectImageFromFile(InputObject));
686     if (!Dyld)
687       Dyld = new RuntimeDyldMachO(MM);
688   } else
689     report_fatal_error("Incompatible object format!");
690
691   if (!Dyld->isCompatibleFile(InputObject))
692     report_fatal_error("Incompatible object format!");
693
694   Dyld->loadObject(InputImage.get());
695   return InputImage.release();
696 }
697
698 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
699   std::unique_ptr<ObjectImage> InputImage;
700   sys::fs::file_magic Type =
701     sys::fs::identify_magic(InputBuffer->getBuffer());
702
703   switch (Type) {
704   case sys::fs::file_magic::elf_relocatable:
705   case sys::fs::file_magic::elf_executable:
706   case sys::fs::file_magic::elf_shared_object:
707   case sys::fs::file_magic::elf_core:
708     InputImage.reset(RuntimeDyldELF::createObjectImage(InputBuffer));
709     if (!Dyld)
710       Dyld = new RuntimeDyldELF(MM);
711     break;
712   case sys::fs::file_magic::macho_object:
713   case sys::fs::file_magic::macho_executable:
714   case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
715   case sys::fs::file_magic::macho_core:
716   case sys::fs::file_magic::macho_preload_executable:
717   case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
718   case sys::fs::file_magic::macho_dynamic_linker:
719   case sys::fs::file_magic::macho_bundle:
720   case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
721   case sys::fs::file_magic::macho_dsym_companion:
722     InputImage.reset(RuntimeDyldMachO::createObjectImage(InputBuffer));
723     if (!Dyld)
724       Dyld = new RuntimeDyldMachO(MM);
725     break;
726   case sys::fs::file_magic::unknown:
727   case sys::fs::file_magic::bitcode:
728   case sys::fs::file_magic::archive:
729   case sys::fs::file_magic::coff_object:
730   case sys::fs::file_magic::coff_import_library:
731   case sys::fs::file_magic::pecoff_executable:
732   case sys::fs::file_magic::macho_universal_binary:
733   case sys::fs::file_magic::windows_resource:
734     report_fatal_error("Incompatible object format!");
735   }
736
737   if (!Dyld->isCompatibleFormat(InputBuffer))
738     report_fatal_error("Incompatible object format!");
739
740   Dyld->loadObject(InputImage.get());
741   return InputImage.release();
742 }
743
744 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
745   if (!Dyld)
746     return NULL;
747   return Dyld->getSymbolAddress(Name);
748 }
749
750 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
751   if (!Dyld)
752     return 0;
753   return Dyld->getSymbolLoadAddress(Name);
754 }
755
756 void RuntimeDyld::resolveRelocations() {
757   Dyld->resolveRelocations();
758 }
759
760 void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
761                                          uint64_t Addr) {
762   Dyld->reassignSectionAddress(SectionID, Addr);
763 }
764
765 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
766                                     uint64_t TargetAddress) {
767   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
768 }
769
770 StringRef RuntimeDyld::getErrorString() {
771   return Dyld->getErrorString();
772 }
773
774 void RuntimeDyld::registerEHFrames() {
775   if (Dyld)
776     Dyld->registerEHFrames();
777 }
778
779 void RuntimeDyld::deregisterEHFrames() {
780   if (Dyld)
781     Dyld->deregisterEHFrames();
782 }
783
784 } // end namespace llvm