xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // Implementation of the MC-JIT runtime dynamic linker.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "llvm/ExecutionEngine/RuntimeDyld.h"
14*0b57cec5SDimitry Andric #include "RuntimeDyldCOFF.h"
15*0b57cec5SDimitry Andric #include "RuntimeDyldELF.h"
16*0b57cec5SDimitry Andric #include "RuntimeDyldImpl.h"
17*0b57cec5SDimitry Andric #include "RuntimeDyldMachO.h"
18*0b57cec5SDimitry Andric #include "llvm/Object/COFF.h"
19*0b57cec5SDimitry Andric #include "llvm/Object/ELFObjectFile.h"
20*0b57cec5SDimitry Andric #include "llvm/Support/MSVCErrorWorkarounds.h"
21*0b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
22*0b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
23*0b57cec5SDimitry Andric #include "llvm/Support/MutexGuard.h"
24*0b57cec5SDimitry Andric 
25*0b57cec5SDimitry Andric #include <future>
26*0b57cec5SDimitry Andric 
27*0b57cec5SDimitry Andric using namespace llvm;
28*0b57cec5SDimitry Andric using namespace llvm::object;
29*0b57cec5SDimitry Andric 
30*0b57cec5SDimitry Andric #define DEBUG_TYPE "dyld"
31*0b57cec5SDimitry Andric 
32*0b57cec5SDimitry Andric namespace {
33*0b57cec5SDimitry Andric 
34*0b57cec5SDimitry Andric enum RuntimeDyldErrorCode {
35*0b57cec5SDimitry Andric   GenericRTDyldError = 1
36*0b57cec5SDimitry Andric };
37*0b57cec5SDimitry Andric 
38*0b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
39*0b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
40*0b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
41*0b57cec5SDimitry Andric class RuntimeDyldErrorCategory : public std::error_category {
42*0b57cec5SDimitry Andric public:
43*0b57cec5SDimitry Andric   const char *name() const noexcept override { return "runtimedyld"; }
44*0b57cec5SDimitry Andric 
45*0b57cec5SDimitry Andric   std::string message(int Condition) const override {
46*0b57cec5SDimitry Andric     switch (static_cast<RuntimeDyldErrorCode>(Condition)) {
47*0b57cec5SDimitry Andric       case GenericRTDyldError: return "Generic RuntimeDyld error";
48*0b57cec5SDimitry Andric     }
49*0b57cec5SDimitry Andric     llvm_unreachable("Unrecognized RuntimeDyldErrorCode");
50*0b57cec5SDimitry Andric   }
51*0b57cec5SDimitry Andric };
52*0b57cec5SDimitry Andric 
53*0b57cec5SDimitry Andric static ManagedStatic<RuntimeDyldErrorCategory> RTDyldErrorCategory;
54*0b57cec5SDimitry Andric 
55*0b57cec5SDimitry Andric }
56*0b57cec5SDimitry Andric 
57*0b57cec5SDimitry Andric char RuntimeDyldError::ID = 0;
58*0b57cec5SDimitry Andric 
59*0b57cec5SDimitry Andric void RuntimeDyldError::log(raw_ostream &OS) const {
60*0b57cec5SDimitry Andric   OS << ErrMsg << "\n";
61*0b57cec5SDimitry Andric }
62*0b57cec5SDimitry Andric 
63*0b57cec5SDimitry Andric std::error_code RuntimeDyldError::convertToErrorCode() const {
64*0b57cec5SDimitry Andric   return std::error_code(GenericRTDyldError, *RTDyldErrorCategory);
65*0b57cec5SDimitry Andric }
66*0b57cec5SDimitry Andric 
67*0b57cec5SDimitry Andric // Empty out-of-line virtual destructor as the key function.
68*0b57cec5SDimitry Andric RuntimeDyldImpl::~RuntimeDyldImpl() {}
69*0b57cec5SDimitry Andric 
70*0b57cec5SDimitry Andric // Pin LoadedObjectInfo's vtables to this file.
71*0b57cec5SDimitry Andric void RuntimeDyld::LoadedObjectInfo::anchor() {}
72*0b57cec5SDimitry Andric 
73*0b57cec5SDimitry Andric namespace llvm {
74*0b57cec5SDimitry Andric 
75*0b57cec5SDimitry Andric void RuntimeDyldImpl::registerEHFrames() {}
76*0b57cec5SDimitry Andric 
77*0b57cec5SDimitry Andric void RuntimeDyldImpl::deregisterEHFrames() {
78*0b57cec5SDimitry Andric   MemMgr.deregisterEHFrames();
79*0b57cec5SDimitry Andric }
80*0b57cec5SDimitry Andric 
81*0b57cec5SDimitry Andric #ifndef NDEBUG
82*0b57cec5SDimitry Andric static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
83*0b57cec5SDimitry Andric   dbgs() << "----- Contents of section " << S.getName() << " " << State
84*0b57cec5SDimitry Andric          << " -----";
85*0b57cec5SDimitry Andric 
86*0b57cec5SDimitry Andric   if (S.getAddress() == nullptr) {
87*0b57cec5SDimitry Andric     dbgs() << "\n          <section not emitted>\n";
88*0b57cec5SDimitry Andric     return;
89*0b57cec5SDimitry Andric   }
90*0b57cec5SDimitry Andric 
91*0b57cec5SDimitry Andric   const unsigned ColsPerRow = 16;
92*0b57cec5SDimitry Andric 
93*0b57cec5SDimitry Andric   uint8_t *DataAddr = S.getAddress();
94*0b57cec5SDimitry Andric   uint64_t LoadAddr = S.getLoadAddress();
95*0b57cec5SDimitry Andric 
96*0b57cec5SDimitry Andric   unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
97*0b57cec5SDimitry Andric   unsigned BytesRemaining = S.getSize();
98*0b57cec5SDimitry Andric 
99*0b57cec5SDimitry Andric   if (StartPadding) {
100*0b57cec5SDimitry Andric     dbgs() << "\n" << format("0x%016" PRIx64,
101*0b57cec5SDimitry Andric                              LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
102*0b57cec5SDimitry Andric     while (StartPadding--)
103*0b57cec5SDimitry Andric       dbgs() << "   ";
104*0b57cec5SDimitry Andric   }
105*0b57cec5SDimitry Andric 
106*0b57cec5SDimitry Andric   while (BytesRemaining > 0) {
107*0b57cec5SDimitry Andric     if ((LoadAddr & (ColsPerRow - 1)) == 0)
108*0b57cec5SDimitry Andric       dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
109*0b57cec5SDimitry Andric 
110*0b57cec5SDimitry Andric     dbgs() << " " << format("%02x", *DataAddr);
111*0b57cec5SDimitry Andric 
112*0b57cec5SDimitry Andric     ++DataAddr;
113*0b57cec5SDimitry Andric     ++LoadAddr;
114*0b57cec5SDimitry Andric     --BytesRemaining;
115*0b57cec5SDimitry Andric   }
116*0b57cec5SDimitry Andric 
117*0b57cec5SDimitry Andric   dbgs() << "\n";
118*0b57cec5SDimitry Andric }
119*0b57cec5SDimitry Andric #endif
120*0b57cec5SDimitry Andric 
121*0b57cec5SDimitry Andric // Resolve the relocations for all symbols we currently know about.
122*0b57cec5SDimitry Andric void RuntimeDyldImpl::resolveRelocations() {
123*0b57cec5SDimitry Andric   MutexGuard locked(lock);
124*0b57cec5SDimitry Andric 
125*0b57cec5SDimitry Andric   // Print out the sections prior to relocation.
126*0b57cec5SDimitry Andric   LLVM_DEBUG(for (int i = 0, e = Sections.size(); i != e; ++i)
127*0b57cec5SDimitry Andric                  dumpSectionMemory(Sections[i], "before relocations"););
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric   // First, resolve relocations associated with external symbols.
130*0b57cec5SDimitry Andric   if (auto Err = resolveExternalSymbols()) {
131*0b57cec5SDimitry Andric     HasError = true;
132*0b57cec5SDimitry Andric     ErrorStr = toString(std::move(Err));
133*0b57cec5SDimitry Andric   }
134*0b57cec5SDimitry Andric 
135*0b57cec5SDimitry Andric   resolveLocalRelocations();
136*0b57cec5SDimitry Andric 
137*0b57cec5SDimitry Andric   // Print out sections after relocation.
138*0b57cec5SDimitry Andric   LLVM_DEBUG(for (int i = 0, e = Sections.size(); i != e; ++i)
139*0b57cec5SDimitry Andric                  dumpSectionMemory(Sections[i], "after relocations"););
140*0b57cec5SDimitry Andric }
141*0b57cec5SDimitry Andric 
142*0b57cec5SDimitry Andric void RuntimeDyldImpl::resolveLocalRelocations() {
143*0b57cec5SDimitry Andric   // Iterate over all outstanding relocations
144*0b57cec5SDimitry Andric   for (auto it = Relocations.begin(), e = Relocations.end(); it != e; ++it) {
145*0b57cec5SDimitry Andric     // The Section here (Sections[i]) refers to the section in which the
146*0b57cec5SDimitry Andric     // symbol for the relocation is located.  The SectionID in the relocation
147*0b57cec5SDimitry Andric     // entry provides the section to which the relocation will be applied.
148*0b57cec5SDimitry Andric     int Idx = it->first;
149*0b57cec5SDimitry Andric     uint64_t Addr = Sections[Idx].getLoadAddress();
150*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"
151*0b57cec5SDimitry Andric                       << format("%p", (uintptr_t)Addr) << "\n");
152*0b57cec5SDimitry Andric     resolveRelocationList(it->second, Addr);
153*0b57cec5SDimitry Andric   }
154*0b57cec5SDimitry Andric   Relocations.clear();
155*0b57cec5SDimitry Andric }
156*0b57cec5SDimitry Andric 
157*0b57cec5SDimitry Andric void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
158*0b57cec5SDimitry Andric                                         uint64_t TargetAddress) {
159*0b57cec5SDimitry Andric   MutexGuard locked(lock);
160*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
161*0b57cec5SDimitry Andric     if (Sections[i].getAddress() == LocalAddress) {
162*0b57cec5SDimitry Andric       reassignSectionAddress(i, TargetAddress);
163*0b57cec5SDimitry Andric       return;
164*0b57cec5SDimitry Andric     }
165*0b57cec5SDimitry Andric   }
166*0b57cec5SDimitry Andric   llvm_unreachable("Attempting to remap address of unknown section!");
167*0b57cec5SDimitry Andric }
168*0b57cec5SDimitry Andric 
169*0b57cec5SDimitry Andric static Error getOffset(const SymbolRef &Sym, SectionRef Sec,
170*0b57cec5SDimitry Andric                        uint64_t &Result) {
171*0b57cec5SDimitry Andric   Expected<uint64_t> AddressOrErr = Sym.getAddress();
172*0b57cec5SDimitry Andric   if (!AddressOrErr)
173*0b57cec5SDimitry Andric     return AddressOrErr.takeError();
174*0b57cec5SDimitry Andric   Result = *AddressOrErr - Sec.getAddress();
175*0b57cec5SDimitry Andric   return Error::success();
176*0b57cec5SDimitry Andric }
177*0b57cec5SDimitry Andric 
178*0b57cec5SDimitry Andric Expected<RuntimeDyldImpl::ObjSectionToIDMap>
179*0b57cec5SDimitry Andric RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
180*0b57cec5SDimitry Andric   MutexGuard locked(lock);
181*0b57cec5SDimitry Andric 
182*0b57cec5SDimitry Andric   // Save information about our target
183*0b57cec5SDimitry Andric   Arch = (Triple::ArchType)Obj.getArch();
184*0b57cec5SDimitry Andric   IsTargetLittleEndian = Obj.isLittleEndian();
185*0b57cec5SDimitry Andric   setMipsABI(Obj);
186*0b57cec5SDimitry Andric 
187*0b57cec5SDimitry Andric   // Compute the memory size required to load all sections to be loaded
188*0b57cec5SDimitry Andric   // and pass this information to the memory manager
189*0b57cec5SDimitry Andric   if (MemMgr.needsToReserveAllocationSpace()) {
190*0b57cec5SDimitry Andric     uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;
191*0b57cec5SDimitry Andric     uint32_t CodeAlign = 1, RODataAlign = 1, RWDataAlign = 1;
192*0b57cec5SDimitry Andric     if (auto Err = computeTotalAllocSize(Obj,
193*0b57cec5SDimitry Andric                                          CodeSize, CodeAlign,
194*0b57cec5SDimitry Andric                                          RODataSize, RODataAlign,
195*0b57cec5SDimitry Andric                                          RWDataSize, RWDataAlign))
196*0b57cec5SDimitry Andric       return std::move(Err);
197*0b57cec5SDimitry Andric     MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,
198*0b57cec5SDimitry Andric                                   RWDataSize, RWDataAlign);
199*0b57cec5SDimitry Andric   }
200*0b57cec5SDimitry Andric 
201*0b57cec5SDimitry Andric   // Used sections from the object file
202*0b57cec5SDimitry Andric   ObjSectionToIDMap LocalSections;
203*0b57cec5SDimitry Andric 
204*0b57cec5SDimitry Andric   // Common symbols requiring allocation, with their sizes and alignments
205*0b57cec5SDimitry Andric   CommonSymbolList CommonSymbolsToAllocate;
206*0b57cec5SDimitry Andric 
207*0b57cec5SDimitry Andric   uint64_t CommonSize = 0;
208*0b57cec5SDimitry Andric   uint32_t CommonAlign = 0;
209*0b57cec5SDimitry Andric 
210*0b57cec5SDimitry Andric   // First, collect all weak and common symbols. We need to know if stronger
211*0b57cec5SDimitry Andric   // definitions occur elsewhere.
212*0b57cec5SDimitry Andric   JITSymbolResolver::LookupSet ResponsibilitySet;
213*0b57cec5SDimitry Andric   {
214*0b57cec5SDimitry Andric     JITSymbolResolver::LookupSet Symbols;
215*0b57cec5SDimitry Andric     for (auto &Sym : Obj.symbols()) {
216*0b57cec5SDimitry Andric       uint32_t Flags = Sym.getFlags();
217*0b57cec5SDimitry Andric       if ((Flags & SymbolRef::SF_Common) || (Flags & SymbolRef::SF_Weak)) {
218*0b57cec5SDimitry Andric         // Get symbol name.
219*0b57cec5SDimitry Andric         if (auto NameOrErr = Sym.getName())
220*0b57cec5SDimitry Andric           Symbols.insert(*NameOrErr);
221*0b57cec5SDimitry Andric         else
222*0b57cec5SDimitry Andric           return NameOrErr.takeError();
223*0b57cec5SDimitry Andric       }
224*0b57cec5SDimitry Andric     }
225*0b57cec5SDimitry Andric 
226*0b57cec5SDimitry Andric     if (auto ResultOrErr = Resolver.getResponsibilitySet(Symbols))
227*0b57cec5SDimitry Andric       ResponsibilitySet = std::move(*ResultOrErr);
228*0b57cec5SDimitry Andric     else
229*0b57cec5SDimitry Andric       return ResultOrErr.takeError();
230*0b57cec5SDimitry Andric   }
231*0b57cec5SDimitry Andric 
232*0b57cec5SDimitry Andric   // Parse symbols
233*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Parse symbols:\n");
234*0b57cec5SDimitry Andric   for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
235*0b57cec5SDimitry Andric        ++I) {
236*0b57cec5SDimitry Andric     uint32_t Flags = I->getFlags();
237*0b57cec5SDimitry Andric 
238*0b57cec5SDimitry Andric     // Skip undefined symbols.
239*0b57cec5SDimitry Andric     if (Flags & SymbolRef::SF_Undefined)
240*0b57cec5SDimitry Andric       continue;
241*0b57cec5SDimitry Andric 
242*0b57cec5SDimitry Andric     // Get the symbol type.
243*0b57cec5SDimitry Andric     object::SymbolRef::Type SymType;
244*0b57cec5SDimitry Andric     if (auto SymTypeOrErr = I->getType())
245*0b57cec5SDimitry Andric       SymType = *SymTypeOrErr;
246*0b57cec5SDimitry Andric     else
247*0b57cec5SDimitry Andric       return SymTypeOrErr.takeError();
248*0b57cec5SDimitry Andric 
249*0b57cec5SDimitry Andric     // Get symbol name.
250*0b57cec5SDimitry Andric     StringRef Name;
251*0b57cec5SDimitry Andric     if (auto NameOrErr = I->getName())
252*0b57cec5SDimitry Andric       Name = *NameOrErr;
253*0b57cec5SDimitry Andric     else
254*0b57cec5SDimitry Andric       return NameOrErr.takeError();
255*0b57cec5SDimitry Andric 
256*0b57cec5SDimitry Andric     // Compute JIT symbol flags.
257*0b57cec5SDimitry Andric     auto JITSymFlags = getJITSymbolFlags(*I);
258*0b57cec5SDimitry Andric     if (!JITSymFlags)
259*0b57cec5SDimitry Andric       return JITSymFlags.takeError();
260*0b57cec5SDimitry Andric 
261*0b57cec5SDimitry Andric     // If this is a weak definition, check to see if there's a strong one.
262*0b57cec5SDimitry Andric     // If there is, skip this symbol (we won't be providing it: the strong
263*0b57cec5SDimitry Andric     // definition will). If there's no strong definition, make this definition
264*0b57cec5SDimitry Andric     // strong.
265*0b57cec5SDimitry Andric     if (JITSymFlags->isWeak() || JITSymFlags->isCommon()) {
266*0b57cec5SDimitry Andric       // First check whether there's already a definition in this instance.
267*0b57cec5SDimitry Andric       if (GlobalSymbolTable.count(Name))
268*0b57cec5SDimitry Andric         continue;
269*0b57cec5SDimitry Andric 
270*0b57cec5SDimitry Andric       // If we're not responsible for this symbol, skip it.
271*0b57cec5SDimitry Andric       if (!ResponsibilitySet.count(Name))
272*0b57cec5SDimitry Andric         continue;
273*0b57cec5SDimitry Andric 
274*0b57cec5SDimitry Andric       // Otherwise update the flags on the symbol to make this definition
275*0b57cec5SDimitry Andric       // strong.
276*0b57cec5SDimitry Andric       if (JITSymFlags->isWeak())
277*0b57cec5SDimitry Andric         *JITSymFlags &= ~JITSymbolFlags::Weak;
278*0b57cec5SDimitry Andric       if (JITSymFlags->isCommon()) {
279*0b57cec5SDimitry Andric         *JITSymFlags &= ~JITSymbolFlags::Common;
280*0b57cec5SDimitry Andric         uint32_t Align = I->getAlignment();
281*0b57cec5SDimitry Andric         uint64_t Size = I->getCommonSize();
282*0b57cec5SDimitry Andric         if (!CommonAlign)
283*0b57cec5SDimitry Andric           CommonAlign = Align;
284*0b57cec5SDimitry Andric         CommonSize = alignTo(CommonSize, Align) + Size;
285*0b57cec5SDimitry Andric         CommonSymbolsToAllocate.push_back(*I);
286*0b57cec5SDimitry Andric       }
287*0b57cec5SDimitry Andric     }
288*0b57cec5SDimitry Andric 
289*0b57cec5SDimitry Andric     if (Flags & SymbolRef::SF_Absolute &&
290*0b57cec5SDimitry Andric         SymType != object::SymbolRef::ST_File) {
291*0b57cec5SDimitry Andric       uint64_t Addr = 0;
292*0b57cec5SDimitry Andric       if (auto AddrOrErr = I->getAddress())
293*0b57cec5SDimitry Andric         Addr = *AddrOrErr;
294*0b57cec5SDimitry Andric       else
295*0b57cec5SDimitry Andric         return AddrOrErr.takeError();
296*0b57cec5SDimitry Andric 
297*0b57cec5SDimitry Andric       unsigned SectionID = AbsoluteSymbolSection;
298*0b57cec5SDimitry Andric 
299*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name
300*0b57cec5SDimitry Andric                         << " SID: " << SectionID
301*0b57cec5SDimitry Andric                         << " Offset: " << format("%p", (uintptr_t)Addr)
302*0b57cec5SDimitry Andric                         << " flags: " << Flags << "\n");
303*0b57cec5SDimitry Andric       GlobalSymbolTable[Name] = SymbolTableEntry(SectionID, Addr, *JITSymFlags);
304*0b57cec5SDimitry Andric     } else if (SymType == object::SymbolRef::ST_Function ||
305*0b57cec5SDimitry Andric                SymType == object::SymbolRef::ST_Data ||
306*0b57cec5SDimitry Andric                SymType == object::SymbolRef::ST_Unknown ||
307*0b57cec5SDimitry Andric                SymType == object::SymbolRef::ST_Other) {
308*0b57cec5SDimitry Andric 
309*0b57cec5SDimitry Andric       section_iterator SI = Obj.section_end();
310*0b57cec5SDimitry Andric       if (auto SIOrErr = I->getSection())
311*0b57cec5SDimitry Andric         SI = *SIOrErr;
312*0b57cec5SDimitry Andric       else
313*0b57cec5SDimitry Andric         return SIOrErr.takeError();
314*0b57cec5SDimitry Andric 
315*0b57cec5SDimitry Andric       if (SI == Obj.section_end())
316*0b57cec5SDimitry Andric         continue;
317*0b57cec5SDimitry Andric 
318*0b57cec5SDimitry Andric       // Get symbol offset.
319*0b57cec5SDimitry Andric       uint64_t SectOffset;
320*0b57cec5SDimitry Andric       if (auto Err = getOffset(*I, *SI, SectOffset))
321*0b57cec5SDimitry Andric         return std::move(Err);
322*0b57cec5SDimitry Andric 
323*0b57cec5SDimitry Andric       bool IsCode = SI->isText();
324*0b57cec5SDimitry Andric       unsigned SectionID;
325*0b57cec5SDimitry Andric       if (auto SectionIDOrErr =
326*0b57cec5SDimitry Andric               findOrEmitSection(Obj, *SI, IsCode, LocalSections))
327*0b57cec5SDimitry Andric         SectionID = *SectionIDOrErr;
328*0b57cec5SDimitry Andric       else
329*0b57cec5SDimitry Andric         return SectionIDOrErr.takeError();
330*0b57cec5SDimitry Andric 
331*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
332*0b57cec5SDimitry Andric                         << " SID: " << SectionID
333*0b57cec5SDimitry Andric                         << " Offset: " << format("%p", (uintptr_t)SectOffset)
334*0b57cec5SDimitry Andric                         << " flags: " << Flags << "\n");
335*0b57cec5SDimitry Andric       GlobalSymbolTable[Name] =
336*0b57cec5SDimitry Andric           SymbolTableEntry(SectionID, SectOffset, *JITSymFlags);
337*0b57cec5SDimitry Andric     }
338*0b57cec5SDimitry Andric   }
339*0b57cec5SDimitry Andric 
340*0b57cec5SDimitry Andric   // Allocate common symbols
341*0b57cec5SDimitry Andric   if (auto Err = emitCommonSymbols(Obj, CommonSymbolsToAllocate, CommonSize,
342*0b57cec5SDimitry Andric                                    CommonAlign))
343*0b57cec5SDimitry Andric     return std::move(Err);
344*0b57cec5SDimitry Andric 
345*0b57cec5SDimitry Andric   // Parse and process relocations
346*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Parse relocations:\n");
347*0b57cec5SDimitry Andric   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
348*0b57cec5SDimitry Andric        SI != SE; ++SI) {
349*0b57cec5SDimitry Andric     StubMap Stubs;
350*0b57cec5SDimitry Andric     section_iterator RelocatedSection = SI->getRelocatedSection();
351*0b57cec5SDimitry Andric 
352*0b57cec5SDimitry Andric     if (RelocatedSection == SE)
353*0b57cec5SDimitry Andric       continue;
354*0b57cec5SDimitry Andric 
355*0b57cec5SDimitry Andric     relocation_iterator I = SI->relocation_begin();
356*0b57cec5SDimitry Andric     relocation_iterator E = SI->relocation_end();
357*0b57cec5SDimitry Andric 
358*0b57cec5SDimitry Andric     if (I == E && !ProcessAllSections)
359*0b57cec5SDimitry Andric       continue;
360*0b57cec5SDimitry Andric 
361*0b57cec5SDimitry Andric     bool IsCode = RelocatedSection->isText();
362*0b57cec5SDimitry Andric     unsigned SectionID = 0;
363*0b57cec5SDimitry Andric     if (auto SectionIDOrErr = findOrEmitSection(Obj, *RelocatedSection, IsCode,
364*0b57cec5SDimitry Andric                                                 LocalSections))
365*0b57cec5SDimitry Andric       SectionID = *SectionIDOrErr;
366*0b57cec5SDimitry Andric     else
367*0b57cec5SDimitry Andric       return SectionIDOrErr.takeError();
368*0b57cec5SDimitry Andric 
369*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
370*0b57cec5SDimitry Andric 
371*0b57cec5SDimitry Andric     for (; I != E;)
372*0b57cec5SDimitry Andric       if (auto IOrErr = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs))
373*0b57cec5SDimitry Andric         I = *IOrErr;
374*0b57cec5SDimitry Andric       else
375*0b57cec5SDimitry Andric         return IOrErr.takeError();
376*0b57cec5SDimitry Andric 
377*0b57cec5SDimitry Andric     // If there is a NotifyStubEmitted callback set, call it to register any
378*0b57cec5SDimitry Andric     // stubs created for this section.
379*0b57cec5SDimitry Andric     if (NotifyStubEmitted) {
380*0b57cec5SDimitry Andric       StringRef FileName = Obj.getFileName();
381*0b57cec5SDimitry Andric       StringRef SectionName = Sections[SectionID].getName();
382*0b57cec5SDimitry Andric       for (auto &KV : Stubs) {
383*0b57cec5SDimitry Andric 
384*0b57cec5SDimitry Andric         auto &VR = KV.first;
385*0b57cec5SDimitry Andric         uint64_t StubAddr = KV.second;
386*0b57cec5SDimitry Andric 
387*0b57cec5SDimitry Andric         // If this is a named stub, just call NotifyStubEmitted.
388*0b57cec5SDimitry Andric         if (VR.SymbolName) {
389*0b57cec5SDimitry Andric           NotifyStubEmitted(FileName, SectionName, VR.SymbolName, SectionID,
390*0b57cec5SDimitry Andric                             StubAddr);
391*0b57cec5SDimitry Andric           continue;
392*0b57cec5SDimitry Andric         }
393*0b57cec5SDimitry Andric 
394*0b57cec5SDimitry Andric         // Otherwise we will have to try a reverse lookup on the globla symbol table.
395*0b57cec5SDimitry Andric         for (auto &GSTMapEntry : GlobalSymbolTable) {
396*0b57cec5SDimitry Andric           StringRef SymbolName = GSTMapEntry.first();
397*0b57cec5SDimitry Andric           auto &GSTEntry = GSTMapEntry.second;
398*0b57cec5SDimitry Andric           if (GSTEntry.getSectionID() == VR.SectionID &&
399*0b57cec5SDimitry Andric               GSTEntry.getOffset() == VR.Offset) {
400*0b57cec5SDimitry Andric             NotifyStubEmitted(FileName, SectionName, SymbolName, SectionID,
401*0b57cec5SDimitry Andric                               StubAddr);
402*0b57cec5SDimitry Andric             break;
403*0b57cec5SDimitry Andric           }
404*0b57cec5SDimitry Andric         }
405*0b57cec5SDimitry Andric       }
406*0b57cec5SDimitry Andric     }
407*0b57cec5SDimitry Andric   }
408*0b57cec5SDimitry Andric 
409*0b57cec5SDimitry Andric   // Process remaining sections
410*0b57cec5SDimitry Andric   if (ProcessAllSections) {
411*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Process remaining sections:\n");
412*0b57cec5SDimitry Andric     for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
413*0b57cec5SDimitry Andric          SI != SE; ++SI) {
414*0b57cec5SDimitry Andric 
415*0b57cec5SDimitry Andric       /* Ignore already loaded sections */
416*0b57cec5SDimitry Andric       if (LocalSections.find(*SI) != LocalSections.end())
417*0b57cec5SDimitry Andric         continue;
418*0b57cec5SDimitry Andric 
419*0b57cec5SDimitry Andric       bool IsCode = SI->isText();
420*0b57cec5SDimitry Andric       if (auto SectionIDOrErr =
421*0b57cec5SDimitry Andric               findOrEmitSection(Obj, *SI, IsCode, LocalSections))
422*0b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "\tSectionID: " << (*SectionIDOrErr) << "\n");
423*0b57cec5SDimitry Andric       else
424*0b57cec5SDimitry Andric         return SectionIDOrErr.takeError();
425*0b57cec5SDimitry Andric     }
426*0b57cec5SDimitry Andric   }
427*0b57cec5SDimitry Andric 
428*0b57cec5SDimitry Andric   // Give the subclasses a chance to tie-up any loose ends.
429*0b57cec5SDimitry Andric   if (auto Err = finalizeLoad(Obj, LocalSections))
430*0b57cec5SDimitry Andric     return std::move(Err);
431*0b57cec5SDimitry Andric 
432*0b57cec5SDimitry Andric //   for (auto E : LocalSections)
433*0b57cec5SDimitry Andric //     llvm::dbgs() << "Added: " << E.first.getRawDataRefImpl() << " -> " << E.second << "\n";
434*0b57cec5SDimitry Andric 
435*0b57cec5SDimitry Andric   return LocalSections;
436*0b57cec5SDimitry Andric }
437*0b57cec5SDimitry Andric 
438*0b57cec5SDimitry Andric // A helper method for computeTotalAllocSize.
439*0b57cec5SDimitry Andric // Computes the memory size required to allocate sections with the given sizes,
440*0b57cec5SDimitry Andric // assuming that all sections are allocated with the given alignment
441*0b57cec5SDimitry Andric static uint64_t
442*0b57cec5SDimitry Andric computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
443*0b57cec5SDimitry Andric                                  uint64_t Alignment) {
444*0b57cec5SDimitry Andric   uint64_t TotalSize = 0;
445*0b57cec5SDimitry Andric   for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
446*0b57cec5SDimitry Andric     uint64_t AlignedSize =
447*0b57cec5SDimitry Andric         (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
448*0b57cec5SDimitry Andric     TotalSize += AlignedSize;
449*0b57cec5SDimitry Andric   }
450*0b57cec5SDimitry Andric   return TotalSize;
451*0b57cec5SDimitry Andric }
452*0b57cec5SDimitry Andric 
453*0b57cec5SDimitry Andric static bool isRequiredForExecution(const SectionRef Section) {
454*0b57cec5SDimitry Andric   const ObjectFile *Obj = Section.getObject();
455*0b57cec5SDimitry Andric   if (isa<object::ELFObjectFileBase>(Obj))
456*0b57cec5SDimitry Andric     return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
457*0b57cec5SDimitry Andric   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
458*0b57cec5SDimitry Andric     const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
459*0b57cec5SDimitry Andric     // Avoid loading zero-sized COFF sections.
460*0b57cec5SDimitry Andric     // In PE files, VirtualSize gives the section size, and SizeOfRawData
461*0b57cec5SDimitry Andric     // may be zero for sections with content. In Obj files, SizeOfRawData
462*0b57cec5SDimitry Andric     // gives the section size, and VirtualSize is always zero. Hence
463*0b57cec5SDimitry Andric     // the need to check for both cases below.
464*0b57cec5SDimitry Andric     bool HasContent =
465*0b57cec5SDimitry Andric         (CoffSection->VirtualSize > 0) || (CoffSection->SizeOfRawData > 0);
466*0b57cec5SDimitry Andric     bool IsDiscardable =
467*0b57cec5SDimitry Andric         CoffSection->Characteristics &
468*0b57cec5SDimitry Andric         (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
469*0b57cec5SDimitry Andric     return HasContent && !IsDiscardable;
470*0b57cec5SDimitry Andric   }
471*0b57cec5SDimitry Andric 
472*0b57cec5SDimitry Andric   assert(isa<MachOObjectFile>(Obj));
473*0b57cec5SDimitry Andric   return true;
474*0b57cec5SDimitry Andric }
475*0b57cec5SDimitry Andric 
476*0b57cec5SDimitry Andric static bool isReadOnlyData(const SectionRef Section) {
477*0b57cec5SDimitry Andric   const ObjectFile *Obj = Section.getObject();
478*0b57cec5SDimitry Andric   if (isa<object::ELFObjectFileBase>(Obj))
479*0b57cec5SDimitry Andric     return !(ELFSectionRef(Section).getFlags() &
480*0b57cec5SDimitry Andric              (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
481*0b57cec5SDimitry Andric   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
482*0b57cec5SDimitry Andric     return ((COFFObj->getCOFFSection(Section)->Characteristics &
483*0b57cec5SDimitry Andric              (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
484*0b57cec5SDimitry Andric              | COFF::IMAGE_SCN_MEM_READ
485*0b57cec5SDimitry Andric              | COFF::IMAGE_SCN_MEM_WRITE))
486*0b57cec5SDimitry Andric              ==
487*0b57cec5SDimitry Andric              (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
488*0b57cec5SDimitry Andric              | COFF::IMAGE_SCN_MEM_READ));
489*0b57cec5SDimitry Andric 
490*0b57cec5SDimitry Andric   assert(isa<MachOObjectFile>(Obj));
491*0b57cec5SDimitry Andric   return false;
492*0b57cec5SDimitry Andric }
493*0b57cec5SDimitry Andric 
494*0b57cec5SDimitry Andric static bool isZeroInit(const SectionRef Section) {
495*0b57cec5SDimitry Andric   const ObjectFile *Obj = Section.getObject();
496*0b57cec5SDimitry Andric   if (isa<object::ELFObjectFileBase>(Obj))
497*0b57cec5SDimitry Andric     return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
498*0b57cec5SDimitry Andric   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
499*0b57cec5SDimitry Andric     return COFFObj->getCOFFSection(Section)->Characteristics &
500*0b57cec5SDimitry Andric             COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
501*0b57cec5SDimitry Andric 
502*0b57cec5SDimitry Andric   auto *MachO = cast<MachOObjectFile>(Obj);
503*0b57cec5SDimitry Andric   unsigned SectionType = MachO->getSectionType(Section);
504*0b57cec5SDimitry Andric   return SectionType == MachO::S_ZEROFILL ||
505*0b57cec5SDimitry Andric          SectionType == MachO::S_GB_ZEROFILL;
506*0b57cec5SDimitry Andric }
507*0b57cec5SDimitry Andric 
508*0b57cec5SDimitry Andric // Compute an upper bound of the memory size that is required to load all
509*0b57cec5SDimitry Andric // sections
510*0b57cec5SDimitry Andric Error RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
511*0b57cec5SDimitry Andric                                              uint64_t &CodeSize,
512*0b57cec5SDimitry Andric                                              uint32_t &CodeAlign,
513*0b57cec5SDimitry Andric                                              uint64_t &RODataSize,
514*0b57cec5SDimitry Andric                                              uint32_t &RODataAlign,
515*0b57cec5SDimitry Andric                                              uint64_t &RWDataSize,
516*0b57cec5SDimitry Andric                                              uint32_t &RWDataAlign) {
517*0b57cec5SDimitry Andric   // Compute the size of all sections required for execution
518*0b57cec5SDimitry Andric   std::vector<uint64_t> CodeSectionSizes;
519*0b57cec5SDimitry Andric   std::vector<uint64_t> ROSectionSizes;
520*0b57cec5SDimitry Andric   std::vector<uint64_t> RWSectionSizes;
521*0b57cec5SDimitry Andric 
522*0b57cec5SDimitry Andric   // Collect sizes of all sections to be loaded;
523*0b57cec5SDimitry Andric   // also determine the max alignment of all sections
524*0b57cec5SDimitry Andric   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
525*0b57cec5SDimitry Andric        SI != SE; ++SI) {
526*0b57cec5SDimitry Andric     const SectionRef &Section = *SI;
527*0b57cec5SDimitry Andric 
528*0b57cec5SDimitry Andric     bool IsRequired = isRequiredForExecution(Section) || ProcessAllSections;
529*0b57cec5SDimitry Andric 
530*0b57cec5SDimitry Andric     // Consider only the sections that are required to be loaded for execution
531*0b57cec5SDimitry Andric     if (IsRequired) {
532*0b57cec5SDimitry Andric       uint64_t DataSize = Section.getSize();
533*0b57cec5SDimitry Andric       uint64_t Alignment64 = Section.getAlignment();
534*0b57cec5SDimitry Andric       unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
535*0b57cec5SDimitry Andric       bool IsCode = Section.isText();
536*0b57cec5SDimitry Andric       bool IsReadOnly = isReadOnlyData(Section);
537*0b57cec5SDimitry Andric 
538*0b57cec5SDimitry Andric       StringRef Name;
539*0b57cec5SDimitry Andric       if (auto EC = Section.getName(Name))
540*0b57cec5SDimitry Andric         return errorCodeToError(EC);
541*0b57cec5SDimitry Andric 
542*0b57cec5SDimitry Andric       uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
543*0b57cec5SDimitry Andric 
544*0b57cec5SDimitry Andric       uint64_t PaddingSize = 0;
545*0b57cec5SDimitry Andric       if (Name == ".eh_frame")
546*0b57cec5SDimitry Andric         PaddingSize += 4;
547*0b57cec5SDimitry Andric       if (StubBufSize != 0)
548*0b57cec5SDimitry Andric         PaddingSize += getStubAlignment() - 1;
549*0b57cec5SDimitry Andric 
550*0b57cec5SDimitry Andric       uint64_t SectionSize = DataSize + PaddingSize + StubBufSize;
551*0b57cec5SDimitry Andric 
552*0b57cec5SDimitry Andric       // The .eh_frame section (at least on Linux) needs an extra four bytes
553*0b57cec5SDimitry Andric       // padded
554*0b57cec5SDimitry Andric       // with zeroes added at the end.  For MachO objects, this section has a
555*0b57cec5SDimitry Andric       // slightly different name, so this won't have any effect for MachO
556*0b57cec5SDimitry Andric       // objects.
557*0b57cec5SDimitry Andric       if (Name == ".eh_frame")
558*0b57cec5SDimitry Andric         SectionSize += 4;
559*0b57cec5SDimitry Andric 
560*0b57cec5SDimitry Andric       if (!SectionSize)
561*0b57cec5SDimitry Andric         SectionSize = 1;
562*0b57cec5SDimitry Andric 
563*0b57cec5SDimitry Andric       if (IsCode) {
564*0b57cec5SDimitry Andric         CodeAlign = std::max(CodeAlign, Alignment);
565*0b57cec5SDimitry Andric         CodeSectionSizes.push_back(SectionSize);
566*0b57cec5SDimitry Andric       } else if (IsReadOnly) {
567*0b57cec5SDimitry Andric         RODataAlign = std::max(RODataAlign, Alignment);
568*0b57cec5SDimitry Andric         ROSectionSizes.push_back(SectionSize);
569*0b57cec5SDimitry Andric       } else {
570*0b57cec5SDimitry Andric         RWDataAlign = std::max(RWDataAlign, Alignment);
571*0b57cec5SDimitry Andric         RWSectionSizes.push_back(SectionSize);
572*0b57cec5SDimitry Andric       }
573*0b57cec5SDimitry Andric     }
574*0b57cec5SDimitry Andric   }
575*0b57cec5SDimitry Andric 
576*0b57cec5SDimitry Andric   // Compute Global Offset Table size. If it is not zero we
577*0b57cec5SDimitry Andric   // also update alignment, which is equal to a size of a
578*0b57cec5SDimitry Andric   // single GOT entry.
579*0b57cec5SDimitry Andric   if (unsigned GotSize = computeGOTSize(Obj)) {
580*0b57cec5SDimitry Andric     RWSectionSizes.push_back(GotSize);
581*0b57cec5SDimitry Andric     RWDataAlign = std::max<uint32_t>(RWDataAlign, getGOTEntrySize());
582*0b57cec5SDimitry Andric   }
583*0b57cec5SDimitry Andric 
584*0b57cec5SDimitry Andric   // Compute the size of all common symbols
585*0b57cec5SDimitry Andric   uint64_t CommonSize = 0;
586*0b57cec5SDimitry Andric   uint32_t CommonAlign = 1;
587*0b57cec5SDimitry Andric   for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
588*0b57cec5SDimitry Andric        ++I) {
589*0b57cec5SDimitry Andric     uint32_t Flags = I->getFlags();
590*0b57cec5SDimitry Andric     if (Flags & SymbolRef::SF_Common) {
591*0b57cec5SDimitry Andric       // Add the common symbols to a list.  We'll allocate them all below.
592*0b57cec5SDimitry Andric       uint64_t Size = I->getCommonSize();
593*0b57cec5SDimitry Andric       uint32_t Align = I->getAlignment();
594*0b57cec5SDimitry Andric       // If this is the first common symbol, use its alignment as the alignment
595*0b57cec5SDimitry Andric       // for the common symbols section.
596*0b57cec5SDimitry Andric       if (CommonSize == 0)
597*0b57cec5SDimitry Andric         CommonAlign = Align;
598*0b57cec5SDimitry Andric       CommonSize = alignTo(CommonSize, Align) + Size;
599*0b57cec5SDimitry Andric     }
600*0b57cec5SDimitry Andric   }
601*0b57cec5SDimitry Andric   if (CommonSize != 0) {
602*0b57cec5SDimitry Andric     RWSectionSizes.push_back(CommonSize);
603*0b57cec5SDimitry Andric     RWDataAlign = std::max(RWDataAlign, CommonAlign);
604*0b57cec5SDimitry Andric   }
605*0b57cec5SDimitry Andric 
606*0b57cec5SDimitry Andric   // Compute the required allocation space for each different type of sections
607*0b57cec5SDimitry Andric   // (code, read-only data, read-write data) assuming that all sections are
608*0b57cec5SDimitry Andric   // allocated with the max alignment. Note that we cannot compute with the
609*0b57cec5SDimitry Andric   // individual alignments of the sections, because then the required size
610*0b57cec5SDimitry Andric   // depends on the order, in which the sections are allocated.
611*0b57cec5SDimitry Andric   CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);
612*0b57cec5SDimitry Andric   RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);
613*0b57cec5SDimitry Andric   RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);
614*0b57cec5SDimitry Andric 
615*0b57cec5SDimitry Andric   return Error::success();
616*0b57cec5SDimitry Andric }
617*0b57cec5SDimitry Andric 
618*0b57cec5SDimitry Andric // compute GOT size
619*0b57cec5SDimitry Andric unsigned RuntimeDyldImpl::computeGOTSize(const ObjectFile &Obj) {
620*0b57cec5SDimitry Andric   size_t GotEntrySize = getGOTEntrySize();
621*0b57cec5SDimitry Andric   if (!GotEntrySize)
622*0b57cec5SDimitry Andric     return 0;
623*0b57cec5SDimitry Andric 
624*0b57cec5SDimitry Andric   size_t GotSize = 0;
625*0b57cec5SDimitry Andric   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
626*0b57cec5SDimitry Andric        SI != SE; ++SI) {
627*0b57cec5SDimitry Andric 
628*0b57cec5SDimitry Andric     for (const RelocationRef &Reloc : SI->relocations())
629*0b57cec5SDimitry Andric       if (relocationNeedsGot(Reloc))
630*0b57cec5SDimitry Andric         GotSize += GotEntrySize;
631*0b57cec5SDimitry Andric   }
632*0b57cec5SDimitry Andric 
633*0b57cec5SDimitry Andric   return GotSize;
634*0b57cec5SDimitry Andric }
635*0b57cec5SDimitry Andric 
636*0b57cec5SDimitry Andric // compute stub buffer size for the given section
637*0b57cec5SDimitry Andric unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
638*0b57cec5SDimitry Andric                                                     const SectionRef &Section) {
639*0b57cec5SDimitry Andric   unsigned StubSize = getMaxStubSize();
640*0b57cec5SDimitry Andric   if (StubSize == 0) {
641*0b57cec5SDimitry Andric     return 0;
642*0b57cec5SDimitry Andric   }
643*0b57cec5SDimitry Andric   // FIXME: this is an inefficient way to handle this. We should computed the
644*0b57cec5SDimitry Andric   // necessary section allocation size in loadObject by walking all the sections
645*0b57cec5SDimitry Andric   // once.
646*0b57cec5SDimitry Andric   unsigned StubBufSize = 0;
647*0b57cec5SDimitry Andric   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
648*0b57cec5SDimitry Andric        SI != SE; ++SI) {
649*0b57cec5SDimitry Andric     section_iterator RelSecI = SI->getRelocatedSection();
650*0b57cec5SDimitry Andric     if (!(RelSecI == Section))
651*0b57cec5SDimitry Andric       continue;
652*0b57cec5SDimitry Andric 
653*0b57cec5SDimitry Andric     for (const RelocationRef &Reloc : SI->relocations())
654*0b57cec5SDimitry Andric       if (relocationNeedsStub(Reloc))
655*0b57cec5SDimitry Andric         StubBufSize += StubSize;
656*0b57cec5SDimitry Andric   }
657*0b57cec5SDimitry Andric 
658*0b57cec5SDimitry Andric   // Get section data size and alignment
659*0b57cec5SDimitry Andric   uint64_t DataSize = Section.getSize();
660*0b57cec5SDimitry Andric   uint64_t Alignment64 = Section.getAlignment();
661*0b57cec5SDimitry Andric 
662*0b57cec5SDimitry Andric   // Add stubbuf size alignment
663*0b57cec5SDimitry Andric   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
664*0b57cec5SDimitry Andric   unsigned StubAlignment = getStubAlignment();
665*0b57cec5SDimitry Andric   unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
666*0b57cec5SDimitry Andric   if (StubAlignment > EndAlignment)
667*0b57cec5SDimitry Andric     StubBufSize += StubAlignment - EndAlignment;
668*0b57cec5SDimitry Andric   return StubBufSize;
669*0b57cec5SDimitry Andric }
670*0b57cec5SDimitry Andric 
671*0b57cec5SDimitry Andric uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
672*0b57cec5SDimitry Andric                                              unsigned Size) const {
673*0b57cec5SDimitry Andric   uint64_t Result = 0;
674*0b57cec5SDimitry Andric   if (IsTargetLittleEndian) {
675*0b57cec5SDimitry Andric     Src += Size - 1;
676*0b57cec5SDimitry Andric     while (Size--)
677*0b57cec5SDimitry Andric       Result = (Result << 8) | *Src--;
678*0b57cec5SDimitry Andric   } else
679*0b57cec5SDimitry Andric     while (Size--)
680*0b57cec5SDimitry Andric       Result = (Result << 8) | *Src++;
681*0b57cec5SDimitry Andric 
682*0b57cec5SDimitry Andric   return Result;
683*0b57cec5SDimitry Andric }
684*0b57cec5SDimitry Andric 
685*0b57cec5SDimitry Andric void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
686*0b57cec5SDimitry Andric                                           unsigned Size) const {
687*0b57cec5SDimitry Andric   if (IsTargetLittleEndian) {
688*0b57cec5SDimitry Andric     while (Size--) {
689*0b57cec5SDimitry Andric       *Dst++ = Value & 0xFF;
690*0b57cec5SDimitry Andric       Value >>= 8;
691*0b57cec5SDimitry Andric     }
692*0b57cec5SDimitry Andric   } else {
693*0b57cec5SDimitry Andric     Dst += Size - 1;
694*0b57cec5SDimitry Andric     while (Size--) {
695*0b57cec5SDimitry Andric       *Dst-- = Value & 0xFF;
696*0b57cec5SDimitry Andric       Value >>= 8;
697*0b57cec5SDimitry Andric     }
698*0b57cec5SDimitry Andric   }
699*0b57cec5SDimitry Andric }
700*0b57cec5SDimitry Andric 
701*0b57cec5SDimitry Andric Expected<JITSymbolFlags>
702*0b57cec5SDimitry Andric RuntimeDyldImpl::getJITSymbolFlags(const SymbolRef &SR) {
703*0b57cec5SDimitry Andric   return JITSymbolFlags::fromObjectSymbol(SR);
704*0b57cec5SDimitry Andric }
705*0b57cec5SDimitry Andric 
706*0b57cec5SDimitry Andric Error RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
707*0b57cec5SDimitry Andric                                          CommonSymbolList &SymbolsToAllocate,
708*0b57cec5SDimitry Andric                                          uint64_t CommonSize,
709*0b57cec5SDimitry Andric                                          uint32_t CommonAlign) {
710*0b57cec5SDimitry Andric   if (SymbolsToAllocate.empty())
711*0b57cec5SDimitry Andric     return Error::success();
712*0b57cec5SDimitry Andric 
713*0b57cec5SDimitry Andric   // Allocate memory for the section
714*0b57cec5SDimitry Andric   unsigned SectionID = Sections.size();
715*0b57cec5SDimitry Andric   uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, CommonAlign, SectionID,
716*0b57cec5SDimitry Andric                                              "<common symbols>", false);
717*0b57cec5SDimitry Andric   if (!Addr)
718*0b57cec5SDimitry Andric     report_fatal_error("Unable to allocate memory for common symbols!");
719*0b57cec5SDimitry Andric   uint64_t Offset = 0;
720*0b57cec5SDimitry Andric   Sections.push_back(
721*0b57cec5SDimitry Andric       SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));
722*0b57cec5SDimitry Andric   memset(Addr, 0, CommonSize);
723*0b57cec5SDimitry Andric 
724*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
725*0b57cec5SDimitry Andric                     << " new addr: " << format("%p", Addr)
726*0b57cec5SDimitry Andric                     << " DataSize: " << CommonSize << "\n");
727*0b57cec5SDimitry Andric 
728*0b57cec5SDimitry Andric   // Assign the address of each symbol
729*0b57cec5SDimitry Andric   for (auto &Sym : SymbolsToAllocate) {
730*0b57cec5SDimitry Andric     uint32_t Align = Sym.getAlignment();
731*0b57cec5SDimitry Andric     uint64_t Size = Sym.getCommonSize();
732*0b57cec5SDimitry Andric     StringRef Name;
733*0b57cec5SDimitry Andric     if (auto NameOrErr = Sym.getName())
734*0b57cec5SDimitry Andric       Name = *NameOrErr;
735*0b57cec5SDimitry Andric     else
736*0b57cec5SDimitry Andric       return NameOrErr.takeError();
737*0b57cec5SDimitry Andric     if (Align) {
738*0b57cec5SDimitry Andric       // This symbol has an alignment requirement.
739*0b57cec5SDimitry Andric       uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
740*0b57cec5SDimitry Andric       Addr += AlignOffset;
741*0b57cec5SDimitry Andric       Offset += AlignOffset;
742*0b57cec5SDimitry Andric     }
743*0b57cec5SDimitry Andric     auto JITSymFlags = getJITSymbolFlags(Sym);
744*0b57cec5SDimitry Andric 
745*0b57cec5SDimitry Andric     if (!JITSymFlags)
746*0b57cec5SDimitry Andric       return JITSymFlags.takeError();
747*0b57cec5SDimitry Andric 
748*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
749*0b57cec5SDimitry Andric                       << format("%p", Addr) << "\n");
750*0b57cec5SDimitry Andric     GlobalSymbolTable[Name] =
751*0b57cec5SDimitry Andric         SymbolTableEntry(SectionID, Offset, std::move(*JITSymFlags));
752*0b57cec5SDimitry Andric     Offset += Size;
753*0b57cec5SDimitry Andric     Addr += Size;
754*0b57cec5SDimitry Andric   }
755*0b57cec5SDimitry Andric 
756*0b57cec5SDimitry Andric   return Error::success();
757*0b57cec5SDimitry Andric }
758*0b57cec5SDimitry Andric 
759*0b57cec5SDimitry Andric Expected<unsigned>
760*0b57cec5SDimitry Andric RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
761*0b57cec5SDimitry Andric                              const SectionRef &Section,
762*0b57cec5SDimitry Andric                              bool IsCode) {
763*0b57cec5SDimitry Andric   StringRef data;
764*0b57cec5SDimitry Andric   uint64_t Alignment64 = Section.getAlignment();
765*0b57cec5SDimitry Andric 
766*0b57cec5SDimitry Andric   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
767*0b57cec5SDimitry Andric   unsigned PaddingSize = 0;
768*0b57cec5SDimitry Andric   unsigned StubBufSize = 0;
769*0b57cec5SDimitry Andric   bool IsRequired = isRequiredForExecution(Section);
770*0b57cec5SDimitry Andric   bool IsVirtual = Section.isVirtual();
771*0b57cec5SDimitry Andric   bool IsZeroInit = isZeroInit(Section);
772*0b57cec5SDimitry Andric   bool IsReadOnly = isReadOnlyData(Section);
773*0b57cec5SDimitry Andric   uint64_t DataSize = Section.getSize();
774*0b57cec5SDimitry Andric 
775*0b57cec5SDimitry Andric   // An alignment of 0 (at least with ELF) is identical to an alignment of 1,
776*0b57cec5SDimitry Andric   // while being more "polite".  Other formats do not support 0-aligned sections
777*0b57cec5SDimitry Andric   // anyway, so we should guarantee that the alignment is always at least 1.
778*0b57cec5SDimitry Andric   Alignment = std::max(1u, Alignment);
779*0b57cec5SDimitry Andric 
780*0b57cec5SDimitry Andric   StringRef Name;
781*0b57cec5SDimitry Andric   if (auto EC = Section.getName(Name))
782*0b57cec5SDimitry Andric     return errorCodeToError(EC);
783*0b57cec5SDimitry Andric 
784*0b57cec5SDimitry Andric   StubBufSize = computeSectionStubBufSize(Obj, Section);
785*0b57cec5SDimitry Andric 
786*0b57cec5SDimitry Andric   // The .eh_frame section (at least on Linux) needs an extra four bytes padded
787*0b57cec5SDimitry Andric   // with zeroes added at the end.  For MachO objects, this section has a
788*0b57cec5SDimitry Andric   // slightly different name, so this won't have any effect for MachO objects.
789*0b57cec5SDimitry Andric   if (Name == ".eh_frame")
790*0b57cec5SDimitry Andric     PaddingSize = 4;
791*0b57cec5SDimitry Andric 
792*0b57cec5SDimitry Andric   uintptr_t Allocate;
793*0b57cec5SDimitry Andric   unsigned SectionID = Sections.size();
794*0b57cec5SDimitry Andric   uint8_t *Addr;
795*0b57cec5SDimitry Andric   const char *pData = nullptr;
796*0b57cec5SDimitry Andric 
797*0b57cec5SDimitry Andric   // If this section contains any bits (i.e. isn't a virtual or bss section),
798*0b57cec5SDimitry Andric   // grab a reference to them.
799*0b57cec5SDimitry Andric   if (!IsVirtual && !IsZeroInit) {
800*0b57cec5SDimitry Andric     // In either case, set the location of the unrelocated section in memory,
801*0b57cec5SDimitry Andric     // since we still process relocations for it even if we're not applying them.
802*0b57cec5SDimitry Andric     if (Expected<StringRef> E = Section.getContents())
803*0b57cec5SDimitry Andric       data = *E;
804*0b57cec5SDimitry Andric     else
805*0b57cec5SDimitry Andric       return E.takeError();
806*0b57cec5SDimitry Andric     pData = data.data();
807*0b57cec5SDimitry Andric   }
808*0b57cec5SDimitry Andric 
809*0b57cec5SDimitry Andric   // If there are any stubs then the section alignment needs to be at least as
810*0b57cec5SDimitry Andric   // high as stub alignment or padding calculations may by incorrect when the
811*0b57cec5SDimitry Andric   // section is remapped.
812*0b57cec5SDimitry Andric   if (StubBufSize != 0) {
813*0b57cec5SDimitry Andric     Alignment = std::max(Alignment, getStubAlignment());
814*0b57cec5SDimitry Andric     PaddingSize += getStubAlignment() - 1;
815*0b57cec5SDimitry Andric   }
816*0b57cec5SDimitry Andric 
817*0b57cec5SDimitry Andric   // Some sections, such as debug info, don't need to be loaded for execution.
818*0b57cec5SDimitry Andric   // Process those only if explicitly requested.
819*0b57cec5SDimitry Andric   if (IsRequired || ProcessAllSections) {
820*0b57cec5SDimitry Andric     Allocate = DataSize + PaddingSize + StubBufSize;
821*0b57cec5SDimitry Andric     if (!Allocate)
822*0b57cec5SDimitry Andric       Allocate = 1;
823*0b57cec5SDimitry Andric     Addr = IsCode ? MemMgr.allocateCodeSection(Allocate, Alignment, SectionID,
824*0b57cec5SDimitry Andric                                                Name)
825*0b57cec5SDimitry Andric                   : MemMgr.allocateDataSection(Allocate, Alignment, SectionID,
826*0b57cec5SDimitry Andric                                                Name, IsReadOnly);
827*0b57cec5SDimitry Andric     if (!Addr)
828*0b57cec5SDimitry Andric       report_fatal_error("Unable to allocate section memory!");
829*0b57cec5SDimitry Andric 
830*0b57cec5SDimitry Andric     // Zero-initialize or copy the data from the image
831*0b57cec5SDimitry Andric     if (IsZeroInit || IsVirtual)
832*0b57cec5SDimitry Andric       memset(Addr, 0, DataSize);
833*0b57cec5SDimitry Andric     else
834*0b57cec5SDimitry Andric       memcpy(Addr, pData, DataSize);
835*0b57cec5SDimitry Andric 
836*0b57cec5SDimitry Andric     // Fill in any extra bytes we allocated for padding
837*0b57cec5SDimitry Andric     if (PaddingSize != 0) {
838*0b57cec5SDimitry Andric       memset(Addr + DataSize, 0, PaddingSize);
839*0b57cec5SDimitry Andric       // Update the DataSize variable to include padding.
840*0b57cec5SDimitry Andric       DataSize += PaddingSize;
841*0b57cec5SDimitry Andric 
842*0b57cec5SDimitry Andric       // Align DataSize to stub alignment if we have any stubs (PaddingSize will
843*0b57cec5SDimitry Andric       // have been increased above to account for this).
844*0b57cec5SDimitry Andric       if (StubBufSize > 0)
845*0b57cec5SDimitry Andric         DataSize &= -(uint64_t)getStubAlignment();
846*0b57cec5SDimitry Andric     }
847*0b57cec5SDimitry Andric 
848*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: "
849*0b57cec5SDimitry Andric                       << Name << " obj addr: " << format("%p", pData)
850*0b57cec5SDimitry Andric                       << " new addr: " << format("%p", Addr) << " DataSize: "
851*0b57cec5SDimitry Andric                       << DataSize << " StubBufSize: " << StubBufSize
852*0b57cec5SDimitry Andric                       << " Allocate: " << Allocate << "\n");
853*0b57cec5SDimitry Andric   } else {
854*0b57cec5SDimitry Andric     // Even if we didn't load the section, we need to record an entry for it
855*0b57cec5SDimitry Andric     // to handle later processing (and by 'handle' I mean don't do anything
856*0b57cec5SDimitry Andric     // with these sections).
857*0b57cec5SDimitry Andric     Allocate = 0;
858*0b57cec5SDimitry Andric     Addr = nullptr;
859*0b57cec5SDimitry Andric     LLVM_DEBUG(
860*0b57cec5SDimitry Andric         dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
861*0b57cec5SDimitry Andric                << " obj addr: " << format("%p", data.data()) << " new addr: 0"
862*0b57cec5SDimitry Andric                << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
863*0b57cec5SDimitry Andric                << " Allocate: " << Allocate << "\n");
864*0b57cec5SDimitry Andric   }
865*0b57cec5SDimitry Andric 
866*0b57cec5SDimitry Andric   Sections.push_back(
867*0b57cec5SDimitry Andric       SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));
868*0b57cec5SDimitry Andric 
869*0b57cec5SDimitry Andric   // Debug info sections are linked as if their load address was zero
870*0b57cec5SDimitry Andric   if (!IsRequired)
871*0b57cec5SDimitry Andric     Sections.back().setLoadAddress(0);
872*0b57cec5SDimitry Andric 
873*0b57cec5SDimitry Andric   return SectionID;
874*0b57cec5SDimitry Andric }
875*0b57cec5SDimitry Andric 
876*0b57cec5SDimitry Andric Expected<unsigned>
877*0b57cec5SDimitry Andric RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
878*0b57cec5SDimitry Andric                                    const SectionRef &Section,
879*0b57cec5SDimitry Andric                                    bool IsCode,
880*0b57cec5SDimitry Andric                                    ObjSectionToIDMap &LocalSections) {
881*0b57cec5SDimitry Andric 
882*0b57cec5SDimitry Andric   unsigned SectionID = 0;
883*0b57cec5SDimitry Andric   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
884*0b57cec5SDimitry Andric   if (i != LocalSections.end())
885*0b57cec5SDimitry Andric     SectionID = i->second;
886*0b57cec5SDimitry Andric   else {
887*0b57cec5SDimitry Andric     if (auto SectionIDOrErr = emitSection(Obj, Section, IsCode))
888*0b57cec5SDimitry Andric       SectionID = *SectionIDOrErr;
889*0b57cec5SDimitry Andric     else
890*0b57cec5SDimitry Andric       return SectionIDOrErr.takeError();
891*0b57cec5SDimitry Andric     LocalSections[Section] = SectionID;
892*0b57cec5SDimitry Andric   }
893*0b57cec5SDimitry Andric   return SectionID;
894*0b57cec5SDimitry Andric }
895*0b57cec5SDimitry Andric 
896*0b57cec5SDimitry Andric void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
897*0b57cec5SDimitry Andric                                               unsigned SectionID) {
898*0b57cec5SDimitry Andric   Relocations[SectionID].push_back(RE);
899*0b57cec5SDimitry Andric }
900*0b57cec5SDimitry Andric 
901*0b57cec5SDimitry Andric void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
902*0b57cec5SDimitry Andric                                              StringRef SymbolName) {
903*0b57cec5SDimitry Andric   // Relocation by symbol.  If the symbol is found in the global symbol table,
904*0b57cec5SDimitry Andric   // create an appropriate section relocation.  Otherwise, add it to
905*0b57cec5SDimitry Andric   // ExternalSymbolRelocations.
906*0b57cec5SDimitry Andric   RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
907*0b57cec5SDimitry Andric   if (Loc == GlobalSymbolTable.end()) {
908*0b57cec5SDimitry Andric     ExternalSymbolRelocations[SymbolName].push_back(RE);
909*0b57cec5SDimitry Andric   } else {
910*0b57cec5SDimitry Andric     // Copy the RE since we want to modify its addend.
911*0b57cec5SDimitry Andric     RelocationEntry RECopy = RE;
912*0b57cec5SDimitry Andric     const auto &SymInfo = Loc->second;
913*0b57cec5SDimitry Andric     RECopy.Addend += SymInfo.getOffset();
914*0b57cec5SDimitry Andric     Relocations[SymInfo.getSectionID()].push_back(RECopy);
915*0b57cec5SDimitry Andric   }
916*0b57cec5SDimitry Andric }
917*0b57cec5SDimitry Andric 
918*0b57cec5SDimitry Andric uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
919*0b57cec5SDimitry Andric                                              unsigned AbiVariant) {
920*0b57cec5SDimitry Andric   if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
921*0b57cec5SDimitry Andric     // This stub has to be able to access the full address space,
922*0b57cec5SDimitry Andric     // since symbol lookup won't necessarily find a handy, in-range,
923*0b57cec5SDimitry Andric     // PLT stub for functions which could be anywhere.
924*0b57cec5SDimitry Andric     // Stub can use ip0 (== x16) to calculate address
925*0b57cec5SDimitry Andric     writeBytesUnaligned(0xd2e00010, Addr,    4); // movz ip0, #:abs_g3:<addr>
926*0b57cec5SDimitry Andric     writeBytesUnaligned(0xf2c00010, Addr+4,  4); // movk ip0, #:abs_g2_nc:<addr>
927*0b57cec5SDimitry Andric     writeBytesUnaligned(0xf2a00010, Addr+8,  4); // movk ip0, #:abs_g1_nc:<addr>
928*0b57cec5SDimitry Andric     writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
929*0b57cec5SDimitry Andric     writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
930*0b57cec5SDimitry Andric 
931*0b57cec5SDimitry Andric     return Addr;
932*0b57cec5SDimitry Andric   } else if (Arch == Triple::arm || Arch == Triple::armeb) {
933*0b57cec5SDimitry Andric     // TODO: There is only ARM far stub now. We should add the Thumb stub,
934*0b57cec5SDimitry Andric     // and stubs for branches Thumb - ARM and ARM - Thumb.
935*0b57cec5SDimitry Andric     writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc, [pc, #-4]
936*0b57cec5SDimitry Andric     return Addr + 4;
937*0b57cec5SDimitry Andric   } else if (IsMipsO32ABI || IsMipsN32ABI) {
938*0b57cec5SDimitry Andric     // 0:   3c190000        lui     t9,%hi(addr).
939*0b57cec5SDimitry Andric     // 4:   27390000        addiu   t9,t9,%lo(addr).
940*0b57cec5SDimitry Andric     // 8:   03200008        jr      t9.
941*0b57cec5SDimitry Andric     // c:   00000000        nop.
942*0b57cec5SDimitry Andric     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
943*0b57cec5SDimitry Andric     const unsigned NopInstr = 0x0;
944*0b57cec5SDimitry Andric     unsigned JrT9Instr = 0x03200008;
945*0b57cec5SDimitry Andric     if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_32R6 ||
946*0b57cec5SDimitry Andric         (AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
947*0b57cec5SDimitry Andric       JrT9Instr = 0x03200009;
948*0b57cec5SDimitry Andric 
949*0b57cec5SDimitry Andric     writeBytesUnaligned(LuiT9Instr, Addr, 4);
950*0b57cec5SDimitry Andric     writeBytesUnaligned(AdduiT9Instr, Addr + 4, 4);
951*0b57cec5SDimitry Andric     writeBytesUnaligned(JrT9Instr, Addr + 8, 4);
952*0b57cec5SDimitry Andric     writeBytesUnaligned(NopInstr, Addr + 12, 4);
953*0b57cec5SDimitry Andric     return Addr;
954*0b57cec5SDimitry Andric   } else if (IsMipsN64ABI) {
955*0b57cec5SDimitry Andric     // 0:   3c190000        lui     t9,%highest(addr).
956*0b57cec5SDimitry Andric     // 4:   67390000        daddiu  t9,t9,%higher(addr).
957*0b57cec5SDimitry Andric     // 8:   0019CC38        dsll    t9,t9,16.
958*0b57cec5SDimitry Andric     // c:   67390000        daddiu  t9,t9,%hi(addr).
959*0b57cec5SDimitry Andric     // 10:  0019CC38        dsll    t9,t9,16.
960*0b57cec5SDimitry Andric     // 14:  67390000        daddiu  t9,t9,%lo(addr).
961*0b57cec5SDimitry Andric     // 18:  03200008        jr      t9.
962*0b57cec5SDimitry Andric     // 1c:  00000000        nop.
963*0b57cec5SDimitry Andric     const unsigned LuiT9Instr = 0x3c190000, DaddiuT9Instr = 0x67390000,
964*0b57cec5SDimitry Andric                    DsllT9Instr = 0x19CC38;
965*0b57cec5SDimitry Andric     const unsigned NopInstr = 0x0;
966*0b57cec5SDimitry Andric     unsigned JrT9Instr = 0x03200008;
967*0b57cec5SDimitry Andric     if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
968*0b57cec5SDimitry Andric       JrT9Instr = 0x03200009;
969*0b57cec5SDimitry Andric 
970*0b57cec5SDimitry Andric     writeBytesUnaligned(LuiT9Instr, Addr, 4);
971*0b57cec5SDimitry Andric     writeBytesUnaligned(DaddiuT9Instr, Addr + 4, 4);
972*0b57cec5SDimitry Andric     writeBytesUnaligned(DsllT9Instr, Addr + 8, 4);
973*0b57cec5SDimitry Andric     writeBytesUnaligned(DaddiuT9Instr, Addr + 12, 4);
974*0b57cec5SDimitry Andric     writeBytesUnaligned(DsllT9Instr, Addr + 16, 4);
975*0b57cec5SDimitry Andric     writeBytesUnaligned(DaddiuT9Instr, Addr + 20, 4);
976*0b57cec5SDimitry Andric     writeBytesUnaligned(JrT9Instr, Addr + 24, 4);
977*0b57cec5SDimitry Andric     writeBytesUnaligned(NopInstr, Addr + 28, 4);
978*0b57cec5SDimitry Andric     return Addr;
979*0b57cec5SDimitry Andric   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
980*0b57cec5SDimitry Andric     // Depending on which version of the ELF ABI is in use, we need to
981*0b57cec5SDimitry Andric     // generate one of two variants of the stub.  They both start with
982*0b57cec5SDimitry Andric     // the same sequence to load the target address into r12.
983*0b57cec5SDimitry Andric     writeInt32BE(Addr,    0x3D800000); // lis   r12, highest(addr)
984*0b57cec5SDimitry Andric     writeInt32BE(Addr+4,  0x618C0000); // ori   r12, higher(addr)
985*0b57cec5SDimitry Andric     writeInt32BE(Addr+8,  0x798C07C6); // sldi  r12, r12, 32
986*0b57cec5SDimitry Andric     writeInt32BE(Addr+12, 0x658C0000); // oris  r12, r12, h(addr)
987*0b57cec5SDimitry Andric     writeInt32BE(Addr+16, 0x618C0000); // ori   r12, r12, l(addr)
988*0b57cec5SDimitry Andric     if (AbiVariant == 2) {
989*0b57cec5SDimitry Andric       // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
990*0b57cec5SDimitry Andric       // The address is already in r12 as required by the ABI.  Branch to it.
991*0b57cec5SDimitry Andric       writeInt32BE(Addr+20, 0xF8410018); // std   r2,  24(r1)
992*0b57cec5SDimitry Andric       writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
993*0b57cec5SDimitry Andric       writeInt32BE(Addr+28, 0x4E800420); // bctr
994*0b57cec5SDimitry Andric     } else {
995*0b57cec5SDimitry Andric       // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
996*0b57cec5SDimitry Andric       // Load the function address on r11 and sets it to control register. Also
997*0b57cec5SDimitry Andric       // loads the function TOC in r2 and environment pointer to r11.
998*0b57cec5SDimitry Andric       writeInt32BE(Addr+20, 0xF8410028); // std   r2,  40(r1)
999*0b57cec5SDimitry Andric       writeInt32BE(Addr+24, 0xE96C0000); // ld    r11, 0(r12)
1000*0b57cec5SDimitry Andric       writeInt32BE(Addr+28, 0xE84C0008); // ld    r2,  0(r12)
1001*0b57cec5SDimitry Andric       writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
1002*0b57cec5SDimitry Andric       writeInt32BE(Addr+36, 0xE96C0010); // ld    r11, 16(r2)
1003*0b57cec5SDimitry Andric       writeInt32BE(Addr+40, 0x4E800420); // bctr
1004*0b57cec5SDimitry Andric     }
1005*0b57cec5SDimitry Andric     return Addr;
1006*0b57cec5SDimitry Andric   } else if (Arch == Triple::systemz) {
1007*0b57cec5SDimitry Andric     writeInt16BE(Addr,    0xC418);     // lgrl %r1,.+8
1008*0b57cec5SDimitry Andric     writeInt16BE(Addr+2,  0x0000);
1009*0b57cec5SDimitry Andric     writeInt16BE(Addr+4,  0x0004);
1010*0b57cec5SDimitry Andric     writeInt16BE(Addr+6,  0x07F1);     // brc 15,%r1
1011*0b57cec5SDimitry Andric     // 8-byte address stored at Addr + 8
1012*0b57cec5SDimitry Andric     return Addr;
1013*0b57cec5SDimitry Andric   } else if (Arch == Triple::x86_64) {
1014*0b57cec5SDimitry Andric     *Addr      = 0xFF; // jmp
1015*0b57cec5SDimitry Andric     *(Addr+1)  = 0x25; // rip
1016*0b57cec5SDimitry Andric     // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
1017*0b57cec5SDimitry Andric   } else if (Arch == Triple::x86) {
1018*0b57cec5SDimitry Andric     *Addr      = 0xE9; // 32-bit pc-relative jump.
1019*0b57cec5SDimitry Andric   }
1020*0b57cec5SDimitry Andric   return Addr;
1021*0b57cec5SDimitry Andric }
1022*0b57cec5SDimitry Andric 
1023*0b57cec5SDimitry Andric // Assign an address to a symbol name and resolve all the relocations
1024*0b57cec5SDimitry Andric // associated with it.
1025*0b57cec5SDimitry Andric void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
1026*0b57cec5SDimitry Andric                                              uint64_t Addr) {
1027*0b57cec5SDimitry Andric   // The address to use for relocation resolution is not
1028*0b57cec5SDimitry Andric   // the address of the local section buffer. We must be doing
1029*0b57cec5SDimitry Andric   // a remote execution environment of some sort. Relocations can't
1030*0b57cec5SDimitry Andric   // be applied until all the sections have been moved.  The client must
1031*0b57cec5SDimitry Andric   // trigger this with a call to MCJIT::finalize() or
1032*0b57cec5SDimitry Andric   // RuntimeDyld::resolveRelocations().
1033*0b57cec5SDimitry Andric   //
1034*0b57cec5SDimitry Andric   // Addr is a uint64_t because we can't assume the pointer width
1035*0b57cec5SDimitry Andric   // of the target is the same as that of the host. Just use a generic
1036*0b57cec5SDimitry Andric   // "big enough" type.
1037*0b57cec5SDimitry Andric   LLVM_DEBUG(
1038*0b57cec5SDimitry Andric       dbgs() << "Reassigning address for section " << SectionID << " ("
1039*0b57cec5SDimitry Andric              << Sections[SectionID].getName() << "): "
1040*0b57cec5SDimitry Andric              << format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())
1041*0b57cec5SDimitry Andric              << " -> " << format("0x%016" PRIx64, Addr) << "\n");
1042*0b57cec5SDimitry Andric   Sections[SectionID].setLoadAddress(Addr);
1043*0b57cec5SDimitry Andric }
1044*0b57cec5SDimitry Andric 
1045*0b57cec5SDimitry Andric void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
1046*0b57cec5SDimitry Andric                                             uint64_t Value) {
1047*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1048*0b57cec5SDimitry Andric     const RelocationEntry &RE = Relocs[i];
1049*0b57cec5SDimitry Andric     // Ignore relocations for sections that were not loaded
1050*0b57cec5SDimitry Andric     if (Sections[RE.SectionID].getAddress() == nullptr)
1051*0b57cec5SDimitry Andric       continue;
1052*0b57cec5SDimitry Andric     resolveRelocation(RE, Value);
1053*0b57cec5SDimitry Andric   }
1054*0b57cec5SDimitry Andric }
1055*0b57cec5SDimitry Andric 
1056*0b57cec5SDimitry Andric void RuntimeDyldImpl::applyExternalSymbolRelocations(
1057*0b57cec5SDimitry Andric     const StringMap<JITEvaluatedSymbol> ExternalSymbolMap) {
1058*0b57cec5SDimitry Andric   while (!ExternalSymbolRelocations.empty()) {
1059*0b57cec5SDimitry Andric 
1060*0b57cec5SDimitry Andric     StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
1061*0b57cec5SDimitry Andric 
1062*0b57cec5SDimitry Andric     StringRef Name = i->first();
1063*0b57cec5SDimitry Andric     if (Name.size() == 0) {
1064*0b57cec5SDimitry Andric       // This is an absolute symbol, use an address of zero.
1065*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Resolving absolute relocations."
1066*0b57cec5SDimitry Andric                         << "\n");
1067*0b57cec5SDimitry Andric       RelocationList &Relocs = i->second;
1068*0b57cec5SDimitry Andric       resolveRelocationList(Relocs, 0);
1069*0b57cec5SDimitry Andric     } else {
1070*0b57cec5SDimitry Andric       uint64_t Addr = 0;
1071*0b57cec5SDimitry Andric       JITSymbolFlags Flags;
1072*0b57cec5SDimitry Andric       RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
1073*0b57cec5SDimitry Andric       if (Loc == GlobalSymbolTable.end()) {
1074*0b57cec5SDimitry Andric         auto RRI = ExternalSymbolMap.find(Name);
1075*0b57cec5SDimitry Andric         assert(RRI != ExternalSymbolMap.end() && "No result for symbol");
1076*0b57cec5SDimitry Andric         Addr = RRI->second.getAddress();
1077*0b57cec5SDimitry Andric         Flags = RRI->second.getFlags();
1078*0b57cec5SDimitry Andric         // The call to getSymbolAddress may have caused additional modules to
1079*0b57cec5SDimitry Andric         // be loaded, which may have added new entries to the
1080*0b57cec5SDimitry Andric         // ExternalSymbolRelocations map.  Consquently, we need to update our
1081*0b57cec5SDimitry Andric         // iterator.  This is also why retrieval of the relocation list
1082*0b57cec5SDimitry Andric         // associated with this symbol is deferred until below this point.
1083*0b57cec5SDimitry Andric         // New entries may have been added to the relocation list.
1084*0b57cec5SDimitry Andric         i = ExternalSymbolRelocations.find(Name);
1085*0b57cec5SDimitry Andric       } else {
1086*0b57cec5SDimitry Andric         // We found the symbol in our global table.  It was probably in a
1087*0b57cec5SDimitry Andric         // Module that we loaded previously.
1088*0b57cec5SDimitry Andric         const auto &SymInfo = Loc->second;
1089*0b57cec5SDimitry Andric         Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
1090*0b57cec5SDimitry Andric                SymInfo.getOffset();
1091*0b57cec5SDimitry Andric         Flags = SymInfo.getFlags();
1092*0b57cec5SDimitry Andric       }
1093*0b57cec5SDimitry Andric 
1094*0b57cec5SDimitry Andric       // FIXME: Implement error handling that doesn't kill the host program!
1095*0b57cec5SDimitry Andric       if (!Addr)
1096*0b57cec5SDimitry Andric         report_fatal_error("Program used external function '" + Name +
1097*0b57cec5SDimitry Andric                            "' which could not be resolved!");
1098*0b57cec5SDimitry Andric 
1099*0b57cec5SDimitry Andric       // If Resolver returned UINT64_MAX, the client wants to handle this symbol
1100*0b57cec5SDimitry Andric       // manually and we shouldn't resolve its relocations.
1101*0b57cec5SDimitry Andric       if (Addr != UINT64_MAX) {
1102*0b57cec5SDimitry Andric 
1103*0b57cec5SDimitry Andric         // Tweak the address based on the symbol flags if necessary.
1104*0b57cec5SDimitry Andric         // For example, this is used by RuntimeDyldMachOARM to toggle the low bit
1105*0b57cec5SDimitry Andric         // if the target symbol is Thumb.
1106*0b57cec5SDimitry Andric         Addr = modifyAddressBasedOnFlags(Addr, Flags);
1107*0b57cec5SDimitry Andric 
1108*0b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
1109*0b57cec5SDimitry Andric                           << format("0x%lx", Addr) << "\n");
1110*0b57cec5SDimitry Andric         // This list may have been updated when we called getSymbolAddress, so
1111*0b57cec5SDimitry Andric         // don't change this code to get the list earlier.
1112*0b57cec5SDimitry Andric         RelocationList &Relocs = i->second;
1113*0b57cec5SDimitry Andric         resolveRelocationList(Relocs, Addr);
1114*0b57cec5SDimitry Andric       }
1115*0b57cec5SDimitry Andric     }
1116*0b57cec5SDimitry Andric 
1117*0b57cec5SDimitry Andric     ExternalSymbolRelocations.erase(i);
1118*0b57cec5SDimitry Andric   }
1119*0b57cec5SDimitry Andric }
1120*0b57cec5SDimitry Andric 
1121*0b57cec5SDimitry Andric Error RuntimeDyldImpl::resolveExternalSymbols() {
1122*0b57cec5SDimitry Andric   StringMap<JITEvaluatedSymbol> ExternalSymbolMap;
1123*0b57cec5SDimitry Andric 
1124*0b57cec5SDimitry Andric   // Resolution can trigger emission of more symbols, so iterate until
1125*0b57cec5SDimitry Andric   // we've resolved *everything*.
1126*0b57cec5SDimitry Andric   {
1127*0b57cec5SDimitry Andric     JITSymbolResolver::LookupSet ResolvedSymbols;
1128*0b57cec5SDimitry Andric 
1129*0b57cec5SDimitry Andric     while (true) {
1130*0b57cec5SDimitry Andric       JITSymbolResolver::LookupSet NewSymbols;
1131*0b57cec5SDimitry Andric 
1132*0b57cec5SDimitry Andric       for (auto &RelocKV : ExternalSymbolRelocations) {
1133*0b57cec5SDimitry Andric         StringRef Name = RelocKV.first();
1134*0b57cec5SDimitry Andric         if (!Name.empty() && !GlobalSymbolTable.count(Name) &&
1135*0b57cec5SDimitry Andric             !ResolvedSymbols.count(Name))
1136*0b57cec5SDimitry Andric           NewSymbols.insert(Name);
1137*0b57cec5SDimitry Andric       }
1138*0b57cec5SDimitry Andric 
1139*0b57cec5SDimitry Andric       if (NewSymbols.empty())
1140*0b57cec5SDimitry Andric         break;
1141*0b57cec5SDimitry Andric 
1142*0b57cec5SDimitry Andric #ifdef _MSC_VER
1143*0b57cec5SDimitry Andric       using ExpectedLookupResult =
1144*0b57cec5SDimitry Andric           MSVCPExpected<JITSymbolResolver::LookupResult>;
1145*0b57cec5SDimitry Andric #else
1146*0b57cec5SDimitry Andric       using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
1147*0b57cec5SDimitry Andric #endif
1148*0b57cec5SDimitry Andric 
1149*0b57cec5SDimitry Andric       auto NewSymbolsP = std::make_shared<std::promise<ExpectedLookupResult>>();
1150*0b57cec5SDimitry Andric       auto NewSymbolsF = NewSymbolsP->get_future();
1151*0b57cec5SDimitry Andric       Resolver.lookup(NewSymbols,
1152*0b57cec5SDimitry Andric                       [=](Expected<JITSymbolResolver::LookupResult> Result) {
1153*0b57cec5SDimitry Andric                         NewSymbolsP->set_value(std::move(Result));
1154*0b57cec5SDimitry Andric                       });
1155*0b57cec5SDimitry Andric 
1156*0b57cec5SDimitry Andric       auto NewResolverResults = NewSymbolsF.get();
1157*0b57cec5SDimitry Andric 
1158*0b57cec5SDimitry Andric       if (!NewResolverResults)
1159*0b57cec5SDimitry Andric         return NewResolverResults.takeError();
1160*0b57cec5SDimitry Andric 
1161*0b57cec5SDimitry Andric       assert(NewResolverResults->size() == NewSymbols.size() &&
1162*0b57cec5SDimitry Andric              "Should have errored on unresolved symbols");
1163*0b57cec5SDimitry Andric 
1164*0b57cec5SDimitry Andric       for (auto &RRKV : *NewResolverResults) {
1165*0b57cec5SDimitry Andric         assert(!ResolvedSymbols.count(RRKV.first) && "Redundant resolution?");
1166*0b57cec5SDimitry Andric         ExternalSymbolMap.insert(RRKV);
1167*0b57cec5SDimitry Andric         ResolvedSymbols.insert(RRKV.first);
1168*0b57cec5SDimitry Andric       }
1169*0b57cec5SDimitry Andric     }
1170*0b57cec5SDimitry Andric   }
1171*0b57cec5SDimitry Andric 
1172*0b57cec5SDimitry Andric   applyExternalSymbolRelocations(ExternalSymbolMap);
1173*0b57cec5SDimitry Andric 
1174*0b57cec5SDimitry Andric   return Error::success();
1175*0b57cec5SDimitry Andric }
1176*0b57cec5SDimitry Andric 
1177*0b57cec5SDimitry Andric void RuntimeDyldImpl::finalizeAsync(
1178*0b57cec5SDimitry Andric     std::unique_ptr<RuntimeDyldImpl> This, std::function<void(Error)> OnEmitted,
1179*0b57cec5SDimitry Andric     std::unique_ptr<MemoryBuffer> UnderlyingBuffer) {
1180*0b57cec5SDimitry Andric 
1181*0b57cec5SDimitry Andric   // FIXME: Move-capture OnRelocsApplied and UnderlyingBuffer once we have
1182*0b57cec5SDimitry Andric   // c++14.
1183*0b57cec5SDimitry Andric   auto SharedUnderlyingBuffer =
1184*0b57cec5SDimitry Andric       std::shared_ptr<MemoryBuffer>(std::move(UnderlyingBuffer));
1185*0b57cec5SDimitry Andric   auto SharedThis = std::shared_ptr<RuntimeDyldImpl>(std::move(This));
1186*0b57cec5SDimitry Andric   auto PostResolveContinuation =
1187*0b57cec5SDimitry Andric       [SharedThis, OnEmitted, SharedUnderlyingBuffer](
1188*0b57cec5SDimitry Andric           Expected<JITSymbolResolver::LookupResult> Result) {
1189*0b57cec5SDimitry Andric         if (!Result) {
1190*0b57cec5SDimitry Andric           OnEmitted(Result.takeError());
1191*0b57cec5SDimitry Andric           return;
1192*0b57cec5SDimitry Andric         }
1193*0b57cec5SDimitry Andric 
1194*0b57cec5SDimitry Andric         /// Copy the result into a StringMap, where the keys are held by value.
1195*0b57cec5SDimitry Andric         StringMap<JITEvaluatedSymbol> Resolved;
1196*0b57cec5SDimitry Andric         for (auto &KV : *Result)
1197*0b57cec5SDimitry Andric           Resolved[KV.first] = KV.second;
1198*0b57cec5SDimitry Andric 
1199*0b57cec5SDimitry Andric         SharedThis->applyExternalSymbolRelocations(Resolved);
1200*0b57cec5SDimitry Andric         SharedThis->resolveLocalRelocations();
1201*0b57cec5SDimitry Andric         SharedThis->registerEHFrames();
1202*0b57cec5SDimitry Andric         std::string ErrMsg;
1203*0b57cec5SDimitry Andric         if (SharedThis->MemMgr.finalizeMemory(&ErrMsg))
1204*0b57cec5SDimitry Andric           OnEmitted(make_error<StringError>(std::move(ErrMsg),
1205*0b57cec5SDimitry Andric                                             inconvertibleErrorCode()));
1206*0b57cec5SDimitry Andric         else
1207*0b57cec5SDimitry Andric           OnEmitted(Error::success());
1208*0b57cec5SDimitry Andric       };
1209*0b57cec5SDimitry Andric 
1210*0b57cec5SDimitry Andric   JITSymbolResolver::LookupSet Symbols;
1211*0b57cec5SDimitry Andric 
1212*0b57cec5SDimitry Andric   for (auto &RelocKV : SharedThis->ExternalSymbolRelocations) {
1213*0b57cec5SDimitry Andric     StringRef Name = RelocKV.first();
1214*0b57cec5SDimitry Andric     assert(!Name.empty() && "Symbol has no name?");
1215*0b57cec5SDimitry Andric     assert(!SharedThis->GlobalSymbolTable.count(Name) &&
1216*0b57cec5SDimitry Andric            "Name already processed. RuntimeDyld instances can not be re-used "
1217*0b57cec5SDimitry Andric            "when finalizing with finalizeAsync.");
1218*0b57cec5SDimitry Andric     Symbols.insert(Name);
1219*0b57cec5SDimitry Andric   }
1220*0b57cec5SDimitry Andric 
1221*0b57cec5SDimitry Andric   if (!Symbols.empty()) {
1222*0b57cec5SDimitry Andric     SharedThis->Resolver.lookup(Symbols, PostResolveContinuation);
1223*0b57cec5SDimitry Andric   } else
1224*0b57cec5SDimitry Andric     PostResolveContinuation(std::map<StringRef, JITEvaluatedSymbol>());
1225*0b57cec5SDimitry Andric }
1226*0b57cec5SDimitry Andric 
1227*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1228*0b57cec5SDimitry Andric // RuntimeDyld class implementation
1229*0b57cec5SDimitry Andric 
1230*0b57cec5SDimitry Andric uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
1231*0b57cec5SDimitry Andric                                           const object::SectionRef &Sec) const {
1232*0b57cec5SDimitry Andric 
1233*0b57cec5SDimitry Andric   auto I = ObjSecToIDMap.find(Sec);
1234*0b57cec5SDimitry Andric   if (I != ObjSecToIDMap.end())
1235*0b57cec5SDimitry Andric     return RTDyld.Sections[I->second].getLoadAddress();
1236*0b57cec5SDimitry Andric 
1237*0b57cec5SDimitry Andric   return 0;
1238*0b57cec5SDimitry Andric }
1239*0b57cec5SDimitry Andric 
1240*0b57cec5SDimitry Andric void RuntimeDyld::MemoryManager::anchor() {}
1241*0b57cec5SDimitry Andric void JITSymbolResolver::anchor() {}
1242*0b57cec5SDimitry Andric void LegacyJITSymbolResolver::anchor() {}
1243*0b57cec5SDimitry Andric 
1244*0b57cec5SDimitry Andric RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
1245*0b57cec5SDimitry Andric                          JITSymbolResolver &Resolver)
1246*0b57cec5SDimitry Andric     : MemMgr(MemMgr), Resolver(Resolver) {
1247*0b57cec5SDimitry Andric   // FIXME: There's a potential issue lurking here if a single instance of
1248*0b57cec5SDimitry Andric   // RuntimeDyld is used to load multiple objects.  The current implementation
1249*0b57cec5SDimitry Andric   // associates a single memory manager with a RuntimeDyld instance.  Even
1250*0b57cec5SDimitry Andric   // though the public class spawns a new 'impl' instance for each load,
1251*0b57cec5SDimitry Andric   // they share a single memory manager.  This can become a problem when page
1252*0b57cec5SDimitry Andric   // permissions are applied.
1253*0b57cec5SDimitry Andric   Dyld = nullptr;
1254*0b57cec5SDimitry Andric   ProcessAllSections = false;
1255*0b57cec5SDimitry Andric }
1256*0b57cec5SDimitry Andric 
1257*0b57cec5SDimitry Andric RuntimeDyld::~RuntimeDyld() {}
1258*0b57cec5SDimitry Andric 
1259*0b57cec5SDimitry Andric static std::unique_ptr<RuntimeDyldCOFF>
1260*0b57cec5SDimitry Andric createRuntimeDyldCOFF(
1261*0b57cec5SDimitry Andric                      Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
1262*0b57cec5SDimitry Andric                      JITSymbolResolver &Resolver, bool ProcessAllSections,
1263*0b57cec5SDimitry Andric                      RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
1264*0b57cec5SDimitry Andric   std::unique_ptr<RuntimeDyldCOFF> Dyld =
1265*0b57cec5SDimitry Andric     RuntimeDyldCOFF::create(Arch, MM, Resolver);
1266*0b57cec5SDimitry Andric   Dyld->setProcessAllSections(ProcessAllSections);
1267*0b57cec5SDimitry Andric   Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
1268*0b57cec5SDimitry Andric   return Dyld;
1269*0b57cec5SDimitry Andric }
1270*0b57cec5SDimitry Andric 
1271*0b57cec5SDimitry Andric static std::unique_ptr<RuntimeDyldELF>
1272*0b57cec5SDimitry Andric createRuntimeDyldELF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
1273*0b57cec5SDimitry Andric                      JITSymbolResolver &Resolver, bool ProcessAllSections,
1274*0b57cec5SDimitry Andric                      RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
1275*0b57cec5SDimitry Andric   std::unique_ptr<RuntimeDyldELF> Dyld =
1276*0b57cec5SDimitry Andric       RuntimeDyldELF::create(Arch, MM, Resolver);
1277*0b57cec5SDimitry Andric   Dyld->setProcessAllSections(ProcessAllSections);
1278*0b57cec5SDimitry Andric   Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
1279*0b57cec5SDimitry Andric   return Dyld;
1280*0b57cec5SDimitry Andric }
1281*0b57cec5SDimitry Andric 
1282*0b57cec5SDimitry Andric static std::unique_ptr<RuntimeDyldMachO>
1283*0b57cec5SDimitry Andric createRuntimeDyldMachO(
1284*0b57cec5SDimitry Andric                      Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
1285*0b57cec5SDimitry Andric                      JITSymbolResolver &Resolver,
1286*0b57cec5SDimitry Andric                      bool ProcessAllSections,
1287*0b57cec5SDimitry Andric                      RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
1288*0b57cec5SDimitry Andric   std::unique_ptr<RuntimeDyldMachO> Dyld =
1289*0b57cec5SDimitry Andric     RuntimeDyldMachO::create(Arch, MM, Resolver);
1290*0b57cec5SDimitry Andric   Dyld->setProcessAllSections(ProcessAllSections);
1291*0b57cec5SDimitry Andric   Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
1292*0b57cec5SDimitry Andric   return Dyld;
1293*0b57cec5SDimitry Andric }
1294*0b57cec5SDimitry Andric 
1295*0b57cec5SDimitry Andric std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
1296*0b57cec5SDimitry Andric RuntimeDyld::loadObject(const ObjectFile &Obj) {
1297*0b57cec5SDimitry Andric   if (!Dyld) {
1298*0b57cec5SDimitry Andric     if (Obj.isELF())
1299*0b57cec5SDimitry Andric       Dyld =
1300*0b57cec5SDimitry Andric           createRuntimeDyldELF(static_cast<Triple::ArchType>(Obj.getArch()),
1301*0b57cec5SDimitry Andric                                MemMgr, Resolver, ProcessAllSections,
1302*0b57cec5SDimitry Andric                                std::move(NotifyStubEmitted));
1303*0b57cec5SDimitry Andric     else if (Obj.isMachO())
1304*0b57cec5SDimitry Andric       Dyld = createRuntimeDyldMachO(
1305*0b57cec5SDimitry Andric                static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
1306*0b57cec5SDimitry Andric                ProcessAllSections, std::move(NotifyStubEmitted));
1307*0b57cec5SDimitry Andric     else if (Obj.isCOFF())
1308*0b57cec5SDimitry Andric       Dyld = createRuntimeDyldCOFF(
1309*0b57cec5SDimitry Andric                static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
1310*0b57cec5SDimitry Andric                ProcessAllSections, std::move(NotifyStubEmitted));
1311*0b57cec5SDimitry Andric     else
1312*0b57cec5SDimitry Andric       report_fatal_error("Incompatible object format!");
1313*0b57cec5SDimitry Andric   }
1314*0b57cec5SDimitry Andric 
1315*0b57cec5SDimitry Andric   if (!Dyld->isCompatibleFile(Obj))
1316*0b57cec5SDimitry Andric     report_fatal_error("Incompatible object format!");
1317*0b57cec5SDimitry Andric 
1318*0b57cec5SDimitry Andric   auto LoadedObjInfo = Dyld->loadObject(Obj);
1319*0b57cec5SDimitry Andric   MemMgr.notifyObjectLoaded(*this, Obj);
1320*0b57cec5SDimitry Andric   return LoadedObjInfo;
1321*0b57cec5SDimitry Andric }
1322*0b57cec5SDimitry Andric 
1323*0b57cec5SDimitry Andric void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
1324*0b57cec5SDimitry Andric   if (!Dyld)
1325*0b57cec5SDimitry Andric     return nullptr;
1326*0b57cec5SDimitry Andric   return Dyld->getSymbolLocalAddress(Name);
1327*0b57cec5SDimitry Andric }
1328*0b57cec5SDimitry Andric 
1329*0b57cec5SDimitry Andric unsigned RuntimeDyld::getSymbolSectionID(StringRef Name) const {
1330*0b57cec5SDimitry Andric   assert(Dyld && "No RuntimeDyld instance attached");
1331*0b57cec5SDimitry Andric   return Dyld->getSymbolSectionID(Name);
1332*0b57cec5SDimitry Andric }
1333*0b57cec5SDimitry Andric 
1334*0b57cec5SDimitry Andric JITEvaluatedSymbol RuntimeDyld::getSymbol(StringRef Name) const {
1335*0b57cec5SDimitry Andric   if (!Dyld)
1336*0b57cec5SDimitry Andric     return nullptr;
1337*0b57cec5SDimitry Andric   return Dyld->getSymbol(Name);
1338*0b57cec5SDimitry Andric }
1339*0b57cec5SDimitry Andric 
1340*0b57cec5SDimitry Andric std::map<StringRef, JITEvaluatedSymbol> RuntimeDyld::getSymbolTable() const {
1341*0b57cec5SDimitry Andric   if (!Dyld)
1342*0b57cec5SDimitry Andric     return std::map<StringRef, JITEvaluatedSymbol>();
1343*0b57cec5SDimitry Andric   return Dyld->getSymbolTable();
1344*0b57cec5SDimitry Andric }
1345*0b57cec5SDimitry Andric 
1346*0b57cec5SDimitry Andric void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
1347*0b57cec5SDimitry Andric 
1348*0b57cec5SDimitry Andric void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
1349*0b57cec5SDimitry Andric   Dyld->reassignSectionAddress(SectionID, Addr);
1350*0b57cec5SDimitry Andric }
1351*0b57cec5SDimitry Andric 
1352*0b57cec5SDimitry Andric void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
1353*0b57cec5SDimitry Andric                                     uint64_t TargetAddress) {
1354*0b57cec5SDimitry Andric   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
1355*0b57cec5SDimitry Andric }
1356*0b57cec5SDimitry Andric 
1357*0b57cec5SDimitry Andric bool RuntimeDyld::hasError() { return Dyld->hasError(); }
1358*0b57cec5SDimitry Andric 
1359*0b57cec5SDimitry Andric StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
1360*0b57cec5SDimitry Andric 
1361*0b57cec5SDimitry Andric void RuntimeDyld::finalizeWithMemoryManagerLocking() {
1362*0b57cec5SDimitry Andric   bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;
1363*0b57cec5SDimitry Andric   MemMgr.FinalizationLocked = true;
1364*0b57cec5SDimitry Andric   resolveRelocations();
1365*0b57cec5SDimitry Andric   registerEHFrames();
1366*0b57cec5SDimitry Andric   if (!MemoryFinalizationLocked) {
1367*0b57cec5SDimitry Andric     MemMgr.finalizeMemory();
1368*0b57cec5SDimitry Andric     MemMgr.FinalizationLocked = false;
1369*0b57cec5SDimitry Andric   }
1370*0b57cec5SDimitry Andric }
1371*0b57cec5SDimitry Andric 
1372*0b57cec5SDimitry Andric StringRef RuntimeDyld::getSectionContent(unsigned SectionID) const {
1373*0b57cec5SDimitry Andric   assert(Dyld && "No Dyld instance attached");
1374*0b57cec5SDimitry Andric   return Dyld->getSectionContent(SectionID);
1375*0b57cec5SDimitry Andric }
1376*0b57cec5SDimitry Andric 
1377*0b57cec5SDimitry Andric uint64_t RuntimeDyld::getSectionLoadAddress(unsigned SectionID) const {
1378*0b57cec5SDimitry Andric   assert(Dyld && "No Dyld instance attached");
1379*0b57cec5SDimitry Andric   return Dyld->getSectionLoadAddress(SectionID);
1380*0b57cec5SDimitry Andric }
1381*0b57cec5SDimitry Andric 
1382*0b57cec5SDimitry Andric void RuntimeDyld::registerEHFrames() {
1383*0b57cec5SDimitry Andric   if (Dyld)
1384*0b57cec5SDimitry Andric     Dyld->registerEHFrames();
1385*0b57cec5SDimitry Andric }
1386*0b57cec5SDimitry Andric 
1387*0b57cec5SDimitry Andric void RuntimeDyld::deregisterEHFrames() {
1388*0b57cec5SDimitry Andric   if (Dyld)
1389*0b57cec5SDimitry Andric     Dyld->deregisterEHFrames();
1390*0b57cec5SDimitry Andric }
1391*0b57cec5SDimitry Andric // FIXME: Kill this with fire once we have a new JIT linker: this is only here
1392*0b57cec5SDimitry Andric // so that we can re-use RuntimeDyld's implementation without twisting the
1393*0b57cec5SDimitry Andric // interface any further for ORC's purposes.
1394*0b57cec5SDimitry Andric void jitLinkForORC(object::ObjectFile &Obj,
1395*0b57cec5SDimitry Andric                    std::unique_ptr<MemoryBuffer> UnderlyingBuffer,
1396*0b57cec5SDimitry Andric                    RuntimeDyld::MemoryManager &MemMgr,
1397*0b57cec5SDimitry Andric                    JITSymbolResolver &Resolver, bool ProcessAllSections,
1398*0b57cec5SDimitry Andric                    std::function<Error(
1399*0b57cec5SDimitry Andric                        std::unique_ptr<RuntimeDyld::LoadedObjectInfo> LoadedObj,
1400*0b57cec5SDimitry Andric                        std::map<StringRef, JITEvaluatedSymbol>)>
1401*0b57cec5SDimitry Andric                        OnLoaded,
1402*0b57cec5SDimitry Andric                    std::function<void(Error)> OnEmitted) {
1403*0b57cec5SDimitry Andric 
1404*0b57cec5SDimitry Andric   RuntimeDyld RTDyld(MemMgr, Resolver);
1405*0b57cec5SDimitry Andric   RTDyld.setProcessAllSections(ProcessAllSections);
1406*0b57cec5SDimitry Andric 
1407*0b57cec5SDimitry Andric   auto Info = RTDyld.loadObject(Obj);
1408*0b57cec5SDimitry Andric 
1409*0b57cec5SDimitry Andric   if (RTDyld.hasError()) {
1410*0b57cec5SDimitry Andric     OnEmitted(make_error<StringError>(RTDyld.getErrorString(),
1411*0b57cec5SDimitry Andric                                       inconvertibleErrorCode()));
1412*0b57cec5SDimitry Andric     return;
1413*0b57cec5SDimitry Andric   }
1414*0b57cec5SDimitry Andric 
1415*0b57cec5SDimitry Andric   if (auto Err = OnLoaded(std::move(Info), RTDyld.getSymbolTable()))
1416*0b57cec5SDimitry Andric     OnEmitted(std::move(Err));
1417*0b57cec5SDimitry Andric 
1418*0b57cec5SDimitry Andric   RuntimeDyldImpl::finalizeAsync(std::move(RTDyld.Dyld), std::move(OnEmitted),
1419*0b57cec5SDimitry Andric                                  std::move(UnderlyingBuffer));
1420*0b57cec5SDimitry Andric }
1421*0b57cec5SDimitry Andric 
1422*0b57cec5SDimitry Andric } // end namespace llvm
1423