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