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