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