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