LLVM API Documentation

RuntimeDyld.cpp
Go to the documentation of this file.
00001 //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Implementation of the MC-JIT runtime dynamic linker.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "dyld"
00015 #include "llvm/ExecutionEngine/RuntimeDyld.h"
00016 #include "JITRegistrar.h"
00017 #include "ObjectImageCommon.h"
00018 #include "RuntimeDyldELF.h"
00019 #include "RuntimeDyldImpl.h"
00020 #include "RuntimeDyldMachO.h"
00021 #include "llvm/Object/ELF.h"
00022 #include "llvm/Support/MathExtras.h"
00023 #include "llvm/Support/MutexGuard.h"
00024 
00025 using namespace llvm;
00026 using namespace llvm::object;
00027 
00028 // Empty out-of-line virtual destructor as the key function.
00029 RuntimeDyldImpl::~RuntimeDyldImpl() {}
00030 
00031 // Pin the JITRegistrar's and ObjectImage*'s vtables to this file.
00032 void JITRegistrar::anchor() {}
00033 void ObjectImage::anchor() {}
00034 void ObjectImageCommon::anchor() {}
00035 
00036 namespace llvm {
00037 
00038 void RuntimeDyldImpl::registerEHFrames() {}
00039 
00040 void RuntimeDyldImpl::deregisterEHFrames() {}
00041 
00042 // Resolve the relocations for all symbols we currently know about.
00043 void RuntimeDyldImpl::resolveRelocations() {
00044   MutexGuard locked(lock);
00045 
00046   // First, resolve relocations associated with external symbols.
00047   resolveExternalSymbols();
00048 
00049   // Just iterate over the sections we have and resolve all the relocations
00050   // in them. Gross overkill, but it gets the job done.
00051   for (int i = 0, e = Sections.size(); i != e; ++i) {
00052     // The Section here (Sections[i]) refers to the section in which the
00053     // symbol for the relocation is located.  The SectionID in the relocation
00054     // entry provides the section to which the relocation will be applied.
00055     uint64_t Addr = Sections[i].LoadAddress;
00056     DEBUG(dbgs() << "Resolving relocations Section #" << i << "\t"
00057                  << format("%p", (uint8_t *)Addr) << "\n");
00058     resolveRelocationList(Relocations[i], Addr);
00059     Relocations.erase(i);
00060   }
00061 }
00062 
00063 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
00064                                         uint64_t TargetAddress) {
00065   MutexGuard locked(lock);
00066   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
00067     if (Sections[i].Address == LocalAddress) {
00068       reassignSectionAddress(i, TargetAddress);
00069       return;
00070     }
00071   }
00072   llvm_unreachable("Attempting to remap address of unknown section!");
00073 }
00074 
00075 ObjectImage *RuntimeDyldImpl::loadObject(ObjectImage *InputObject) {
00076   MutexGuard locked(lock);
00077 
00078   std::unique_ptr<ObjectImage> Obj(InputObject);
00079   if (!Obj)
00080     return NULL;
00081 
00082   // Save information about our target
00083   Arch = (Triple::ArchType)Obj->getArch();
00084   IsTargetLittleEndian = Obj->getObjectFile()->isLittleEndian();
00085 
00086   // Compute the memory size required to load all sections to be loaded
00087   // and pass this information to the memory manager
00088   if (MemMgr->needsToReserveAllocationSpace()) {
00089     uint64_t CodeSize = 0, DataSizeRO = 0, DataSizeRW = 0;
00090     computeTotalAllocSize(*Obj, CodeSize, DataSizeRO, DataSizeRW);
00091     MemMgr->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
00092   }
00093 
00094   // Symbols found in this object
00095   StringMap<SymbolLoc> LocalSymbols;
00096   // Used sections from the object file
00097   ObjSectionToIDMap LocalSections;
00098 
00099   // Common symbols requiring allocation, with their sizes and alignments
00100   CommonSymbolMap CommonSymbols;
00101   // Maximum required total memory to allocate all common symbols
00102   uint64_t CommonSize = 0;
00103 
00104   // Parse symbols
00105   DEBUG(dbgs() << "Parse symbols:\n");
00106   for (symbol_iterator I = Obj->begin_symbols(), E = Obj->end_symbols(); I != E;
00107        ++I) {
00108     object::SymbolRef::Type SymType;
00109     StringRef Name;
00110     Check(I->getType(SymType));
00111     Check(I->getName(Name));
00112 
00113     uint32_t Flags = I->getFlags();
00114 
00115     bool IsCommon = Flags & SymbolRef::SF_Common;
00116     if (IsCommon) {
00117       // Add the common symbols to a list.  We'll allocate them all below.
00118       uint32_t Align;
00119       Check(I->getAlignment(Align));
00120       uint64_t Size = 0;
00121       Check(I->getSize(Size));
00122       CommonSize += Size + Align;
00123       CommonSymbols[*I] = CommonSymbolInfo(Size, Align);
00124     } else {
00125       if (SymType == object::SymbolRef::ST_Function ||
00126           SymType == object::SymbolRef::ST_Data ||
00127           SymType == object::SymbolRef::ST_Unknown) {
00128         uint64_t FileOffset;
00129         StringRef SectionData;
00130         bool IsCode;
00131         section_iterator SI = Obj->end_sections();
00132         Check(I->getFileOffset(FileOffset));
00133         Check(I->getSection(SI));
00134         if (SI == Obj->end_sections())
00135           continue;
00136         Check(SI->getContents(SectionData));
00137         Check(SI->isText(IsCode));
00138         const uint8_t *SymPtr =
00139             (const uint8_t *)Obj->getData().data() + (uintptr_t)FileOffset;
00140         uintptr_t SectOffset =
00141             (uintptr_t)(SymPtr - (const uint8_t *)SectionData.begin());
00142         unsigned SectionID =
00143             findOrEmitSection(*Obj, *SI, IsCode, LocalSections);
00144         LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
00145         DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOffset)
00146                      << " flags: " << Flags << " SID: " << SectionID
00147                      << " Offset: " << format("%p", SectOffset));
00148         GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
00149       }
00150     }
00151     DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
00152   }
00153 
00154   // Allocate common symbols
00155   if (CommonSize != 0)
00156     emitCommonSymbols(*Obj, CommonSymbols, CommonSize, LocalSymbols);
00157 
00158   // Parse and process relocations
00159   DEBUG(dbgs() << "Parse relocations:\n");
00160   for (section_iterator SI = Obj->begin_sections(), SE = Obj->end_sections();
00161        SI != SE; ++SI) {
00162     unsigned SectionID = 0;
00163     StubMap Stubs;
00164     section_iterator RelocatedSection = SI->getRelocatedSection();
00165 
00166     relocation_iterator I = SI->relocation_begin();
00167     relocation_iterator E = SI->relocation_end();
00168 
00169     if (I == E && !ProcessAllSections)
00170       continue;
00171 
00172     bool IsCode = false;
00173     Check(RelocatedSection->isText(IsCode));
00174     SectionID =
00175         findOrEmitSection(*Obj, *RelocatedSection, IsCode, LocalSections);
00176     DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
00177 
00178     for (; I != E;)
00179       I = processRelocationRef(SectionID, I, *Obj, LocalSections, LocalSymbols,
00180                                Stubs);
00181   }
00182 
00183   // Give the subclasses a chance to tie-up any loose ends.
00184   finalizeLoad(LocalSections);
00185 
00186   return Obj.release();
00187 }
00188 
00189 // A helper method for computeTotalAllocSize.
00190 // Computes the memory size required to allocate sections with the given sizes,
00191 // assuming that all sections are allocated with the given alignment
00192 static uint64_t
00193 computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
00194                                  uint64_t Alignment) {
00195   uint64_t TotalSize = 0;
00196   for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
00197     uint64_t AlignedSize =
00198         (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
00199     TotalSize += AlignedSize;
00200   }
00201   return TotalSize;
00202 }
00203 
00204 // Compute an upper bound of the memory size that is required to load all
00205 // sections
00206 void RuntimeDyldImpl::computeTotalAllocSize(ObjectImage &Obj,
00207                                             uint64_t &CodeSize,
00208                                             uint64_t &DataSizeRO,
00209                                             uint64_t &DataSizeRW) {
00210   // Compute the size of all sections required for execution
00211   std::vector<uint64_t> CodeSectionSizes;
00212   std::vector<uint64_t> ROSectionSizes;
00213   std::vector<uint64_t> RWSectionSizes;
00214   uint64_t MaxAlignment = sizeof(void *);
00215 
00216   // Collect sizes of all sections to be loaded;
00217   // also determine the max alignment of all sections
00218   for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
00219        SI != SE; ++SI) {
00220     const SectionRef &Section = *SI;
00221 
00222     bool IsRequired;
00223     Check(Section.isRequiredForExecution(IsRequired));
00224 
00225     // Consider only the sections that are required to be loaded for execution
00226     if (IsRequired) {
00227       uint64_t DataSize = 0;
00228       uint64_t Alignment64 = 0;
00229       bool IsCode = false;
00230       bool IsReadOnly = false;
00231       StringRef Name;
00232       Check(Section.getSize(DataSize));
00233       Check(Section.getAlignment(Alignment64));
00234       Check(Section.isText(IsCode));
00235       Check(Section.isReadOnlyData(IsReadOnly));
00236       Check(Section.getName(Name));
00237       unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
00238 
00239       uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
00240       uint64_t SectionSize = DataSize + StubBufSize;
00241 
00242       // The .eh_frame section (at least on Linux) needs an extra four bytes
00243       // padded
00244       // with zeroes added at the end.  For MachO objects, this section has a
00245       // slightly different name, so this won't have any effect for MachO
00246       // objects.
00247       if (Name == ".eh_frame")
00248         SectionSize += 4;
00249 
00250       if (SectionSize > 0) {
00251         // save the total size of the section
00252         if (IsCode) {
00253           CodeSectionSizes.push_back(SectionSize);
00254         } else if (IsReadOnly) {
00255           ROSectionSizes.push_back(SectionSize);
00256         } else {
00257           RWSectionSizes.push_back(SectionSize);
00258         }
00259         // update the max alignment
00260         if (Alignment > MaxAlignment) {
00261           MaxAlignment = Alignment;
00262         }
00263       }
00264     }
00265   }
00266 
00267   // Compute the size of all common symbols
00268   uint64_t CommonSize = 0;
00269   for (symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols(); I != E;
00270        ++I) {
00271     uint32_t Flags = I->getFlags();
00272     if (Flags & SymbolRef::SF_Common) {
00273       // Add the common symbols to a list.  We'll allocate them all below.
00274       uint64_t Size = 0;
00275       Check(I->getSize(Size));
00276       CommonSize += Size;
00277     }
00278   }
00279   if (CommonSize != 0) {
00280     RWSectionSizes.push_back(CommonSize);
00281   }
00282 
00283   // Compute the required allocation space for each different type of sections
00284   // (code, read-only data, read-write data) assuming that all sections are
00285   // allocated with the max alignment. Note that we cannot compute with the
00286   // individual alignments of the sections, because then the required size
00287   // depends on the order, in which the sections are allocated.
00288   CodeSize = computeAllocationSizeForSections(CodeSectionSizes, MaxAlignment);
00289   DataSizeRO = computeAllocationSizeForSections(ROSectionSizes, MaxAlignment);
00290   DataSizeRW = computeAllocationSizeForSections(RWSectionSizes, MaxAlignment);
00291 }
00292 
00293 // compute stub buffer size for the given section
00294 unsigned RuntimeDyldImpl::computeSectionStubBufSize(ObjectImage &Obj,
00295                                                     const SectionRef &Section) {
00296   unsigned StubSize = getMaxStubSize();
00297   if (StubSize == 0) {
00298     return 0;
00299   }
00300   // FIXME: this is an inefficient way to handle this. We should computed the
00301   // necessary section allocation size in loadObject by walking all the sections
00302   // once.
00303   unsigned StubBufSize = 0;
00304   for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
00305        SI != SE; ++SI) {
00306     section_iterator RelSecI = SI->getRelocatedSection();
00307     if (!(RelSecI == Section))
00308       continue;
00309 
00310     for (const RelocationRef &Reloc : SI->relocations()) {
00311       (void)Reloc;
00312       StubBufSize += StubSize;
00313     }
00314   }
00315 
00316   // Get section data size and alignment
00317   uint64_t Alignment64;
00318   uint64_t DataSize;
00319   Check(Section.getSize(DataSize));
00320   Check(Section.getAlignment(Alignment64));
00321 
00322   // Add stubbuf size alignment
00323   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
00324   unsigned StubAlignment = getStubAlignment();
00325   unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
00326   if (StubAlignment > EndAlignment)
00327     StubBufSize += StubAlignment - EndAlignment;
00328   return StubBufSize;
00329 }
00330 
00331 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
00332                                         const CommonSymbolMap &CommonSymbols,
00333                                         uint64_t TotalSize,
00334                                         SymbolTableMap &SymbolTable) {
00335   // Allocate memory for the section
00336   unsigned SectionID = Sections.size();
00337   uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void *),
00338                                               SectionID, StringRef(), false);
00339   if (!Addr)
00340     report_fatal_error("Unable to allocate memory for common symbols!");
00341   uint64_t Offset = 0;
00342   Sections.push_back(SectionEntry(StringRef(), Addr, TotalSize, 0));
00343   memset(Addr, 0, TotalSize);
00344 
00345   DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID << " new addr: "
00346                << format("%p", Addr) << " DataSize: " << TotalSize << "\n");
00347 
00348   // Assign the address of each symbol
00349   for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
00350        itEnd = CommonSymbols.end(); it != itEnd; ++it) {
00351     uint64_t Size = it->second.first;
00352     uint64_t Align = it->second.second;
00353     StringRef Name;
00354     it->first.getName(Name);
00355     if (Align) {
00356       // This symbol has an alignment requirement.
00357       uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
00358       Addr += AlignOffset;
00359       Offset += AlignOffset;
00360       DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
00361                    << format("%p\n", Addr));
00362     }
00363     Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
00364     SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
00365     Offset += Size;
00366     Addr += Size;
00367   }
00368 }
00369 
00370 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
00371                                       const SectionRef &Section, bool IsCode) {
00372 
00373   StringRef data;
00374   uint64_t Alignment64;
00375   Check(Section.getContents(data));
00376   Check(Section.getAlignment(Alignment64));
00377 
00378   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
00379   bool IsRequired;
00380   bool IsVirtual;
00381   bool IsZeroInit;
00382   bool IsReadOnly;
00383   uint64_t DataSize;
00384   unsigned PaddingSize = 0;
00385   unsigned StubBufSize = 0;
00386   StringRef Name;
00387   Check(Section.isRequiredForExecution(IsRequired));
00388   Check(Section.isVirtual(IsVirtual));
00389   Check(Section.isZeroInit(IsZeroInit));
00390   Check(Section.isReadOnlyData(IsReadOnly));
00391   Check(Section.getSize(DataSize));
00392   Check(Section.getName(Name));
00393 
00394   StubBufSize = computeSectionStubBufSize(Obj, Section);
00395 
00396   // The .eh_frame section (at least on Linux) needs an extra four bytes padded
00397   // with zeroes added at the end.  For MachO objects, this section has a
00398   // slightly different name, so this won't have any effect for MachO objects.
00399   if (Name == ".eh_frame")
00400     PaddingSize = 4;
00401 
00402   uintptr_t Allocate;
00403   unsigned SectionID = Sections.size();
00404   uint8_t *Addr;
00405   const char *pData = 0;
00406 
00407   // Some sections, such as debug info, don't need to be loaded for execution.
00408   // Leave those where they are.
00409   if (IsRequired) {
00410     Allocate = DataSize + PaddingSize + StubBufSize;
00411     Addr = IsCode ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID,
00412                                                 Name)
00413                   : MemMgr->allocateDataSection(Allocate, Alignment, SectionID,
00414                                                 Name, IsReadOnly);
00415     if (!Addr)
00416       report_fatal_error("Unable to allocate section memory!");
00417 
00418     // Virtual sections have no data in the object image, so leave pData = 0
00419     if (!IsVirtual)
00420       pData = data.data();
00421 
00422     // Zero-initialize or copy the data from the image
00423     if (IsZeroInit || IsVirtual)
00424       memset(Addr, 0, DataSize);
00425     else
00426       memcpy(Addr, pData, DataSize);
00427 
00428     // Fill in any extra bytes we allocated for padding
00429     if (PaddingSize != 0) {
00430       memset(Addr + DataSize, 0, PaddingSize);
00431       // Update the DataSize variable so that the stub offset is set correctly.
00432       DataSize += PaddingSize;
00433     }
00434 
00435     DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
00436                  << " obj addr: " << format("%p", pData)
00437                  << " new addr: " << format("%p", Addr)
00438                  << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
00439                  << " Allocate: " << Allocate << "\n");
00440     Obj.updateSectionAddress(Section, (uint64_t)Addr);
00441   } else {
00442     // Even if we didn't load the section, we need to record an entry for it
00443     // to handle later processing (and by 'handle' I mean don't do anything
00444     // with these sections).
00445     Allocate = 0;
00446     Addr = 0;
00447     DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
00448                  << " obj addr: " << format("%p", data.data()) << " new addr: 0"
00449                  << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
00450                  << " Allocate: " << Allocate << "\n");
00451   }
00452 
00453   Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
00454   return SectionID;
00455 }
00456 
00457 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
00458                                             const SectionRef &Section,
00459                                             bool IsCode,
00460                                             ObjSectionToIDMap &LocalSections) {
00461 
00462   unsigned SectionID = 0;
00463   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
00464   if (i != LocalSections.end())
00465     SectionID = i->second;
00466   else {
00467     SectionID = emitSection(Obj, Section, IsCode);
00468     LocalSections[Section] = SectionID;
00469   }
00470   return SectionID;
00471 }
00472 
00473 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
00474                                               unsigned SectionID) {
00475   Relocations[SectionID].push_back(RE);
00476 }
00477 
00478 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
00479                                              StringRef SymbolName) {
00480   // Relocation by symbol.  If the symbol is found in the global symbol table,
00481   // create an appropriate section relocation.  Otherwise, add it to
00482   // ExternalSymbolRelocations.
00483   SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
00484   if (Loc == GlobalSymbolTable.end()) {
00485     ExternalSymbolRelocations[SymbolName].push_back(RE);
00486   } else {
00487     // Copy the RE since we want to modify its addend.
00488     RelocationEntry RECopy = RE;
00489     RECopy.Addend += Loc->second.second;
00490     Relocations[Loc->second.first].push_back(RECopy);
00491   }
00492 }
00493 
00494 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
00495   if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
00496     // This stub has to be able to access the full address space,
00497     // since symbol lookup won't necessarily find a handy, in-range,
00498     // PLT stub for functions which could be anywhere.
00499     uint32_t *StubAddr = (uint32_t *)Addr;
00500 
00501     // Stub can use ip0 (== x16) to calculate address
00502     *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
00503     StubAddr++;
00504     *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
00505     StubAddr++;
00506     *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
00507     StubAddr++;
00508     *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
00509     StubAddr++;
00510     *StubAddr = 0xd61f0200; // br ip0
00511 
00512     return Addr;
00513   } else if (Arch == Triple::arm || Arch == Triple::armeb) {
00514     // TODO: There is only ARM far stub now. We should add the Thumb stub,
00515     // and stubs for branches Thumb - ARM and ARM - Thumb.
00516     uint32_t *StubAddr = (uint32_t *)Addr;
00517     *StubAddr = 0xe51ff004; // ldr pc,<label>
00518     return (uint8_t *)++StubAddr;
00519   } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
00520     uint32_t *StubAddr = (uint32_t *)Addr;
00521     // 0:   3c190000        lui     t9,%hi(addr).
00522     // 4:   27390000        addiu   t9,t9,%lo(addr).
00523     // 8:   03200008        jr      t9.
00524     // c:   00000000        nop.
00525     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
00526     const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
00527 
00528     *StubAddr = LuiT9Instr;
00529     StubAddr++;
00530     *StubAddr = AdduiT9Instr;
00531     StubAddr++;
00532     *StubAddr = JrT9Instr;
00533     StubAddr++;
00534     *StubAddr = NopInstr;
00535     return Addr;
00536   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
00537     // PowerPC64 stub: the address points to a function descriptor
00538     // instead of the function itself. Load the function address
00539     // on r11 and sets it to control register. Also loads the function
00540     // TOC in r2 and environment pointer to r11.
00541     writeInt32BE(Addr,    0x3D800000); // lis   r12, highest(addr)
00542     writeInt32BE(Addr+4,  0x618C0000); // ori   r12, higher(addr)
00543     writeInt32BE(Addr+8,  0x798C07C6); // sldi  r12, r12, 32
00544     writeInt32BE(Addr+12, 0x658C0000); // oris  r12, r12, h(addr)
00545     writeInt32BE(Addr+16, 0x618C0000); // ori   r12, r12, l(addr)
00546     writeInt32BE(Addr+20, 0xF8410028); // std   r2,  40(r1)
00547     writeInt32BE(Addr+24, 0xE96C0000); // ld    r11, 0(r12)
00548     writeInt32BE(Addr+28, 0xE84C0008); // ld    r2,  0(r12)
00549     writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
00550     writeInt32BE(Addr+36, 0xE96C0010); // ld    r11, 16(r2)
00551     writeInt32BE(Addr+40, 0x4E800420); // bctr
00552 
00553     return Addr;
00554   } else if (Arch == Triple::systemz) {
00555     writeInt16BE(Addr,    0xC418);     // lgrl %r1,.+8
00556     writeInt16BE(Addr+2,  0x0000);
00557     writeInt16BE(Addr+4,  0x0004);
00558     writeInt16BE(Addr+6,  0x07F1);     // brc 15,%r1
00559     // 8-byte address stored at Addr + 8
00560     return Addr;
00561   } else if (Arch == Triple::x86_64) {
00562     *Addr      = 0xFF; // jmp
00563     *(Addr+1)  = 0x25; // rip
00564     // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
00565   }
00566   return Addr;
00567 }
00568 
00569 // Assign an address to a symbol name and resolve all the relocations
00570 // associated with it.
00571 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
00572                                              uint64_t Addr) {
00573   // The address to use for relocation resolution is not
00574   // the address of the local section buffer. We must be doing
00575   // a remote execution environment of some sort. Relocations can't
00576   // be applied until all the sections have been moved.  The client must
00577   // trigger this with a call to MCJIT::finalize() or
00578   // RuntimeDyld::resolveRelocations().
00579   //
00580   // Addr is a uint64_t because we can't assume the pointer width
00581   // of the target is the same as that of the host. Just use a generic
00582   // "big enough" type.
00583   Sections[SectionID].LoadAddress = Addr;
00584 }
00585 
00586 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
00587                                             uint64_t Value) {
00588   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
00589     const RelocationEntry &RE = Relocs[i];
00590     // Ignore relocations for sections that were not loaded
00591     if (Sections[RE.SectionID].Address == 0)
00592       continue;
00593     resolveRelocation(RE, Value);
00594   }
00595 }
00596 
00597 void RuntimeDyldImpl::resolveExternalSymbols() {
00598   while (!ExternalSymbolRelocations.empty()) {
00599     StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
00600 
00601     StringRef Name = i->first();
00602     if (Name.size() == 0) {
00603       // This is an absolute symbol, use an address of zero.
00604       DEBUG(dbgs() << "Resolving absolute relocations."
00605                    << "\n");
00606       RelocationList &Relocs = i->second;
00607       resolveRelocationList(Relocs, 0);
00608     } else {
00609       uint64_t Addr = 0;
00610       SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
00611       if (Loc == GlobalSymbolTable.end()) {
00612         // This is an external symbol, try to get its address from
00613         // MemoryManager.
00614         Addr = MemMgr->getSymbolAddress(Name.data());
00615         // The call to getSymbolAddress may have caused additional modules to
00616         // be loaded, which may have added new entries to the
00617         // ExternalSymbolRelocations map.  Consquently, we need to update our
00618         // iterator.  This is also why retrieval of the relocation list
00619         // associated with this symbol is deferred until below this point.
00620         // New entries may have been added to the relocation list.
00621         i = ExternalSymbolRelocations.find(Name);
00622       } else {
00623         // We found the symbol in our global table.  It was probably in a
00624         // Module that we loaded previously.
00625         SymbolLoc SymLoc = Loc->second;
00626         Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
00627       }
00628 
00629       // FIXME: Implement error handling that doesn't kill the host program!
00630       if (!Addr)
00631         report_fatal_error("Program used external function '" + Name +
00632                            "' which could not be resolved!");
00633 
00634       updateGOTEntries(Name, Addr);
00635       DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
00636                    << format("0x%lx", Addr) << "\n");
00637       // This list may have been updated when we called getSymbolAddress, so
00638       // don't change this code to get the list earlier.
00639       RelocationList &Relocs = i->second;
00640       resolveRelocationList(Relocs, Addr);
00641     }
00642 
00643     ExternalSymbolRelocations.erase(i);
00644   }
00645 }
00646 
00647 //===----------------------------------------------------------------------===//
00648 // RuntimeDyld class implementation
00649 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
00650   // FIXME: There's a potential issue lurking here if a single instance of
00651   // RuntimeDyld is used to load multiple objects.  The current implementation
00652   // associates a single memory manager with a RuntimeDyld instance.  Even
00653   // though the public class spawns a new 'impl' instance for each load,
00654   // they share a single memory manager.  This can become a problem when page
00655   // permissions are applied.
00656   Dyld = 0;
00657   MM = mm;
00658   ProcessAllSections = false;
00659 }
00660 
00661 RuntimeDyld::~RuntimeDyld() { delete Dyld; }
00662 
00663 static std::unique_ptr<RuntimeDyldELF>
00664 createRuntimeDyldELF(RTDyldMemoryManager *MM, bool ProcessAllSections) {
00665   std::unique_ptr<RuntimeDyldELF> Dyld(new RuntimeDyldELF(MM));
00666   Dyld->setProcessAllSections(ProcessAllSections);
00667   return Dyld;
00668 }
00669 
00670 static std::unique_ptr<RuntimeDyldMachO>
00671 createRuntimeDyldMachO(RTDyldMemoryManager *MM, bool ProcessAllSections) {
00672   std::unique_ptr<RuntimeDyldMachO> Dyld(new RuntimeDyldMachO(MM));
00673   Dyld->setProcessAllSections(ProcessAllSections);
00674   return Dyld;
00675 }
00676 
00677 ObjectImage *RuntimeDyld::loadObject(ObjectFile *InputObject) {
00678   std::unique_ptr<ObjectImage> InputImage;
00679 
00680   if (InputObject->isELF()) {
00681     InputImage.reset(RuntimeDyldELF::createObjectImageFromFile(InputObject));
00682     if (!Dyld)
00683       Dyld = createRuntimeDyldELF(MM, ProcessAllSections).release();
00684   } else if (InputObject->isMachO()) {
00685     InputImage.reset(RuntimeDyldMachO::createObjectImageFromFile(InputObject));
00686     if (!Dyld)
00687       Dyld = createRuntimeDyldMachO(MM, ProcessAllSections).release();
00688   } else
00689     report_fatal_error("Incompatible object format!");
00690 
00691   if (!Dyld->isCompatibleFile(InputObject))
00692     report_fatal_error("Incompatible object format!");
00693 
00694   Dyld->loadObject(InputImage.get());
00695   return InputImage.release();
00696 }
00697 
00698 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
00699   std::unique_ptr<ObjectImage> InputImage;
00700   sys::fs::file_magic Type = sys::fs::identify_magic(InputBuffer->getBuffer());
00701 
00702   switch (Type) {
00703   case sys::fs::file_magic::elf_relocatable:
00704   case sys::fs::file_magic::elf_executable:
00705   case sys::fs::file_magic::elf_shared_object:
00706   case sys::fs::file_magic::elf_core:
00707     InputImage.reset(RuntimeDyldELF::createObjectImage(InputBuffer));
00708     if (!Dyld)
00709       Dyld = createRuntimeDyldELF(MM, ProcessAllSections).release();
00710     break;
00711   case sys::fs::file_magic::macho_object:
00712   case sys::fs::file_magic::macho_executable:
00713   case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
00714   case sys::fs::file_magic::macho_core:
00715   case sys::fs::file_magic::macho_preload_executable:
00716   case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
00717   case sys::fs::file_magic::macho_dynamic_linker:
00718   case sys::fs::file_magic::macho_bundle:
00719   case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
00720   case sys::fs::file_magic::macho_dsym_companion:
00721     InputImage.reset(RuntimeDyldMachO::createObjectImage(InputBuffer));
00722     if (!Dyld)
00723       Dyld = createRuntimeDyldMachO(MM, ProcessAllSections).release();
00724     break;
00725   case sys::fs::file_magic::unknown:
00726   case sys::fs::file_magic::bitcode:
00727   case sys::fs::file_magic::archive:
00728   case sys::fs::file_magic::coff_object:
00729   case sys::fs::file_magic::coff_import_library:
00730   case sys::fs::file_magic::pecoff_executable:
00731   case sys::fs::file_magic::macho_universal_binary:
00732   case sys::fs::file_magic::windows_resource:
00733     report_fatal_error("Incompatible object format!");
00734   }
00735 
00736   if (!Dyld->isCompatibleFormat(InputBuffer))
00737     report_fatal_error("Incompatible object format!");
00738 
00739   Dyld->loadObject(InputImage.get());
00740   return InputImage.release();
00741 }
00742 
00743 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
00744   if (!Dyld)
00745     return NULL;
00746   return Dyld->getSymbolAddress(Name);
00747 }
00748 
00749 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
00750   if (!Dyld)
00751     return 0;
00752   return Dyld->getSymbolLoadAddress(Name);
00753 }
00754 
00755 void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
00756 
00757 void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
00758   Dyld->reassignSectionAddress(SectionID, Addr);
00759 }
00760 
00761 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
00762                                     uint64_t TargetAddress) {
00763   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
00764 }
00765 
00766 bool RuntimeDyld::hasError() { return Dyld->hasError(); }
00767 
00768 StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
00769 
00770 void RuntimeDyld::registerEHFrames() {
00771   if (Dyld)
00772     Dyld->registerEHFrames();
00773 }
00774 
00775 void RuntimeDyld::deregisterEHFrames() {
00776   if (Dyld)
00777     Dyld->deregisterEHFrames();
00778 }
00779 
00780 } // end namespace llvm