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