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