xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
10b57cec5SDimitry Andric //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Implementation of the MC-JIT runtime dynamic linker.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/ExecutionEngine/RuntimeDyld.h"
140b57cec5SDimitry Andric #include "RuntimeDyldCOFF.h"
150b57cec5SDimitry Andric #include "RuntimeDyldELF.h"
160b57cec5SDimitry Andric #include "RuntimeDyldImpl.h"
170b57cec5SDimitry Andric #include "RuntimeDyldMachO.h"
180b57cec5SDimitry Andric #include "llvm/Object/COFF.h"
190b57cec5SDimitry Andric #include "llvm/Object/ELFObjectFile.h"
208bcb0991SDimitry Andric #include "llvm/Support/Alignment.h"
210b57cec5SDimitry Andric #include "llvm/Support/MSVCErrorWorkarounds.h"
220b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
230b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
248bcb0991SDimitry Andric #include <mutex>
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric #include <future>
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric using namespace llvm;
290b57cec5SDimitry Andric using namespace llvm::object;
300b57cec5SDimitry Andric 
310b57cec5SDimitry Andric #define DEBUG_TYPE "dyld"
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric namespace {
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric enum RuntimeDyldErrorCode {
360b57cec5SDimitry Andric   GenericRTDyldError = 1
370b57cec5SDimitry Andric };
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
400b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
410b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
420b57cec5SDimitry Andric class RuntimeDyldErrorCategory : public std::error_category {
430b57cec5SDimitry Andric public:
440b57cec5SDimitry Andric   const char *name() const noexcept override { return "runtimedyld"; }
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric   std::string message(int Condition) const override {
470b57cec5SDimitry Andric     switch (static_cast<RuntimeDyldErrorCode>(Condition)) {
480b57cec5SDimitry Andric       case GenericRTDyldError: return "Generic RuntimeDyld error";
490b57cec5SDimitry Andric     }
500b57cec5SDimitry Andric     llvm_unreachable("Unrecognized RuntimeDyldErrorCode");
510b57cec5SDimitry Andric   }
520b57cec5SDimitry Andric };
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric static ManagedStatic<RuntimeDyldErrorCategory> RTDyldErrorCategory;
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric }
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric char RuntimeDyldError::ID = 0;
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric void RuntimeDyldError::log(raw_ostream &OS) const {
610b57cec5SDimitry Andric   OS << ErrMsg << "\n";
620b57cec5SDimitry Andric }
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric std::error_code RuntimeDyldError::convertToErrorCode() const {
650b57cec5SDimitry Andric   return std::error_code(GenericRTDyldError, *RTDyldErrorCategory);
660b57cec5SDimitry Andric }
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric // Empty out-of-line virtual destructor as the key function.
690b57cec5SDimitry Andric RuntimeDyldImpl::~RuntimeDyldImpl() {}
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric // Pin LoadedObjectInfo's vtables to this file.
720b57cec5SDimitry Andric void RuntimeDyld::LoadedObjectInfo::anchor() {}
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric namespace llvm {
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric void RuntimeDyldImpl::registerEHFrames() {}
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric void RuntimeDyldImpl::deregisterEHFrames() {
790b57cec5SDimitry Andric   MemMgr.deregisterEHFrames();
800b57cec5SDimitry Andric }
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric #ifndef NDEBUG
830b57cec5SDimitry Andric static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
840b57cec5SDimitry Andric   dbgs() << "----- Contents of section " << S.getName() << " " << State
850b57cec5SDimitry Andric          << " -----";
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric   if (S.getAddress() == nullptr) {
880b57cec5SDimitry Andric     dbgs() << "\n          <section not emitted>\n";
890b57cec5SDimitry Andric     return;
900b57cec5SDimitry Andric   }
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   const unsigned ColsPerRow = 16;
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric   uint8_t *DataAddr = S.getAddress();
950b57cec5SDimitry Andric   uint64_t LoadAddr = S.getLoadAddress();
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric   unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
980b57cec5SDimitry Andric   unsigned BytesRemaining = S.getSize();
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric   if (StartPadding) {
1010b57cec5SDimitry Andric     dbgs() << "\n" << format("0x%016" PRIx64,
1020b57cec5SDimitry Andric                              LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
1030b57cec5SDimitry Andric     while (StartPadding--)
1040b57cec5SDimitry Andric       dbgs() << "   ";
1050b57cec5SDimitry Andric   }
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric   while (BytesRemaining > 0) {
1080b57cec5SDimitry Andric     if ((LoadAddr & (ColsPerRow - 1)) == 0)
1090b57cec5SDimitry Andric       dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric     dbgs() << " " << format("%02x", *DataAddr);
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric     ++DataAddr;
1140b57cec5SDimitry Andric     ++LoadAddr;
1150b57cec5SDimitry Andric     --BytesRemaining;
1160b57cec5SDimitry Andric   }
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   dbgs() << "\n";
1190b57cec5SDimitry Andric }
1200b57cec5SDimitry Andric #endif
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric // Resolve the relocations for all symbols we currently know about.
1230b57cec5SDimitry Andric void RuntimeDyldImpl::resolveRelocations() {
1248bcb0991SDimitry Andric   std::lock_guard<sys::Mutex> locked(lock);
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric   // Print out the sections prior to relocation.
127*0eae32dcSDimitry Andric   LLVM_DEBUG({
128*0eae32dcSDimitry Andric     for (SectionEntry &S : Sections)
129*0eae32dcSDimitry Andric       dumpSectionMemory(S, "before relocations");
130*0eae32dcSDimitry Andric   });
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric   // First, resolve relocations associated with external symbols.
1330b57cec5SDimitry Andric   if (auto Err = resolveExternalSymbols()) {
1340b57cec5SDimitry Andric     HasError = true;
1350b57cec5SDimitry Andric     ErrorStr = toString(std::move(Err));
1360b57cec5SDimitry Andric   }
1370b57cec5SDimitry Andric 
1380b57cec5SDimitry Andric   resolveLocalRelocations();
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   // Print out sections after relocation.
141*0eae32dcSDimitry Andric   LLVM_DEBUG({
142*0eae32dcSDimitry Andric     for (SectionEntry &S : Sections)
143*0eae32dcSDimitry Andric       dumpSectionMemory(S, "after relocations");
144*0eae32dcSDimitry Andric   });
1450b57cec5SDimitry Andric }
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric void RuntimeDyldImpl::resolveLocalRelocations() {
1480b57cec5SDimitry Andric   // Iterate over all outstanding relocations
149*0eae32dcSDimitry Andric   for (const auto &Rel : Relocations) {
1500b57cec5SDimitry Andric     // The Section here (Sections[i]) refers to the section in which the
1510b57cec5SDimitry Andric     // symbol for the relocation is located.  The SectionID in the relocation
1520b57cec5SDimitry Andric     // entry provides the section to which the relocation will be applied.
153*0eae32dcSDimitry Andric     unsigned Idx = Rel.first;
154fe6060f1SDimitry Andric     uint64_t Addr = getSectionLoadAddress(Idx);
1550b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"
1560b57cec5SDimitry Andric                       << format("%p", (uintptr_t)Addr) << "\n");
157*0eae32dcSDimitry Andric     resolveRelocationList(Rel.second, Addr);
1580b57cec5SDimitry Andric   }
1590b57cec5SDimitry Andric   Relocations.clear();
1600b57cec5SDimitry Andric }
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
1630b57cec5SDimitry Andric                                         uint64_t TargetAddress) {
1648bcb0991SDimitry Andric   std::lock_guard<sys::Mutex> locked(lock);
1650b57cec5SDimitry Andric   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
1660b57cec5SDimitry Andric     if (Sections[i].getAddress() == LocalAddress) {
1670b57cec5SDimitry Andric       reassignSectionAddress(i, TargetAddress);
1680b57cec5SDimitry Andric       return;
1690b57cec5SDimitry Andric     }
1700b57cec5SDimitry Andric   }
1710b57cec5SDimitry Andric   llvm_unreachable("Attempting to remap address of unknown section!");
1720b57cec5SDimitry Andric }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric static Error getOffset(const SymbolRef &Sym, SectionRef Sec,
1750b57cec5SDimitry Andric                        uint64_t &Result) {
1760b57cec5SDimitry Andric   Expected<uint64_t> AddressOrErr = Sym.getAddress();
1770b57cec5SDimitry Andric   if (!AddressOrErr)
1780b57cec5SDimitry Andric     return AddressOrErr.takeError();
1790b57cec5SDimitry Andric   Result = *AddressOrErr - Sec.getAddress();
1800b57cec5SDimitry Andric   return Error::success();
1810b57cec5SDimitry Andric }
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric Expected<RuntimeDyldImpl::ObjSectionToIDMap>
1840b57cec5SDimitry Andric RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
1858bcb0991SDimitry Andric   std::lock_guard<sys::Mutex> locked(lock);
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   // Save information about our target
1880b57cec5SDimitry Andric   Arch = (Triple::ArchType)Obj.getArch();
1890b57cec5SDimitry Andric   IsTargetLittleEndian = Obj.isLittleEndian();
1900b57cec5SDimitry Andric   setMipsABI(Obj);
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   // Compute the memory size required to load all sections to be loaded
1930b57cec5SDimitry Andric   // and pass this information to the memory manager
1940b57cec5SDimitry Andric   if (MemMgr.needsToReserveAllocationSpace()) {
1950b57cec5SDimitry Andric     uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;
1960b57cec5SDimitry Andric     uint32_t CodeAlign = 1, RODataAlign = 1, RWDataAlign = 1;
1970b57cec5SDimitry Andric     if (auto Err = computeTotalAllocSize(Obj,
1980b57cec5SDimitry Andric                                          CodeSize, CodeAlign,
1990b57cec5SDimitry Andric                                          RODataSize, RODataAlign,
2000b57cec5SDimitry Andric                                          RWDataSize, RWDataAlign))
2010b57cec5SDimitry Andric       return std::move(Err);
2020b57cec5SDimitry Andric     MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,
2030b57cec5SDimitry Andric                                   RWDataSize, RWDataAlign);
2040b57cec5SDimitry Andric   }
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   // Used sections from the object file
2070b57cec5SDimitry Andric   ObjSectionToIDMap LocalSections;
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   // Common symbols requiring allocation, with their sizes and alignments
2100b57cec5SDimitry Andric   CommonSymbolList CommonSymbolsToAllocate;
2110b57cec5SDimitry Andric 
2120b57cec5SDimitry Andric   uint64_t CommonSize = 0;
2130b57cec5SDimitry Andric   uint32_t CommonAlign = 0;
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   // First, collect all weak and common symbols. We need to know if stronger
2160b57cec5SDimitry Andric   // definitions occur elsewhere.
2170b57cec5SDimitry Andric   JITSymbolResolver::LookupSet ResponsibilitySet;
2180b57cec5SDimitry Andric   {
2190b57cec5SDimitry Andric     JITSymbolResolver::LookupSet Symbols;
2200b57cec5SDimitry Andric     for (auto &Sym : Obj.symbols()) {
2215ffd83dbSDimitry Andric       Expected<uint32_t> FlagsOrErr = Sym.getFlags();
2225ffd83dbSDimitry Andric       if (!FlagsOrErr)
2235ffd83dbSDimitry Andric         // TODO: Test this error.
2245ffd83dbSDimitry Andric         return FlagsOrErr.takeError();
2255ffd83dbSDimitry Andric       if ((*FlagsOrErr & SymbolRef::SF_Common) ||
2265ffd83dbSDimitry Andric           (*FlagsOrErr & SymbolRef::SF_Weak)) {
2270b57cec5SDimitry Andric         // Get symbol name.
2280b57cec5SDimitry Andric         if (auto NameOrErr = Sym.getName())
2290b57cec5SDimitry Andric           Symbols.insert(*NameOrErr);
2300b57cec5SDimitry Andric         else
2310b57cec5SDimitry Andric           return NameOrErr.takeError();
2320b57cec5SDimitry Andric       }
2330b57cec5SDimitry Andric     }
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     if (auto ResultOrErr = Resolver.getResponsibilitySet(Symbols))
2360b57cec5SDimitry Andric       ResponsibilitySet = std::move(*ResultOrErr);
2370b57cec5SDimitry Andric     else
2380b57cec5SDimitry Andric       return ResultOrErr.takeError();
2390b57cec5SDimitry Andric   }
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   // Parse symbols
2420b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Parse symbols:\n");
2430b57cec5SDimitry Andric   for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
2440b57cec5SDimitry Andric        ++I) {
2455ffd83dbSDimitry Andric     Expected<uint32_t> FlagsOrErr = I->getFlags();
2465ffd83dbSDimitry Andric     if (!FlagsOrErr)
2475ffd83dbSDimitry Andric       // TODO: Test this error.
2485ffd83dbSDimitry Andric       return FlagsOrErr.takeError();
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric     // Skip undefined symbols.
2515ffd83dbSDimitry Andric     if (*FlagsOrErr & SymbolRef::SF_Undefined)
2520b57cec5SDimitry Andric       continue;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric     // Get the symbol type.
2550b57cec5SDimitry Andric     object::SymbolRef::Type SymType;
2560b57cec5SDimitry Andric     if (auto SymTypeOrErr = I->getType())
2570b57cec5SDimitry Andric       SymType = *SymTypeOrErr;
2580b57cec5SDimitry Andric     else
2590b57cec5SDimitry Andric       return SymTypeOrErr.takeError();
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric     // Get symbol name.
2620b57cec5SDimitry Andric     StringRef Name;
2630b57cec5SDimitry Andric     if (auto NameOrErr = I->getName())
2640b57cec5SDimitry Andric       Name = *NameOrErr;
2650b57cec5SDimitry Andric     else
2660b57cec5SDimitry Andric       return NameOrErr.takeError();
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric     // Compute JIT symbol flags.
2690b57cec5SDimitry Andric     auto JITSymFlags = getJITSymbolFlags(*I);
2700b57cec5SDimitry Andric     if (!JITSymFlags)
2710b57cec5SDimitry Andric       return JITSymFlags.takeError();
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric     // If this is a weak definition, check to see if there's a strong one.
2740b57cec5SDimitry Andric     // If there is, skip this symbol (we won't be providing it: the strong
2750b57cec5SDimitry Andric     // definition will). If there's no strong definition, make this definition
2760b57cec5SDimitry Andric     // strong.
2770b57cec5SDimitry Andric     if (JITSymFlags->isWeak() || JITSymFlags->isCommon()) {
2780b57cec5SDimitry Andric       // First check whether there's already a definition in this instance.
2790b57cec5SDimitry Andric       if (GlobalSymbolTable.count(Name))
2800b57cec5SDimitry Andric         continue;
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric       // If we're not responsible for this symbol, skip it.
2830b57cec5SDimitry Andric       if (!ResponsibilitySet.count(Name))
2840b57cec5SDimitry Andric         continue;
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric       // Otherwise update the flags on the symbol to make this definition
2870b57cec5SDimitry Andric       // strong.
2880b57cec5SDimitry Andric       if (JITSymFlags->isWeak())
2890b57cec5SDimitry Andric         *JITSymFlags &= ~JITSymbolFlags::Weak;
2900b57cec5SDimitry Andric       if (JITSymFlags->isCommon()) {
2910b57cec5SDimitry Andric         *JITSymFlags &= ~JITSymbolFlags::Common;
2920b57cec5SDimitry Andric         uint32_t Align = I->getAlignment();
2930b57cec5SDimitry Andric         uint64_t Size = I->getCommonSize();
2940b57cec5SDimitry Andric         if (!CommonAlign)
2950b57cec5SDimitry Andric           CommonAlign = Align;
2960b57cec5SDimitry Andric         CommonSize = alignTo(CommonSize, Align) + Size;
2970b57cec5SDimitry Andric         CommonSymbolsToAllocate.push_back(*I);
2980b57cec5SDimitry Andric       }
2990b57cec5SDimitry Andric     }
3000b57cec5SDimitry Andric 
3015ffd83dbSDimitry Andric     if (*FlagsOrErr & SymbolRef::SF_Absolute &&
3020b57cec5SDimitry Andric         SymType != object::SymbolRef::ST_File) {
3030b57cec5SDimitry Andric       uint64_t Addr = 0;
3040b57cec5SDimitry Andric       if (auto AddrOrErr = I->getAddress())
3050b57cec5SDimitry Andric         Addr = *AddrOrErr;
3060b57cec5SDimitry Andric       else
3070b57cec5SDimitry Andric         return AddrOrErr.takeError();
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric       unsigned SectionID = AbsoluteSymbolSection;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name
3120b57cec5SDimitry Andric                         << " SID: " << SectionID
3130b57cec5SDimitry Andric                         << " Offset: " << format("%p", (uintptr_t)Addr)
3145ffd83dbSDimitry Andric                         << " flags: " << *FlagsOrErr << "\n");
315eaeb601bSDimitry Andric       if (!Name.empty()) // Skip absolute symbol relocations.
316eaeb601bSDimitry Andric         GlobalSymbolTable[Name] =
317eaeb601bSDimitry Andric             SymbolTableEntry(SectionID, Addr, *JITSymFlags);
3180b57cec5SDimitry Andric     } else if (SymType == object::SymbolRef::ST_Function ||
3190b57cec5SDimitry Andric                SymType == object::SymbolRef::ST_Data ||
3200b57cec5SDimitry Andric                SymType == object::SymbolRef::ST_Unknown ||
3210b57cec5SDimitry Andric                SymType == object::SymbolRef::ST_Other) {
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric       section_iterator SI = Obj.section_end();
3240b57cec5SDimitry Andric       if (auto SIOrErr = I->getSection())
3250b57cec5SDimitry Andric         SI = *SIOrErr;
3260b57cec5SDimitry Andric       else
3270b57cec5SDimitry Andric         return SIOrErr.takeError();
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric       if (SI == Obj.section_end())
3300b57cec5SDimitry Andric         continue;
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric       // Get symbol offset.
3330b57cec5SDimitry Andric       uint64_t SectOffset;
3340b57cec5SDimitry Andric       if (auto Err = getOffset(*I, *SI, SectOffset))
3350b57cec5SDimitry Andric         return std::move(Err);
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric       bool IsCode = SI->isText();
3380b57cec5SDimitry Andric       unsigned SectionID;
3390b57cec5SDimitry Andric       if (auto SectionIDOrErr =
3400b57cec5SDimitry Andric               findOrEmitSection(Obj, *SI, IsCode, LocalSections))
3410b57cec5SDimitry Andric         SectionID = *SectionIDOrErr;
3420b57cec5SDimitry Andric       else
3430b57cec5SDimitry Andric         return SectionIDOrErr.takeError();
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
3460b57cec5SDimitry Andric                         << " SID: " << SectionID
3470b57cec5SDimitry Andric                         << " Offset: " << format("%p", (uintptr_t)SectOffset)
3485ffd83dbSDimitry Andric                         << " flags: " << *FlagsOrErr << "\n");
349eaeb601bSDimitry Andric       if (!Name.empty()) // Skip absolute symbol relocations
3500b57cec5SDimitry Andric         GlobalSymbolTable[Name] =
3510b57cec5SDimitry Andric             SymbolTableEntry(SectionID, SectOffset, *JITSymFlags);
3520b57cec5SDimitry Andric     }
3530b57cec5SDimitry Andric   }
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   // Allocate common symbols
3560b57cec5SDimitry Andric   if (auto Err = emitCommonSymbols(Obj, CommonSymbolsToAllocate, CommonSize,
3570b57cec5SDimitry Andric                                    CommonAlign))
3580b57cec5SDimitry Andric     return std::move(Err);
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   // Parse and process relocations
3610b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Parse relocations:\n");
3620b57cec5SDimitry Andric   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
3630b57cec5SDimitry Andric        SI != SE; ++SI) {
3640b57cec5SDimitry Andric     StubMap Stubs;
3650b57cec5SDimitry Andric 
3668bcb0991SDimitry Andric     Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
3678bcb0991SDimitry Andric     if (!RelSecOrErr)
3688bcb0991SDimitry Andric       return RelSecOrErr.takeError();
3698bcb0991SDimitry Andric 
3708bcb0991SDimitry Andric     section_iterator RelocatedSection = *RelSecOrErr;
3710b57cec5SDimitry Andric     if (RelocatedSection == SE)
3720b57cec5SDimitry Andric       continue;
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric     relocation_iterator I = SI->relocation_begin();
3750b57cec5SDimitry Andric     relocation_iterator E = SI->relocation_end();
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric     if (I == E && !ProcessAllSections)
3780b57cec5SDimitry Andric       continue;
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric     bool IsCode = RelocatedSection->isText();
3810b57cec5SDimitry Andric     unsigned SectionID = 0;
3820b57cec5SDimitry Andric     if (auto SectionIDOrErr = findOrEmitSection(Obj, *RelocatedSection, IsCode,
3830b57cec5SDimitry Andric                                                 LocalSections))
3840b57cec5SDimitry Andric       SectionID = *SectionIDOrErr;
3850b57cec5SDimitry Andric     else
3860b57cec5SDimitry Andric       return SectionIDOrErr.takeError();
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric     for (; I != E;)
3910b57cec5SDimitry Andric       if (auto IOrErr = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs))
3920b57cec5SDimitry Andric         I = *IOrErr;
3930b57cec5SDimitry Andric       else
3940b57cec5SDimitry Andric         return IOrErr.takeError();
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric     // If there is a NotifyStubEmitted callback set, call it to register any
3970b57cec5SDimitry Andric     // stubs created for this section.
3980b57cec5SDimitry Andric     if (NotifyStubEmitted) {
3990b57cec5SDimitry Andric       StringRef FileName = Obj.getFileName();
4000b57cec5SDimitry Andric       StringRef SectionName = Sections[SectionID].getName();
4010b57cec5SDimitry Andric       for (auto &KV : Stubs) {
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric         auto &VR = KV.first;
4040b57cec5SDimitry Andric         uint64_t StubAddr = KV.second;
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric         // If this is a named stub, just call NotifyStubEmitted.
4070b57cec5SDimitry Andric         if (VR.SymbolName) {
4080b57cec5SDimitry Andric           NotifyStubEmitted(FileName, SectionName, VR.SymbolName, SectionID,
4090b57cec5SDimitry Andric                             StubAddr);
4100b57cec5SDimitry Andric           continue;
4110b57cec5SDimitry Andric         }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric         // Otherwise we will have to try a reverse lookup on the globla symbol table.
4140b57cec5SDimitry Andric         for (auto &GSTMapEntry : GlobalSymbolTable) {
4150b57cec5SDimitry Andric           StringRef SymbolName = GSTMapEntry.first();
4160b57cec5SDimitry Andric           auto &GSTEntry = GSTMapEntry.second;
4170b57cec5SDimitry Andric           if (GSTEntry.getSectionID() == VR.SectionID &&
4180b57cec5SDimitry Andric               GSTEntry.getOffset() == VR.Offset) {
4190b57cec5SDimitry Andric             NotifyStubEmitted(FileName, SectionName, SymbolName, SectionID,
4200b57cec5SDimitry Andric                               StubAddr);
4210b57cec5SDimitry Andric             break;
4220b57cec5SDimitry Andric           }
4230b57cec5SDimitry Andric         }
4240b57cec5SDimitry Andric       }
4250b57cec5SDimitry Andric     }
4260b57cec5SDimitry Andric   }
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   // Process remaining sections
4290b57cec5SDimitry Andric   if (ProcessAllSections) {
4300b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Process remaining sections:\n");
4310b57cec5SDimitry Andric     for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
4320b57cec5SDimitry Andric          SI != SE; ++SI) {
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric       /* Ignore already loaded sections */
4350b57cec5SDimitry Andric       if (LocalSections.find(*SI) != LocalSections.end())
4360b57cec5SDimitry Andric         continue;
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric       bool IsCode = SI->isText();
4390b57cec5SDimitry Andric       if (auto SectionIDOrErr =
4400b57cec5SDimitry Andric               findOrEmitSection(Obj, *SI, IsCode, LocalSections))
4410b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\tSectionID: " << (*SectionIDOrErr) << "\n");
4420b57cec5SDimitry Andric       else
4430b57cec5SDimitry Andric         return SectionIDOrErr.takeError();
4440b57cec5SDimitry Andric     }
4450b57cec5SDimitry Andric   }
4460b57cec5SDimitry Andric 
4470b57cec5SDimitry Andric   // Give the subclasses a chance to tie-up any loose ends.
4480b57cec5SDimitry Andric   if (auto Err = finalizeLoad(Obj, LocalSections))
4490b57cec5SDimitry Andric     return std::move(Err);
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric //   for (auto E : LocalSections)
4520b57cec5SDimitry Andric //     llvm::dbgs() << "Added: " << E.first.getRawDataRefImpl() << " -> " << E.second << "\n";
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   return LocalSections;
4550b57cec5SDimitry Andric }
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric // A helper method for computeTotalAllocSize.
4580b57cec5SDimitry Andric // Computes the memory size required to allocate sections with the given sizes,
4590b57cec5SDimitry Andric // assuming that all sections are allocated with the given alignment
4600b57cec5SDimitry Andric static uint64_t
4610b57cec5SDimitry Andric computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
4620b57cec5SDimitry Andric                                  uint64_t Alignment) {
4630b57cec5SDimitry Andric   uint64_t TotalSize = 0;
464*0eae32dcSDimitry Andric   for (uint64_t SectionSize : SectionSizes) {
4650b57cec5SDimitry Andric     uint64_t AlignedSize =
466*0eae32dcSDimitry Andric         (SectionSize + Alignment - 1) / Alignment * Alignment;
4670b57cec5SDimitry Andric     TotalSize += AlignedSize;
4680b57cec5SDimitry Andric   }
4690b57cec5SDimitry Andric   return TotalSize;
4700b57cec5SDimitry Andric }
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric static bool isRequiredForExecution(const SectionRef Section) {
4730b57cec5SDimitry Andric   const ObjectFile *Obj = Section.getObject();
4740b57cec5SDimitry Andric   if (isa<object::ELFObjectFileBase>(Obj))
4750b57cec5SDimitry Andric     return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
4760b57cec5SDimitry Andric   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
4770b57cec5SDimitry Andric     const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
4780b57cec5SDimitry Andric     // Avoid loading zero-sized COFF sections.
4790b57cec5SDimitry Andric     // In PE files, VirtualSize gives the section size, and SizeOfRawData
4800b57cec5SDimitry Andric     // may be zero for sections with content. In Obj files, SizeOfRawData
4810b57cec5SDimitry Andric     // gives the section size, and VirtualSize is always zero. Hence
4820b57cec5SDimitry Andric     // the need to check for both cases below.
4830b57cec5SDimitry Andric     bool HasContent =
4840b57cec5SDimitry Andric         (CoffSection->VirtualSize > 0) || (CoffSection->SizeOfRawData > 0);
4850b57cec5SDimitry Andric     bool IsDiscardable =
4860b57cec5SDimitry Andric         CoffSection->Characteristics &
4870b57cec5SDimitry Andric         (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
4880b57cec5SDimitry Andric     return HasContent && !IsDiscardable;
4890b57cec5SDimitry Andric   }
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   assert(isa<MachOObjectFile>(Obj));
4920b57cec5SDimitry Andric   return true;
4930b57cec5SDimitry Andric }
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric static bool isReadOnlyData(const SectionRef Section) {
4960b57cec5SDimitry Andric   const ObjectFile *Obj = Section.getObject();
4970b57cec5SDimitry Andric   if (isa<object::ELFObjectFileBase>(Obj))
4980b57cec5SDimitry Andric     return !(ELFSectionRef(Section).getFlags() &
4990b57cec5SDimitry Andric              (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
5000b57cec5SDimitry Andric   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
5010b57cec5SDimitry Andric     return ((COFFObj->getCOFFSection(Section)->Characteristics &
5020b57cec5SDimitry Andric              (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
5030b57cec5SDimitry Andric              | COFF::IMAGE_SCN_MEM_READ
5040b57cec5SDimitry Andric              | COFF::IMAGE_SCN_MEM_WRITE))
5050b57cec5SDimitry Andric              ==
5060b57cec5SDimitry Andric              (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
5070b57cec5SDimitry Andric              | COFF::IMAGE_SCN_MEM_READ));
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   assert(isa<MachOObjectFile>(Obj));
5100b57cec5SDimitry Andric   return false;
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric static bool isZeroInit(const SectionRef Section) {
5140b57cec5SDimitry Andric   const ObjectFile *Obj = Section.getObject();
5150b57cec5SDimitry Andric   if (isa<object::ELFObjectFileBase>(Obj))
5160b57cec5SDimitry Andric     return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
5170b57cec5SDimitry Andric   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
5180b57cec5SDimitry Andric     return COFFObj->getCOFFSection(Section)->Characteristics &
5190b57cec5SDimitry Andric             COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric   auto *MachO = cast<MachOObjectFile>(Obj);
5220b57cec5SDimitry Andric   unsigned SectionType = MachO->getSectionType(Section);
5230b57cec5SDimitry Andric   return SectionType == MachO::S_ZEROFILL ||
5240b57cec5SDimitry Andric          SectionType == MachO::S_GB_ZEROFILL;
5250b57cec5SDimitry Andric }
5260b57cec5SDimitry Andric 
527349cc55cSDimitry Andric static bool isTLS(const SectionRef Section) {
528349cc55cSDimitry Andric   const ObjectFile *Obj = Section.getObject();
529349cc55cSDimitry Andric   if (isa<object::ELFObjectFileBase>(Obj))
530349cc55cSDimitry Andric     return ELFSectionRef(Section).getFlags() & ELF::SHF_TLS;
531349cc55cSDimitry Andric   return false;
532349cc55cSDimitry Andric }
533349cc55cSDimitry Andric 
5340b57cec5SDimitry Andric // Compute an upper bound of the memory size that is required to load all
5350b57cec5SDimitry Andric // sections
5360b57cec5SDimitry Andric Error RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
5370b57cec5SDimitry Andric                                              uint64_t &CodeSize,
5380b57cec5SDimitry Andric                                              uint32_t &CodeAlign,
5390b57cec5SDimitry Andric                                              uint64_t &RODataSize,
5400b57cec5SDimitry Andric                                              uint32_t &RODataAlign,
5410b57cec5SDimitry Andric                                              uint64_t &RWDataSize,
5420b57cec5SDimitry Andric                                              uint32_t &RWDataAlign) {
5430b57cec5SDimitry Andric   // Compute the size of all sections required for execution
5440b57cec5SDimitry Andric   std::vector<uint64_t> CodeSectionSizes;
5450b57cec5SDimitry Andric   std::vector<uint64_t> ROSectionSizes;
5460b57cec5SDimitry Andric   std::vector<uint64_t> RWSectionSizes;
5470b57cec5SDimitry Andric 
5480b57cec5SDimitry Andric   // Collect sizes of all sections to be loaded;
5490b57cec5SDimitry Andric   // also determine the max alignment of all sections
5500b57cec5SDimitry Andric   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
5510b57cec5SDimitry Andric        SI != SE; ++SI) {
5520b57cec5SDimitry Andric     const SectionRef &Section = *SI;
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric     bool IsRequired = isRequiredForExecution(Section) || ProcessAllSections;
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric     // Consider only the sections that are required to be loaded for execution
5570b57cec5SDimitry Andric     if (IsRequired) {
5580b57cec5SDimitry Andric       uint64_t DataSize = Section.getSize();
5590b57cec5SDimitry Andric       uint64_t Alignment64 = Section.getAlignment();
5600b57cec5SDimitry Andric       unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
5610b57cec5SDimitry Andric       bool IsCode = Section.isText();
5620b57cec5SDimitry Andric       bool IsReadOnly = isReadOnlyData(Section);
563349cc55cSDimitry Andric       bool IsTLS = isTLS(Section);
5640b57cec5SDimitry Andric 
5658bcb0991SDimitry Andric       Expected<StringRef> NameOrErr = Section.getName();
5668bcb0991SDimitry Andric       if (!NameOrErr)
5678bcb0991SDimitry Andric         return NameOrErr.takeError();
5688bcb0991SDimitry Andric       StringRef Name = *NameOrErr;
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric       uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric       uint64_t PaddingSize = 0;
5730b57cec5SDimitry Andric       if (Name == ".eh_frame")
5740b57cec5SDimitry Andric         PaddingSize += 4;
5750b57cec5SDimitry Andric       if (StubBufSize != 0)
5760b57cec5SDimitry Andric         PaddingSize += getStubAlignment() - 1;
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric       uint64_t SectionSize = DataSize + PaddingSize + StubBufSize;
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric       // The .eh_frame section (at least on Linux) needs an extra four bytes
5810b57cec5SDimitry Andric       // padded
5820b57cec5SDimitry Andric       // with zeroes added at the end.  For MachO objects, this section has a
5830b57cec5SDimitry Andric       // slightly different name, so this won't have any effect for MachO
5840b57cec5SDimitry Andric       // objects.
5850b57cec5SDimitry Andric       if (Name == ".eh_frame")
5860b57cec5SDimitry Andric         SectionSize += 4;
5870b57cec5SDimitry Andric 
5880b57cec5SDimitry Andric       if (!SectionSize)
5890b57cec5SDimitry Andric         SectionSize = 1;
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric       if (IsCode) {
5920b57cec5SDimitry Andric         CodeAlign = std::max(CodeAlign, Alignment);
5930b57cec5SDimitry Andric         CodeSectionSizes.push_back(SectionSize);
5940b57cec5SDimitry Andric       } else if (IsReadOnly) {
5950b57cec5SDimitry Andric         RODataAlign = std::max(RODataAlign, Alignment);
5960b57cec5SDimitry Andric         ROSectionSizes.push_back(SectionSize);
597349cc55cSDimitry Andric       } else if (!IsTLS) {
5980b57cec5SDimitry Andric         RWDataAlign = std::max(RWDataAlign, Alignment);
5990b57cec5SDimitry Andric         RWSectionSizes.push_back(SectionSize);
6000b57cec5SDimitry Andric       }
6010b57cec5SDimitry Andric     }
6020b57cec5SDimitry Andric   }
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric   // Compute Global Offset Table size. If it is not zero we
6050b57cec5SDimitry Andric   // also update alignment, which is equal to a size of a
6060b57cec5SDimitry Andric   // single GOT entry.
6070b57cec5SDimitry Andric   if (unsigned GotSize = computeGOTSize(Obj)) {
6080b57cec5SDimitry Andric     RWSectionSizes.push_back(GotSize);
6090b57cec5SDimitry Andric     RWDataAlign = std::max<uint32_t>(RWDataAlign, getGOTEntrySize());
6100b57cec5SDimitry Andric   }
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric   // Compute the size of all common symbols
6130b57cec5SDimitry Andric   uint64_t CommonSize = 0;
6140b57cec5SDimitry Andric   uint32_t CommonAlign = 1;
6150b57cec5SDimitry Andric   for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
6160b57cec5SDimitry Andric        ++I) {
6175ffd83dbSDimitry Andric     Expected<uint32_t> FlagsOrErr = I->getFlags();
6185ffd83dbSDimitry Andric     if (!FlagsOrErr)
6195ffd83dbSDimitry Andric       // TODO: Test this error.
6205ffd83dbSDimitry Andric       return FlagsOrErr.takeError();
6215ffd83dbSDimitry Andric     if (*FlagsOrErr & SymbolRef::SF_Common) {
6220b57cec5SDimitry Andric       // Add the common symbols to a list.  We'll allocate them all below.
6230b57cec5SDimitry Andric       uint64_t Size = I->getCommonSize();
6240b57cec5SDimitry Andric       uint32_t Align = I->getAlignment();
6250b57cec5SDimitry Andric       // If this is the first common symbol, use its alignment as the alignment
6260b57cec5SDimitry Andric       // for the common symbols section.
6270b57cec5SDimitry Andric       if (CommonSize == 0)
6280b57cec5SDimitry Andric         CommonAlign = Align;
6290b57cec5SDimitry Andric       CommonSize = alignTo(CommonSize, Align) + Size;
6300b57cec5SDimitry Andric     }
6310b57cec5SDimitry Andric   }
6320b57cec5SDimitry Andric   if (CommonSize != 0) {
6330b57cec5SDimitry Andric     RWSectionSizes.push_back(CommonSize);
6340b57cec5SDimitry Andric     RWDataAlign = std::max(RWDataAlign, CommonAlign);
6350b57cec5SDimitry Andric   }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   // Compute the required allocation space for each different type of sections
6380b57cec5SDimitry Andric   // (code, read-only data, read-write data) assuming that all sections are
6390b57cec5SDimitry Andric   // allocated with the max alignment. Note that we cannot compute with the
6400b57cec5SDimitry Andric   // individual alignments of the sections, because then the required size
6410b57cec5SDimitry Andric   // depends on the order, in which the sections are allocated.
6420b57cec5SDimitry Andric   CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);
6430b57cec5SDimitry Andric   RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);
6440b57cec5SDimitry Andric   RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric   return Error::success();
6470b57cec5SDimitry Andric }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric // compute GOT size
6500b57cec5SDimitry Andric unsigned RuntimeDyldImpl::computeGOTSize(const ObjectFile &Obj) {
6510b57cec5SDimitry Andric   size_t GotEntrySize = getGOTEntrySize();
6520b57cec5SDimitry Andric   if (!GotEntrySize)
6530b57cec5SDimitry Andric     return 0;
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric   size_t GotSize = 0;
6560b57cec5SDimitry Andric   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
6570b57cec5SDimitry Andric        SI != SE; ++SI) {
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric     for (const RelocationRef &Reloc : SI->relocations())
6600b57cec5SDimitry Andric       if (relocationNeedsGot(Reloc))
6610b57cec5SDimitry Andric         GotSize += GotEntrySize;
6620b57cec5SDimitry Andric   }
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   return GotSize;
6650b57cec5SDimitry Andric }
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric // compute stub buffer size for the given section
6680b57cec5SDimitry Andric unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
6690b57cec5SDimitry Andric                                                     const SectionRef &Section) {
670fe6060f1SDimitry Andric   if (!MemMgr.allowStubAllocation()) {
671fe6060f1SDimitry Andric     return 0;
672fe6060f1SDimitry Andric   }
673fe6060f1SDimitry Andric 
6740b57cec5SDimitry Andric   unsigned StubSize = getMaxStubSize();
6750b57cec5SDimitry Andric   if (StubSize == 0) {
6760b57cec5SDimitry Andric     return 0;
6770b57cec5SDimitry Andric   }
6780b57cec5SDimitry Andric   // FIXME: this is an inefficient way to handle this. We should computed the
6790b57cec5SDimitry Andric   // necessary section allocation size in loadObject by walking all the sections
6800b57cec5SDimitry Andric   // once.
6810b57cec5SDimitry Andric   unsigned StubBufSize = 0;
6820b57cec5SDimitry Andric   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
6830b57cec5SDimitry Andric        SI != SE; ++SI) {
6848bcb0991SDimitry Andric 
6858bcb0991SDimitry Andric     Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
6868bcb0991SDimitry Andric     if (!RelSecOrErr)
687349cc55cSDimitry Andric       report_fatal_error(Twine(toString(RelSecOrErr.takeError())));
6888bcb0991SDimitry Andric 
6898bcb0991SDimitry Andric     section_iterator RelSecI = *RelSecOrErr;
6900b57cec5SDimitry Andric     if (!(RelSecI == Section))
6910b57cec5SDimitry Andric       continue;
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric     for (const RelocationRef &Reloc : SI->relocations())
6940b57cec5SDimitry Andric       if (relocationNeedsStub(Reloc))
6950b57cec5SDimitry Andric         StubBufSize += StubSize;
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   // Get section data size and alignment
6990b57cec5SDimitry Andric   uint64_t DataSize = Section.getSize();
7000b57cec5SDimitry Andric   uint64_t Alignment64 = Section.getAlignment();
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   // Add stubbuf size alignment
7030b57cec5SDimitry Andric   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
7040b57cec5SDimitry Andric   unsigned StubAlignment = getStubAlignment();
7050b57cec5SDimitry Andric   unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
7060b57cec5SDimitry Andric   if (StubAlignment > EndAlignment)
7070b57cec5SDimitry Andric     StubBufSize += StubAlignment - EndAlignment;
7080b57cec5SDimitry Andric   return StubBufSize;
7090b57cec5SDimitry Andric }
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
7120b57cec5SDimitry Andric                                              unsigned Size) const {
7130b57cec5SDimitry Andric   uint64_t Result = 0;
7140b57cec5SDimitry Andric   if (IsTargetLittleEndian) {
7150b57cec5SDimitry Andric     Src += Size - 1;
7160b57cec5SDimitry Andric     while (Size--)
7170b57cec5SDimitry Andric       Result = (Result << 8) | *Src--;
7180b57cec5SDimitry Andric   } else
7190b57cec5SDimitry Andric     while (Size--)
7200b57cec5SDimitry Andric       Result = (Result << 8) | *Src++;
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric   return Result;
7230b57cec5SDimitry Andric }
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
7260b57cec5SDimitry Andric                                           unsigned Size) const {
7270b57cec5SDimitry Andric   if (IsTargetLittleEndian) {
7280b57cec5SDimitry Andric     while (Size--) {
7290b57cec5SDimitry Andric       *Dst++ = Value & 0xFF;
7300b57cec5SDimitry Andric       Value >>= 8;
7310b57cec5SDimitry Andric     }
7320b57cec5SDimitry Andric   } else {
7330b57cec5SDimitry Andric     Dst += Size - 1;
7340b57cec5SDimitry Andric     while (Size--) {
7350b57cec5SDimitry Andric       *Dst-- = Value & 0xFF;
7360b57cec5SDimitry Andric       Value >>= 8;
7370b57cec5SDimitry Andric     }
7380b57cec5SDimitry Andric   }
7390b57cec5SDimitry Andric }
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric Expected<JITSymbolFlags>
7420b57cec5SDimitry Andric RuntimeDyldImpl::getJITSymbolFlags(const SymbolRef &SR) {
7430b57cec5SDimitry Andric   return JITSymbolFlags::fromObjectSymbol(SR);
7440b57cec5SDimitry Andric }
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric Error RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
7470b57cec5SDimitry Andric                                          CommonSymbolList &SymbolsToAllocate,
7480b57cec5SDimitry Andric                                          uint64_t CommonSize,
7490b57cec5SDimitry Andric                                          uint32_t CommonAlign) {
7500b57cec5SDimitry Andric   if (SymbolsToAllocate.empty())
7510b57cec5SDimitry Andric     return Error::success();
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   // Allocate memory for the section
7540b57cec5SDimitry Andric   unsigned SectionID = Sections.size();
7550b57cec5SDimitry Andric   uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, CommonAlign, SectionID,
7560b57cec5SDimitry Andric                                              "<common symbols>", false);
7570b57cec5SDimitry Andric   if (!Addr)
7580b57cec5SDimitry Andric     report_fatal_error("Unable to allocate memory for common symbols!");
7590b57cec5SDimitry Andric   uint64_t Offset = 0;
7600b57cec5SDimitry Andric   Sections.push_back(
7610b57cec5SDimitry Andric       SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));
7620b57cec5SDimitry Andric   memset(Addr, 0, CommonSize);
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
7650b57cec5SDimitry Andric                     << " new addr: " << format("%p", Addr)
7660b57cec5SDimitry Andric                     << " DataSize: " << CommonSize << "\n");
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   // Assign the address of each symbol
7690b57cec5SDimitry Andric   for (auto &Sym : SymbolsToAllocate) {
7708bcb0991SDimitry Andric     uint32_t Alignment = Sym.getAlignment();
7710b57cec5SDimitry Andric     uint64_t Size = Sym.getCommonSize();
7720b57cec5SDimitry Andric     StringRef Name;
7730b57cec5SDimitry Andric     if (auto NameOrErr = Sym.getName())
7740b57cec5SDimitry Andric       Name = *NameOrErr;
7750b57cec5SDimitry Andric     else
7760b57cec5SDimitry Andric       return NameOrErr.takeError();
7778bcb0991SDimitry Andric     if (Alignment) {
7780b57cec5SDimitry Andric       // This symbol has an alignment requirement.
7798bcb0991SDimitry Andric       uint64_t AlignOffset =
7808bcb0991SDimitry Andric           offsetToAlignment((uint64_t)Addr, Align(Alignment));
7810b57cec5SDimitry Andric       Addr += AlignOffset;
7820b57cec5SDimitry Andric       Offset += AlignOffset;
7830b57cec5SDimitry Andric     }
7840b57cec5SDimitry Andric     auto JITSymFlags = getJITSymbolFlags(Sym);
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric     if (!JITSymFlags)
7870b57cec5SDimitry Andric       return JITSymFlags.takeError();
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
7900b57cec5SDimitry Andric                       << format("%p", Addr) << "\n");
791eaeb601bSDimitry Andric     if (!Name.empty()) // Skip absolute symbol relocations.
7920b57cec5SDimitry Andric       GlobalSymbolTable[Name] =
7930b57cec5SDimitry Andric           SymbolTableEntry(SectionID, Offset, std::move(*JITSymFlags));
7940b57cec5SDimitry Andric     Offset += Size;
7950b57cec5SDimitry Andric     Addr += Size;
7960b57cec5SDimitry Andric   }
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric   return Error::success();
7990b57cec5SDimitry Andric }
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric Expected<unsigned>
8020b57cec5SDimitry Andric RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
8030b57cec5SDimitry Andric                              const SectionRef &Section,
8040b57cec5SDimitry Andric                              bool IsCode) {
8050b57cec5SDimitry Andric   StringRef data;
8060b57cec5SDimitry Andric   uint64_t Alignment64 = Section.getAlignment();
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
8090b57cec5SDimitry Andric   unsigned PaddingSize = 0;
8100b57cec5SDimitry Andric   unsigned StubBufSize = 0;
8110b57cec5SDimitry Andric   bool IsRequired = isRequiredForExecution(Section);
8120b57cec5SDimitry Andric   bool IsVirtual = Section.isVirtual();
8130b57cec5SDimitry Andric   bool IsZeroInit = isZeroInit(Section);
8140b57cec5SDimitry Andric   bool IsReadOnly = isReadOnlyData(Section);
815349cc55cSDimitry Andric   bool IsTLS = isTLS(Section);
8160b57cec5SDimitry Andric   uint64_t DataSize = Section.getSize();
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   // An alignment of 0 (at least with ELF) is identical to an alignment of 1,
8190b57cec5SDimitry Andric   // while being more "polite".  Other formats do not support 0-aligned sections
8200b57cec5SDimitry Andric   // anyway, so we should guarantee that the alignment is always at least 1.
8210b57cec5SDimitry Andric   Alignment = std::max(1u, Alignment);
8220b57cec5SDimitry Andric 
8238bcb0991SDimitry Andric   Expected<StringRef> NameOrErr = Section.getName();
8248bcb0991SDimitry Andric   if (!NameOrErr)
8258bcb0991SDimitry Andric     return NameOrErr.takeError();
8268bcb0991SDimitry Andric   StringRef Name = *NameOrErr;
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   StubBufSize = computeSectionStubBufSize(Obj, Section);
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric   // The .eh_frame section (at least on Linux) needs an extra four bytes padded
8310b57cec5SDimitry Andric   // with zeroes added at the end.  For MachO objects, this section has a
8320b57cec5SDimitry Andric   // slightly different name, so this won't have any effect for MachO objects.
8330b57cec5SDimitry Andric   if (Name == ".eh_frame")
8340b57cec5SDimitry Andric     PaddingSize = 4;
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   uintptr_t Allocate;
8370b57cec5SDimitry Andric   unsigned SectionID = Sections.size();
8380b57cec5SDimitry Andric   uint8_t *Addr;
839349cc55cSDimitry Andric   uint64_t LoadAddress = 0;
8400b57cec5SDimitry Andric   const char *pData = nullptr;
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric   // If this section contains any bits (i.e. isn't a virtual or bss section),
8430b57cec5SDimitry Andric   // grab a reference to them.
8440b57cec5SDimitry Andric   if (!IsVirtual && !IsZeroInit) {
8450b57cec5SDimitry Andric     // In either case, set the location of the unrelocated section in memory,
8460b57cec5SDimitry Andric     // since we still process relocations for it even if we're not applying them.
8470b57cec5SDimitry Andric     if (Expected<StringRef> E = Section.getContents())
8480b57cec5SDimitry Andric       data = *E;
8490b57cec5SDimitry Andric     else
8500b57cec5SDimitry Andric       return E.takeError();
8510b57cec5SDimitry Andric     pData = data.data();
8520b57cec5SDimitry Andric   }
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   // If there are any stubs then the section alignment needs to be at least as
8550b57cec5SDimitry Andric   // high as stub alignment or padding calculations may by incorrect when the
8560b57cec5SDimitry Andric   // section is remapped.
8570b57cec5SDimitry Andric   if (StubBufSize != 0) {
8580b57cec5SDimitry Andric     Alignment = std::max(Alignment, getStubAlignment());
8590b57cec5SDimitry Andric     PaddingSize += getStubAlignment() - 1;
8600b57cec5SDimitry Andric   }
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   // Some sections, such as debug info, don't need to be loaded for execution.
8630b57cec5SDimitry Andric   // Process those only if explicitly requested.
8640b57cec5SDimitry Andric   if (IsRequired || ProcessAllSections) {
8650b57cec5SDimitry Andric     Allocate = DataSize + PaddingSize + StubBufSize;
8660b57cec5SDimitry Andric     if (!Allocate)
8670b57cec5SDimitry Andric       Allocate = 1;
868349cc55cSDimitry Andric     if (IsTLS) {
869349cc55cSDimitry Andric       auto TLSSection =
870349cc55cSDimitry Andric           MemMgr.allocateTLSSection(Allocate, Alignment, SectionID, Name);
871349cc55cSDimitry Andric       Addr = TLSSection.InitializationImage;
872349cc55cSDimitry Andric       LoadAddress = TLSSection.Offset;
873349cc55cSDimitry Andric     } else if (IsCode) {
874349cc55cSDimitry Andric       Addr = MemMgr.allocateCodeSection(Allocate, Alignment, SectionID, Name);
875349cc55cSDimitry Andric     } else {
876349cc55cSDimitry Andric       Addr = MemMgr.allocateDataSection(Allocate, Alignment, SectionID, Name,
877349cc55cSDimitry Andric                                         IsReadOnly);
878349cc55cSDimitry Andric     }
8790b57cec5SDimitry Andric     if (!Addr)
8800b57cec5SDimitry Andric       report_fatal_error("Unable to allocate section memory!");
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric     // Zero-initialize or copy the data from the image
8830b57cec5SDimitry Andric     if (IsZeroInit || IsVirtual)
8840b57cec5SDimitry Andric       memset(Addr, 0, DataSize);
8850b57cec5SDimitry Andric     else
8860b57cec5SDimitry Andric       memcpy(Addr, pData, DataSize);
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric     // Fill in any extra bytes we allocated for padding
8890b57cec5SDimitry Andric     if (PaddingSize != 0) {
8900b57cec5SDimitry Andric       memset(Addr + DataSize, 0, PaddingSize);
8910b57cec5SDimitry Andric       // Update the DataSize variable to include padding.
8920b57cec5SDimitry Andric       DataSize += PaddingSize;
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric       // Align DataSize to stub alignment if we have any stubs (PaddingSize will
8950b57cec5SDimitry Andric       // have been increased above to account for this).
8960b57cec5SDimitry Andric       if (StubBufSize > 0)
8970b57cec5SDimitry Andric         DataSize &= -(uint64_t)getStubAlignment();
8980b57cec5SDimitry Andric     }
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: "
9010b57cec5SDimitry Andric                       << Name << " obj addr: " << format("%p", pData)
9020b57cec5SDimitry Andric                       << " new addr: " << format("%p", Addr) << " DataSize: "
9030b57cec5SDimitry Andric                       << DataSize << " StubBufSize: " << StubBufSize
9040b57cec5SDimitry Andric                       << " Allocate: " << Allocate << "\n");
9050b57cec5SDimitry Andric   } else {
9060b57cec5SDimitry Andric     // Even if we didn't load the section, we need to record an entry for it
9070b57cec5SDimitry Andric     // to handle later processing (and by 'handle' I mean don't do anything
9080b57cec5SDimitry Andric     // with these sections).
9090b57cec5SDimitry Andric     Allocate = 0;
9100b57cec5SDimitry Andric     Addr = nullptr;
9110b57cec5SDimitry Andric     LLVM_DEBUG(
9120b57cec5SDimitry Andric         dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
9130b57cec5SDimitry Andric                << " obj addr: " << format("%p", data.data()) << " new addr: 0"
9140b57cec5SDimitry Andric                << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
9150b57cec5SDimitry Andric                << " Allocate: " << Allocate << "\n");
9160b57cec5SDimitry Andric   }
9170b57cec5SDimitry Andric 
9180b57cec5SDimitry Andric   Sections.push_back(
9190b57cec5SDimitry Andric       SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));
9200b57cec5SDimitry Andric 
921349cc55cSDimitry Andric   // The load address of a TLS section is not equal to the address of its
922349cc55cSDimitry Andric   // initialization image
923349cc55cSDimitry Andric   if (IsTLS)
924349cc55cSDimitry Andric     Sections.back().setLoadAddress(LoadAddress);
9250b57cec5SDimitry Andric   // Debug info sections are linked as if their load address was zero
9260b57cec5SDimitry Andric   if (!IsRequired)
9270b57cec5SDimitry Andric     Sections.back().setLoadAddress(0);
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   return SectionID;
9300b57cec5SDimitry Andric }
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric Expected<unsigned>
9330b57cec5SDimitry Andric RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
9340b57cec5SDimitry Andric                                    const SectionRef &Section,
9350b57cec5SDimitry Andric                                    bool IsCode,
9360b57cec5SDimitry Andric                                    ObjSectionToIDMap &LocalSections) {
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   unsigned SectionID = 0;
9390b57cec5SDimitry Andric   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
9400b57cec5SDimitry Andric   if (i != LocalSections.end())
9410b57cec5SDimitry Andric     SectionID = i->second;
9420b57cec5SDimitry Andric   else {
9430b57cec5SDimitry Andric     if (auto SectionIDOrErr = emitSection(Obj, Section, IsCode))
9440b57cec5SDimitry Andric       SectionID = *SectionIDOrErr;
9450b57cec5SDimitry Andric     else
9460b57cec5SDimitry Andric       return SectionIDOrErr.takeError();
9470b57cec5SDimitry Andric     LocalSections[Section] = SectionID;
9480b57cec5SDimitry Andric   }
9490b57cec5SDimitry Andric   return SectionID;
9500b57cec5SDimitry Andric }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
9530b57cec5SDimitry Andric                                               unsigned SectionID) {
9540b57cec5SDimitry Andric   Relocations[SectionID].push_back(RE);
9550b57cec5SDimitry Andric }
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
9580b57cec5SDimitry Andric                                              StringRef SymbolName) {
9590b57cec5SDimitry Andric   // Relocation by symbol.  If the symbol is found in the global symbol table,
9600b57cec5SDimitry Andric   // create an appropriate section relocation.  Otherwise, add it to
9610b57cec5SDimitry Andric   // ExternalSymbolRelocations.
9620b57cec5SDimitry Andric   RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
9630b57cec5SDimitry Andric   if (Loc == GlobalSymbolTable.end()) {
9640b57cec5SDimitry Andric     ExternalSymbolRelocations[SymbolName].push_back(RE);
9650b57cec5SDimitry Andric   } else {
966eaeb601bSDimitry Andric     assert(!SymbolName.empty() &&
967eaeb601bSDimitry Andric            "Empty symbol should not be in GlobalSymbolTable");
9680b57cec5SDimitry Andric     // Copy the RE since we want to modify its addend.
9690b57cec5SDimitry Andric     RelocationEntry RECopy = RE;
9700b57cec5SDimitry Andric     const auto &SymInfo = Loc->second;
9710b57cec5SDimitry Andric     RECopy.Addend += SymInfo.getOffset();
9720b57cec5SDimitry Andric     Relocations[SymInfo.getSectionID()].push_back(RECopy);
9730b57cec5SDimitry Andric   }
9740b57cec5SDimitry Andric }
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
9770b57cec5SDimitry Andric                                              unsigned AbiVariant) {
9788bcb0991SDimitry Andric   if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be ||
9798bcb0991SDimitry Andric       Arch == Triple::aarch64_32) {
9800b57cec5SDimitry Andric     // This stub has to be able to access the full address space,
9810b57cec5SDimitry Andric     // since symbol lookup won't necessarily find a handy, in-range,
9820b57cec5SDimitry Andric     // PLT stub for functions which could be anywhere.
9830b57cec5SDimitry Andric     // Stub can use ip0 (== x16) to calculate address
9840b57cec5SDimitry Andric     writeBytesUnaligned(0xd2e00010, Addr,    4); // movz ip0, #:abs_g3:<addr>
9850b57cec5SDimitry Andric     writeBytesUnaligned(0xf2c00010, Addr+4,  4); // movk ip0, #:abs_g2_nc:<addr>
9860b57cec5SDimitry Andric     writeBytesUnaligned(0xf2a00010, Addr+8,  4); // movk ip0, #:abs_g1_nc:<addr>
9870b57cec5SDimitry Andric     writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
9880b57cec5SDimitry Andric     writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric     return Addr;
9910b57cec5SDimitry Andric   } else if (Arch == Triple::arm || Arch == Triple::armeb) {
9920b57cec5SDimitry Andric     // TODO: There is only ARM far stub now. We should add the Thumb stub,
9930b57cec5SDimitry Andric     // and stubs for branches Thumb - ARM and ARM - Thumb.
9940b57cec5SDimitry Andric     writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc, [pc, #-4]
9950b57cec5SDimitry Andric     return Addr + 4;
9960b57cec5SDimitry Andric   } else if (IsMipsO32ABI || IsMipsN32ABI) {
9970b57cec5SDimitry Andric     // 0:   3c190000        lui     t9,%hi(addr).
9980b57cec5SDimitry Andric     // 4:   27390000        addiu   t9,t9,%lo(addr).
9990b57cec5SDimitry Andric     // 8:   03200008        jr      t9.
10000b57cec5SDimitry Andric     // c:   00000000        nop.
10010b57cec5SDimitry Andric     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
10020b57cec5SDimitry Andric     const unsigned NopInstr = 0x0;
10030b57cec5SDimitry Andric     unsigned JrT9Instr = 0x03200008;
10040b57cec5SDimitry Andric     if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_32R6 ||
10050b57cec5SDimitry Andric         (AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
10060b57cec5SDimitry Andric       JrT9Instr = 0x03200009;
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric     writeBytesUnaligned(LuiT9Instr, Addr, 4);
10090b57cec5SDimitry Andric     writeBytesUnaligned(AdduiT9Instr, Addr + 4, 4);
10100b57cec5SDimitry Andric     writeBytesUnaligned(JrT9Instr, Addr + 8, 4);
10110b57cec5SDimitry Andric     writeBytesUnaligned(NopInstr, Addr + 12, 4);
10120b57cec5SDimitry Andric     return Addr;
10130b57cec5SDimitry Andric   } else if (IsMipsN64ABI) {
10140b57cec5SDimitry Andric     // 0:   3c190000        lui     t9,%highest(addr).
10150b57cec5SDimitry Andric     // 4:   67390000        daddiu  t9,t9,%higher(addr).
10160b57cec5SDimitry Andric     // 8:   0019CC38        dsll    t9,t9,16.
10170b57cec5SDimitry Andric     // c:   67390000        daddiu  t9,t9,%hi(addr).
10180b57cec5SDimitry Andric     // 10:  0019CC38        dsll    t9,t9,16.
10190b57cec5SDimitry Andric     // 14:  67390000        daddiu  t9,t9,%lo(addr).
10200b57cec5SDimitry Andric     // 18:  03200008        jr      t9.
10210b57cec5SDimitry Andric     // 1c:  00000000        nop.
10220b57cec5SDimitry Andric     const unsigned LuiT9Instr = 0x3c190000, DaddiuT9Instr = 0x67390000,
10230b57cec5SDimitry Andric                    DsllT9Instr = 0x19CC38;
10240b57cec5SDimitry Andric     const unsigned NopInstr = 0x0;
10250b57cec5SDimitry Andric     unsigned JrT9Instr = 0x03200008;
10260b57cec5SDimitry Andric     if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
10270b57cec5SDimitry Andric       JrT9Instr = 0x03200009;
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric     writeBytesUnaligned(LuiT9Instr, Addr, 4);
10300b57cec5SDimitry Andric     writeBytesUnaligned(DaddiuT9Instr, Addr + 4, 4);
10310b57cec5SDimitry Andric     writeBytesUnaligned(DsllT9Instr, Addr + 8, 4);
10320b57cec5SDimitry Andric     writeBytesUnaligned(DaddiuT9Instr, Addr + 12, 4);
10330b57cec5SDimitry Andric     writeBytesUnaligned(DsllT9Instr, Addr + 16, 4);
10340b57cec5SDimitry Andric     writeBytesUnaligned(DaddiuT9Instr, Addr + 20, 4);
10350b57cec5SDimitry Andric     writeBytesUnaligned(JrT9Instr, Addr + 24, 4);
10360b57cec5SDimitry Andric     writeBytesUnaligned(NopInstr, Addr + 28, 4);
10370b57cec5SDimitry Andric     return Addr;
10380b57cec5SDimitry Andric   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
10390b57cec5SDimitry Andric     // Depending on which version of the ELF ABI is in use, we need to
10400b57cec5SDimitry Andric     // generate one of two variants of the stub.  They both start with
10410b57cec5SDimitry Andric     // the same sequence to load the target address into r12.
10420b57cec5SDimitry Andric     writeInt32BE(Addr,    0x3D800000); // lis   r12, highest(addr)
10430b57cec5SDimitry Andric     writeInt32BE(Addr+4,  0x618C0000); // ori   r12, higher(addr)
10440b57cec5SDimitry Andric     writeInt32BE(Addr+8,  0x798C07C6); // sldi  r12, r12, 32
10450b57cec5SDimitry Andric     writeInt32BE(Addr+12, 0x658C0000); // oris  r12, r12, h(addr)
10460b57cec5SDimitry Andric     writeInt32BE(Addr+16, 0x618C0000); // ori   r12, r12, l(addr)
10470b57cec5SDimitry Andric     if (AbiVariant == 2) {
10480b57cec5SDimitry Andric       // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
10490b57cec5SDimitry Andric       // The address is already in r12 as required by the ABI.  Branch to it.
10500b57cec5SDimitry Andric       writeInt32BE(Addr+20, 0xF8410018); // std   r2,  24(r1)
10510b57cec5SDimitry Andric       writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
10520b57cec5SDimitry Andric       writeInt32BE(Addr+28, 0x4E800420); // bctr
10530b57cec5SDimitry Andric     } else {
10540b57cec5SDimitry Andric       // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
10550b57cec5SDimitry Andric       // Load the function address on r11 and sets it to control register. Also
10560b57cec5SDimitry Andric       // loads the function TOC in r2 and environment pointer to r11.
10570b57cec5SDimitry Andric       writeInt32BE(Addr+20, 0xF8410028); // std   r2,  40(r1)
10580b57cec5SDimitry Andric       writeInt32BE(Addr+24, 0xE96C0000); // ld    r11, 0(r12)
10590b57cec5SDimitry Andric       writeInt32BE(Addr+28, 0xE84C0008); // ld    r2,  0(r12)
10600b57cec5SDimitry Andric       writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
10610b57cec5SDimitry Andric       writeInt32BE(Addr+36, 0xE96C0010); // ld    r11, 16(r2)
10620b57cec5SDimitry Andric       writeInt32BE(Addr+40, 0x4E800420); // bctr
10630b57cec5SDimitry Andric     }
10640b57cec5SDimitry Andric     return Addr;
10650b57cec5SDimitry Andric   } else if (Arch == Triple::systemz) {
10660b57cec5SDimitry Andric     writeInt16BE(Addr,    0xC418);     // lgrl %r1,.+8
10670b57cec5SDimitry Andric     writeInt16BE(Addr+2,  0x0000);
10680b57cec5SDimitry Andric     writeInt16BE(Addr+4,  0x0004);
10690b57cec5SDimitry Andric     writeInt16BE(Addr+6,  0x07F1);     // brc 15,%r1
10700b57cec5SDimitry Andric     // 8-byte address stored at Addr + 8
10710b57cec5SDimitry Andric     return Addr;
10720b57cec5SDimitry Andric   } else if (Arch == Triple::x86_64) {
10730b57cec5SDimitry Andric     *Addr      = 0xFF; // jmp
10740b57cec5SDimitry Andric     *(Addr+1)  = 0x25; // rip
10750b57cec5SDimitry Andric     // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
10760b57cec5SDimitry Andric   } else if (Arch == Triple::x86) {
10770b57cec5SDimitry Andric     *Addr      = 0xE9; // 32-bit pc-relative jump.
10780b57cec5SDimitry Andric   }
10790b57cec5SDimitry Andric   return Addr;
10800b57cec5SDimitry Andric }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric // Assign an address to a symbol name and resolve all the relocations
10830b57cec5SDimitry Andric // associated with it.
10840b57cec5SDimitry Andric void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
10850b57cec5SDimitry Andric                                              uint64_t Addr) {
10860b57cec5SDimitry Andric   // The address to use for relocation resolution is not
10870b57cec5SDimitry Andric   // the address of the local section buffer. We must be doing
10880b57cec5SDimitry Andric   // a remote execution environment of some sort. Relocations can't
10890b57cec5SDimitry Andric   // be applied until all the sections have been moved.  The client must
10900b57cec5SDimitry Andric   // trigger this with a call to MCJIT::finalize() or
10910b57cec5SDimitry Andric   // RuntimeDyld::resolveRelocations().
10920b57cec5SDimitry Andric   //
10930b57cec5SDimitry Andric   // Addr is a uint64_t because we can't assume the pointer width
10940b57cec5SDimitry Andric   // of the target is the same as that of the host. Just use a generic
10950b57cec5SDimitry Andric   // "big enough" type.
10960b57cec5SDimitry Andric   LLVM_DEBUG(
10970b57cec5SDimitry Andric       dbgs() << "Reassigning address for section " << SectionID << " ("
10980b57cec5SDimitry Andric              << Sections[SectionID].getName() << "): "
10990b57cec5SDimitry Andric              << format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())
11000b57cec5SDimitry Andric              << " -> " << format("0x%016" PRIx64, Addr) << "\n");
11010b57cec5SDimitry Andric   Sections[SectionID].setLoadAddress(Addr);
11020b57cec5SDimitry Andric }
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
11050b57cec5SDimitry Andric                                             uint64_t Value) {
11060b57cec5SDimitry Andric   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
11070b57cec5SDimitry Andric     const RelocationEntry &RE = Relocs[i];
11080b57cec5SDimitry Andric     // Ignore relocations for sections that were not loaded
1109fe6060f1SDimitry Andric     if (RE.SectionID != AbsoluteSymbolSection &&
1110fe6060f1SDimitry Andric         Sections[RE.SectionID].getAddress() == nullptr)
11110b57cec5SDimitry Andric       continue;
11120b57cec5SDimitry Andric     resolveRelocation(RE, Value);
11130b57cec5SDimitry Andric   }
11140b57cec5SDimitry Andric }
11150b57cec5SDimitry Andric 
11160b57cec5SDimitry Andric void RuntimeDyldImpl::applyExternalSymbolRelocations(
11170b57cec5SDimitry Andric     const StringMap<JITEvaluatedSymbol> ExternalSymbolMap) {
1118fe6060f1SDimitry Andric   for (auto &RelocKV : ExternalSymbolRelocations) {
1119fe6060f1SDimitry Andric     StringRef Name = RelocKV.first();
1120fe6060f1SDimitry Andric     RelocationList &Relocs = RelocKV.second;
11210b57cec5SDimitry Andric     if (Name.size() == 0) {
11220b57cec5SDimitry Andric       // This is an absolute symbol, use an address of zero.
11230b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Resolving absolute relocations."
11240b57cec5SDimitry Andric                         << "\n");
11250b57cec5SDimitry Andric       resolveRelocationList(Relocs, 0);
11260b57cec5SDimitry Andric     } else {
11270b57cec5SDimitry Andric       uint64_t Addr = 0;
11280b57cec5SDimitry Andric       JITSymbolFlags Flags;
11290b57cec5SDimitry Andric       RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
11300b57cec5SDimitry Andric       if (Loc == GlobalSymbolTable.end()) {
11310b57cec5SDimitry Andric         auto RRI = ExternalSymbolMap.find(Name);
11320b57cec5SDimitry Andric         assert(RRI != ExternalSymbolMap.end() && "No result for symbol");
11330b57cec5SDimitry Andric         Addr = RRI->second.getAddress();
11340b57cec5SDimitry Andric         Flags = RRI->second.getFlags();
11350b57cec5SDimitry Andric       } else {
11360b57cec5SDimitry Andric         // We found the symbol in our global table.  It was probably in a
11370b57cec5SDimitry Andric         // Module that we loaded previously.
11380b57cec5SDimitry Andric         const auto &SymInfo = Loc->second;
11390b57cec5SDimitry Andric         Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
11400b57cec5SDimitry Andric                SymInfo.getOffset();
11410b57cec5SDimitry Andric         Flags = SymInfo.getFlags();
11420b57cec5SDimitry Andric       }
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric       // FIXME: Implement error handling that doesn't kill the host program!
1145fe6060f1SDimitry Andric       if (!Addr && !Resolver.allowsZeroSymbols())
1146349cc55cSDimitry Andric         report_fatal_error(Twine("Program used external function '") + Name +
11470b57cec5SDimitry Andric                            "' which could not be resolved!");
11480b57cec5SDimitry Andric 
11490b57cec5SDimitry Andric       // If Resolver returned UINT64_MAX, the client wants to handle this symbol
11500b57cec5SDimitry Andric       // manually and we shouldn't resolve its relocations.
11510b57cec5SDimitry Andric       if (Addr != UINT64_MAX) {
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric         // Tweak the address based on the symbol flags if necessary.
11540b57cec5SDimitry Andric         // For example, this is used by RuntimeDyldMachOARM to toggle the low bit
11550b57cec5SDimitry Andric         // if the target symbol is Thumb.
11560b57cec5SDimitry Andric         Addr = modifyAddressBasedOnFlags(Addr, Flags);
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
11590b57cec5SDimitry Andric                           << format("0x%lx", Addr) << "\n");
11600b57cec5SDimitry Andric         resolveRelocationList(Relocs, Addr);
11610b57cec5SDimitry Andric       }
11620b57cec5SDimitry Andric     }
11630b57cec5SDimitry Andric   }
1164fe6060f1SDimitry Andric   ExternalSymbolRelocations.clear();
11650b57cec5SDimitry Andric }
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric Error RuntimeDyldImpl::resolveExternalSymbols() {
11680b57cec5SDimitry Andric   StringMap<JITEvaluatedSymbol> ExternalSymbolMap;
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   // Resolution can trigger emission of more symbols, so iterate until
11710b57cec5SDimitry Andric   // we've resolved *everything*.
11720b57cec5SDimitry Andric   {
11730b57cec5SDimitry Andric     JITSymbolResolver::LookupSet ResolvedSymbols;
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric     while (true) {
11760b57cec5SDimitry Andric       JITSymbolResolver::LookupSet NewSymbols;
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric       for (auto &RelocKV : ExternalSymbolRelocations) {
11790b57cec5SDimitry Andric         StringRef Name = RelocKV.first();
11800b57cec5SDimitry Andric         if (!Name.empty() && !GlobalSymbolTable.count(Name) &&
11810b57cec5SDimitry Andric             !ResolvedSymbols.count(Name))
11820b57cec5SDimitry Andric           NewSymbols.insert(Name);
11830b57cec5SDimitry Andric       }
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric       if (NewSymbols.empty())
11860b57cec5SDimitry Andric         break;
11870b57cec5SDimitry Andric 
11880b57cec5SDimitry Andric #ifdef _MSC_VER
11890b57cec5SDimitry Andric       using ExpectedLookupResult =
11900b57cec5SDimitry Andric           MSVCPExpected<JITSymbolResolver::LookupResult>;
11910b57cec5SDimitry Andric #else
11920b57cec5SDimitry Andric       using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
11930b57cec5SDimitry Andric #endif
11940b57cec5SDimitry Andric 
11950b57cec5SDimitry Andric       auto NewSymbolsP = std::make_shared<std::promise<ExpectedLookupResult>>();
11960b57cec5SDimitry Andric       auto NewSymbolsF = NewSymbolsP->get_future();
11970b57cec5SDimitry Andric       Resolver.lookup(NewSymbols,
11980b57cec5SDimitry Andric                       [=](Expected<JITSymbolResolver::LookupResult> Result) {
11990b57cec5SDimitry Andric                         NewSymbolsP->set_value(std::move(Result));
12000b57cec5SDimitry Andric                       });
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric       auto NewResolverResults = NewSymbolsF.get();
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric       if (!NewResolverResults)
12050b57cec5SDimitry Andric         return NewResolverResults.takeError();
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric       assert(NewResolverResults->size() == NewSymbols.size() &&
12080b57cec5SDimitry Andric              "Should have errored on unresolved symbols");
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric       for (auto &RRKV : *NewResolverResults) {
12110b57cec5SDimitry Andric         assert(!ResolvedSymbols.count(RRKV.first) && "Redundant resolution?");
12120b57cec5SDimitry Andric         ExternalSymbolMap.insert(RRKV);
12130b57cec5SDimitry Andric         ResolvedSymbols.insert(RRKV.first);
12140b57cec5SDimitry Andric       }
12150b57cec5SDimitry Andric     }
12160b57cec5SDimitry Andric   }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   applyExternalSymbolRelocations(ExternalSymbolMap);
12190b57cec5SDimitry Andric 
12200b57cec5SDimitry Andric   return Error::success();
12210b57cec5SDimitry Andric }
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric void RuntimeDyldImpl::finalizeAsync(
12248bcb0991SDimitry Andric     std::unique_ptr<RuntimeDyldImpl> This,
1225e8d8bef9SDimitry Andric     unique_function<void(object::OwningBinary<object::ObjectFile>,
1226e8d8bef9SDimitry Andric                          std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
12275ffd83dbSDimitry Andric         OnEmitted,
1228e8d8bef9SDimitry Andric     object::OwningBinary<object::ObjectFile> O,
1229e8d8bef9SDimitry Andric     std::unique_ptr<RuntimeDyld::LoadedObjectInfo> Info) {
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric   auto SharedThis = std::shared_ptr<RuntimeDyldImpl>(std::move(This));
12320b57cec5SDimitry Andric   auto PostResolveContinuation =
1233e8d8bef9SDimitry Andric       [SharedThis, OnEmitted = std::move(OnEmitted), O = std::move(O),
1234e8d8bef9SDimitry Andric        Info = std::move(Info)](
12358bcb0991SDimitry Andric           Expected<JITSymbolResolver::LookupResult> Result) mutable {
12360b57cec5SDimitry Andric         if (!Result) {
1237e8d8bef9SDimitry Andric           OnEmitted(std::move(O), std::move(Info), Result.takeError());
12380b57cec5SDimitry Andric           return;
12390b57cec5SDimitry Andric         }
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric         /// Copy the result into a StringMap, where the keys are held by value.
12420b57cec5SDimitry Andric         StringMap<JITEvaluatedSymbol> Resolved;
12430b57cec5SDimitry Andric         for (auto &KV : *Result)
12440b57cec5SDimitry Andric           Resolved[KV.first] = KV.second;
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric         SharedThis->applyExternalSymbolRelocations(Resolved);
12470b57cec5SDimitry Andric         SharedThis->resolveLocalRelocations();
12480b57cec5SDimitry Andric         SharedThis->registerEHFrames();
12490b57cec5SDimitry Andric         std::string ErrMsg;
12500b57cec5SDimitry Andric         if (SharedThis->MemMgr.finalizeMemory(&ErrMsg))
1251e8d8bef9SDimitry Andric           OnEmitted(std::move(O), std::move(Info),
12525ffd83dbSDimitry Andric                     make_error<StringError>(std::move(ErrMsg),
12530b57cec5SDimitry Andric                                             inconvertibleErrorCode()));
12540b57cec5SDimitry Andric         else
1255e8d8bef9SDimitry Andric           OnEmitted(std::move(O), std::move(Info), Error::success());
12560b57cec5SDimitry Andric       };
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric   JITSymbolResolver::LookupSet Symbols;
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric   for (auto &RelocKV : SharedThis->ExternalSymbolRelocations) {
12610b57cec5SDimitry Andric     StringRef Name = RelocKV.first();
1262eaeb601bSDimitry Andric     if (Name.empty()) // Skip absolute symbol relocations.
1263eaeb601bSDimitry Andric       continue;
12640b57cec5SDimitry Andric     assert(!SharedThis->GlobalSymbolTable.count(Name) &&
12650b57cec5SDimitry Andric            "Name already processed. RuntimeDyld instances can not be re-used "
12660b57cec5SDimitry Andric            "when finalizing with finalizeAsync.");
12670b57cec5SDimitry Andric     Symbols.insert(Name);
12680b57cec5SDimitry Andric   }
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   if (!Symbols.empty()) {
12718bcb0991SDimitry Andric     SharedThis->Resolver.lookup(Symbols, std::move(PostResolveContinuation));
12720b57cec5SDimitry Andric   } else
12730b57cec5SDimitry Andric     PostResolveContinuation(std::map<StringRef, JITEvaluatedSymbol>());
12740b57cec5SDimitry Andric }
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12770b57cec5SDimitry Andric // RuntimeDyld class implementation
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
12800b57cec5SDimitry Andric                                           const object::SectionRef &Sec) const {
12810b57cec5SDimitry Andric 
12820b57cec5SDimitry Andric   auto I = ObjSecToIDMap.find(Sec);
12830b57cec5SDimitry Andric   if (I != ObjSecToIDMap.end())
12840b57cec5SDimitry Andric     return RTDyld.Sections[I->second].getLoadAddress();
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric   return 0;
12870b57cec5SDimitry Andric }
12880b57cec5SDimitry Andric 
1289349cc55cSDimitry Andric RuntimeDyld::MemoryManager::TLSSection
1290349cc55cSDimitry Andric RuntimeDyld::MemoryManager::allocateTLSSection(uintptr_t Size,
1291349cc55cSDimitry Andric                                                unsigned Alignment,
1292349cc55cSDimitry Andric                                                unsigned SectionID,
1293349cc55cSDimitry Andric                                                StringRef SectionName) {
1294349cc55cSDimitry Andric   report_fatal_error("allocation of TLS not implemented");
1295349cc55cSDimitry Andric }
1296349cc55cSDimitry Andric 
12970b57cec5SDimitry Andric void RuntimeDyld::MemoryManager::anchor() {}
12980b57cec5SDimitry Andric void JITSymbolResolver::anchor() {}
12990b57cec5SDimitry Andric void LegacyJITSymbolResolver::anchor() {}
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
13020b57cec5SDimitry Andric                          JITSymbolResolver &Resolver)
13030b57cec5SDimitry Andric     : MemMgr(MemMgr), Resolver(Resolver) {
13040b57cec5SDimitry Andric   // FIXME: There's a potential issue lurking here if a single instance of
13050b57cec5SDimitry Andric   // RuntimeDyld is used to load multiple objects.  The current implementation
13060b57cec5SDimitry Andric   // associates a single memory manager with a RuntimeDyld instance.  Even
13070b57cec5SDimitry Andric   // though the public class spawns a new 'impl' instance for each load,
13080b57cec5SDimitry Andric   // they share a single memory manager.  This can become a problem when page
13090b57cec5SDimitry Andric   // permissions are applied.
13100b57cec5SDimitry Andric   Dyld = nullptr;
13110b57cec5SDimitry Andric   ProcessAllSections = false;
13120b57cec5SDimitry Andric }
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric RuntimeDyld::~RuntimeDyld() {}
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric static std::unique_ptr<RuntimeDyldCOFF>
13170b57cec5SDimitry Andric createRuntimeDyldCOFF(
13180b57cec5SDimitry Andric                      Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
13190b57cec5SDimitry Andric                      JITSymbolResolver &Resolver, bool ProcessAllSections,
13200b57cec5SDimitry Andric                      RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
13210b57cec5SDimitry Andric   std::unique_ptr<RuntimeDyldCOFF> Dyld =
13220b57cec5SDimitry Andric     RuntimeDyldCOFF::create(Arch, MM, Resolver);
13230b57cec5SDimitry Andric   Dyld->setProcessAllSections(ProcessAllSections);
13240b57cec5SDimitry Andric   Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
13250b57cec5SDimitry Andric   return Dyld;
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric static std::unique_ptr<RuntimeDyldELF>
13290b57cec5SDimitry Andric createRuntimeDyldELF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
13300b57cec5SDimitry Andric                      JITSymbolResolver &Resolver, bool ProcessAllSections,
13310b57cec5SDimitry Andric                      RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
13320b57cec5SDimitry Andric   std::unique_ptr<RuntimeDyldELF> Dyld =
13330b57cec5SDimitry Andric       RuntimeDyldELF::create(Arch, MM, Resolver);
13340b57cec5SDimitry Andric   Dyld->setProcessAllSections(ProcessAllSections);
13350b57cec5SDimitry Andric   Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
13360b57cec5SDimitry Andric   return Dyld;
13370b57cec5SDimitry Andric }
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric static std::unique_ptr<RuntimeDyldMachO>
13400b57cec5SDimitry Andric createRuntimeDyldMachO(
13410b57cec5SDimitry Andric                      Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
13420b57cec5SDimitry Andric                      JITSymbolResolver &Resolver,
13430b57cec5SDimitry Andric                      bool ProcessAllSections,
13440b57cec5SDimitry Andric                      RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
13450b57cec5SDimitry Andric   std::unique_ptr<RuntimeDyldMachO> Dyld =
13460b57cec5SDimitry Andric     RuntimeDyldMachO::create(Arch, MM, Resolver);
13470b57cec5SDimitry Andric   Dyld->setProcessAllSections(ProcessAllSections);
13480b57cec5SDimitry Andric   Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
13490b57cec5SDimitry Andric   return Dyld;
13500b57cec5SDimitry Andric }
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
13530b57cec5SDimitry Andric RuntimeDyld::loadObject(const ObjectFile &Obj) {
13540b57cec5SDimitry Andric   if (!Dyld) {
13550b57cec5SDimitry Andric     if (Obj.isELF())
13560b57cec5SDimitry Andric       Dyld =
13570b57cec5SDimitry Andric           createRuntimeDyldELF(static_cast<Triple::ArchType>(Obj.getArch()),
13580b57cec5SDimitry Andric                                MemMgr, Resolver, ProcessAllSections,
13590b57cec5SDimitry Andric                                std::move(NotifyStubEmitted));
13600b57cec5SDimitry Andric     else if (Obj.isMachO())
13610b57cec5SDimitry Andric       Dyld = createRuntimeDyldMachO(
13620b57cec5SDimitry Andric                static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
13630b57cec5SDimitry Andric                ProcessAllSections, std::move(NotifyStubEmitted));
13640b57cec5SDimitry Andric     else if (Obj.isCOFF())
13650b57cec5SDimitry Andric       Dyld = createRuntimeDyldCOFF(
13660b57cec5SDimitry Andric                static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
13670b57cec5SDimitry Andric                ProcessAllSections, std::move(NotifyStubEmitted));
13680b57cec5SDimitry Andric     else
13690b57cec5SDimitry Andric       report_fatal_error("Incompatible object format!");
13700b57cec5SDimitry Andric   }
13710b57cec5SDimitry Andric 
13720b57cec5SDimitry Andric   if (!Dyld->isCompatibleFile(Obj))
13730b57cec5SDimitry Andric     report_fatal_error("Incompatible object format!");
13740b57cec5SDimitry Andric 
13750b57cec5SDimitry Andric   auto LoadedObjInfo = Dyld->loadObject(Obj);
13760b57cec5SDimitry Andric   MemMgr.notifyObjectLoaded(*this, Obj);
13770b57cec5SDimitry Andric   return LoadedObjInfo;
13780b57cec5SDimitry Andric }
13790b57cec5SDimitry Andric 
13800b57cec5SDimitry Andric void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
13810b57cec5SDimitry Andric   if (!Dyld)
13820b57cec5SDimitry Andric     return nullptr;
13830b57cec5SDimitry Andric   return Dyld->getSymbolLocalAddress(Name);
13840b57cec5SDimitry Andric }
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric unsigned RuntimeDyld::getSymbolSectionID(StringRef Name) const {
13870b57cec5SDimitry Andric   assert(Dyld && "No RuntimeDyld instance attached");
13880b57cec5SDimitry Andric   return Dyld->getSymbolSectionID(Name);
13890b57cec5SDimitry Andric }
13900b57cec5SDimitry Andric 
13910b57cec5SDimitry Andric JITEvaluatedSymbol RuntimeDyld::getSymbol(StringRef Name) const {
13920b57cec5SDimitry Andric   if (!Dyld)
13930b57cec5SDimitry Andric     return nullptr;
13940b57cec5SDimitry Andric   return Dyld->getSymbol(Name);
13950b57cec5SDimitry Andric }
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric std::map<StringRef, JITEvaluatedSymbol> RuntimeDyld::getSymbolTable() const {
13980b57cec5SDimitry Andric   if (!Dyld)
13990b57cec5SDimitry Andric     return std::map<StringRef, JITEvaluatedSymbol>();
14000b57cec5SDimitry Andric   return Dyld->getSymbolTable();
14010b57cec5SDimitry Andric }
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
14060b57cec5SDimitry Andric   Dyld->reassignSectionAddress(SectionID, Addr);
14070b57cec5SDimitry Andric }
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
14100b57cec5SDimitry Andric                                     uint64_t TargetAddress) {
14110b57cec5SDimitry Andric   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
14120b57cec5SDimitry Andric }
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric bool RuntimeDyld::hasError() { return Dyld->hasError(); }
14150b57cec5SDimitry Andric 
14160b57cec5SDimitry Andric StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
14170b57cec5SDimitry Andric 
14180b57cec5SDimitry Andric void RuntimeDyld::finalizeWithMemoryManagerLocking() {
14190b57cec5SDimitry Andric   bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;
14200b57cec5SDimitry Andric   MemMgr.FinalizationLocked = true;
14210b57cec5SDimitry Andric   resolveRelocations();
14220b57cec5SDimitry Andric   registerEHFrames();
14230b57cec5SDimitry Andric   if (!MemoryFinalizationLocked) {
14240b57cec5SDimitry Andric     MemMgr.finalizeMemory();
14250b57cec5SDimitry Andric     MemMgr.FinalizationLocked = false;
14260b57cec5SDimitry Andric   }
14270b57cec5SDimitry Andric }
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric StringRef RuntimeDyld::getSectionContent(unsigned SectionID) const {
14300b57cec5SDimitry Andric   assert(Dyld && "No Dyld instance attached");
14310b57cec5SDimitry Andric   return Dyld->getSectionContent(SectionID);
14320b57cec5SDimitry Andric }
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric uint64_t RuntimeDyld::getSectionLoadAddress(unsigned SectionID) const {
14350b57cec5SDimitry Andric   assert(Dyld && "No Dyld instance attached");
14360b57cec5SDimitry Andric   return Dyld->getSectionLoadAddress(SectionID);
14370b57cec5SDimitry Andric }
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric void RuntimeDyld::registerEHFrames() {
14400b57cec5SDimitry Andric   if (Dyld)
14410b57cec5SDimitry Andric     Dyld->registerEHFrames();
14420b57cec5SDimitry Andric }
14430b57cec5SDimitry Andric 
14440b57cec5SDimitry Andric void RuntimeDyld::deregisterEHFrames() {
14450b57cec5SDimitry Andric   if (Dyld)
14460b57cec5SDimitry Andric     Dyld->deregisterEHFrames();
14470b57cec5SDimitry Andric }
14480b57cec5SDimitry Andric // FIXME: Kill this with fire once we have a new JIT linker: this is only here
14490b57cec5SDimitry Andric // so that we can re-use RuntimeDyld's implementation without twisting the
14500b57cec5SDimitry Andric // interface any further for ORC's purposes.
14515ffd83dbSDimitry Andric void jitLinkForORC(
14525ffd83dbSDimitry Andric     object::OwningBinary<object::ObjectFile> O,
14535ffd83dbSDimitry Andric     RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,
14545ffd83dbSDimitry Andric     bool ProcessAllSections,
1455e8d8bef9SDimitry Andric     unique_function<Error(const object::ObjectFile &Obj,
1456e8d8bef9SDimitry Andric                           RuntimeDyld::LoadedObjectInfo &LoadedObj,
14570b57cec5SDimitry Andric                           std::map<StringRef, JITEvaluatedSymbol>)>
14580b57cec5SDimitry Andric         OnLoaded,
1459e8d8bef9SDimitry Andric     unique_function<void(object::OwningBinary<object::ObjectFile>,
1460e8d8bef9SDimitry Andric                          std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
14615ffd83dbSDimitry Andric         OnEmitted) {
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   RuntimeDyld RTDyld(MemMgr, Resolver);
14640b57cec5SDimitry Andric   RTDyld.setProcessAllSections(ProcessAllSections);
14650b57cec5SDimitry Andric 
14665ffd83dbSDimitry Andric   auto Info = RTDyld.loadObject(*O.getBinary());
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric   if (RTDyld.hasError()) {
1469e8d8bef9SDimitry Andric     OnEmitted(std::move(O), std::move(Info),
1470e8d8bef9SDimitry Andric               make_error<StringError>(RTDyld.getErrorString(),
14710b57cec5SDimitry Andric                                       inconvertibleErrorCode()));
14720b57cec5SDimitry Andric     return;
14730b57cec5SDimitry Andric   }
14740b57cec5SDimitry Andric 
1475e8d8bef9SDimitry Andric   if (auto Err = OnLoaded(*O.getBinary(), *Info, RTDyld.getSymbolTable()))
1476e8d8bef9SDimitry Andric     OnEmitted(std::move(O), std::move(Info), std::move(Err));
14770b57cec5SDimitry Andric 
14780b57cec5SDimitry Andric   RuntimeDyldImpl::finalizeAsync(std::move(RTDyld.Dyld), std::move(OnEmitted),
1479e8d8bef9SDimitry Andric                                  std::move(O), std::move(Info));
14800b57cec5SDimitry Andric }
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric } // end namespace llvm
1483