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