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