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