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