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