1 //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implementation of the MC-JIT runtime dynamic linker.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ExecutionEngine/RuntimeDyld.h"
15 #include "RuntimeDyldCheckerImpl.h"
16 #include "RuntimeDyldCOFF.h"
17 #include "RuntimeDyldELF.h"
18 #include "RuntimeDyldImpl.h"
19 #include "RuntimeDyldMachO.h"
20 #include "llvm/Object/ELFObjectFile.h"
21 #include "llvm/Object/COFF.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/MutexGuard.h"
24 
25 using namespace llvm;
26 using namespace llvm::object;
27 
28 #define DEBUG_TYPE "dyld"
29 
30 // Empty out-of-line virtual destructor as the key function.
31 RuntimeDyldImpl::~RuntimeDyldImpl() {}
32 
33 // Pin LoadedObjectInfo's vtables to this file.
34 void RuntimeDyld::LoadedObjectInfo::anchor() {}
35 
36 namespace llvm {
37 
38 void RuntimeDyldImpl::registerEHFrames() {}
39 
40 void RuntimeDyldImpl::deregisterEHFrames() {}
41 
42 #ifndef NDEBUG
43 static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
44   dbgs() << "----- Contents of section " << S.getName() << " " << State
45          << " -----";
46 
47   if (S.getAddress() == nullptr) {
48     dbgs() << "\n          <section not emitted>\n";
49     return;
50   }
51 
52   const unsigned ColsPerRow = 16;
53 
54   uint8_t *DataAddr = S.getAddress();
55   uint64_t LoadAddr = S.getLoadAddress();
56 
57   unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
58   unsigned BytesRemaining = S.getSize();
59 
60   if (StartPadding) {
61     dbgs() << "\n" << format("0x%016" PRIx64,
62                              LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
63     while (StartPadding--)
64       dbgs() << "   ";
65   }
66 
67   while (BytesRemaining > 0) {
68     if ((LoadAddr & (ColsPerRow - 1)) == 0)
69       dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
70 
71     dbgs() << " " << format("%02x", *DataAddr);
72 
73     ++DataAddr;
74     ++LoadAddr;
75     --BytesRemaining;
76   }
77 
78   dbgs() << "\n";
79 }
80 #endif
81 
82 // Resolve the relocations for all symbols we currently know about.
83 void RuntimeDyldImpl::resolveRelocations() {
84   MutexGuard locked(lock);
85 
86   // Print out the sections prior to relocation.
87   DEBUG(
88     for (int i = 0, e = Sections.size(); i != e; ++i)
89       dumpSectionMemory(Sections[i], "before relocations");
90   );
91 
92   // First, resolve relocations associated with external symbols.
93   resolveExternalSymbols();
94 
95   // Iterate over all outstanding relocations
96   for (auto it = Relocations.begin(), e = Relocations.end(); it != e; ++it) {
97     // The Section here (Sections[i]) refers to the section in which the
98     // symbol for the relocation is located.  The SectionID in the relocation
99     // entry provides the section to which the relocation will be applied.
100     int Idx = it->first;
101     uint64_t Addr = Sections[Idx].getLoadAddress();
102     DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"
103                  << format("%p", (uintptr_t)Addr) << "\n");
104     resolveRelocationList(it->second, Addr);
105   }
106   Relocations.clear();
107 
108   // Print out sections after relocation.
109   DEBUG(
110     for (int i = 0, e = Sections.size(); i != e; ++i)
111       dumpSectionMemory(Sections[i], "after relocations");
112   );
113 
114 }
115 
116 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
117                                         uint64_t TargetAddress) {
118   MutexGuard locked(lock);
119   for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
120     if (Sections[i].getAddress() == LocalAddress) {
121       reassignSectionAddress(i, TargetAddress);
122       return;
123     }
124   }
125   llvm_unreachable("Attempting to remap address of unknown section!");
126 }
127 
128 static std::error_code getOffset(const SymbolRef &Sym, SectionRef Sec,
129                                  uint64_t &Result) {
130   ErrorOr<uint64_t> AddressOrErr = Sym.getAddress();
131   if (std::error_code EC = AddressOrErr.getError())
132     return EC;
133   Result = *AddressOrErr - Sec.getAddress();
134   return std::error_code();
135 }
136 
137 RuntimeDyldImpl::ObjSectionToIDMap
138 RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
139   MutexGuard locked(lock);
140 
141   // Save information about our target
142   Arch = (Triple::ArchType)Obj.getArch();
143   IsTargetLittleEndian = Obj.isLittleEndian();
144   setMipsABI(Obj);
145 
146   // Compute the memory size required to load all sections to be loaded
147   // and pass this information to the memory manager
148   if (MemMgr.needsToReserveAllocationSpace()) {
149     uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;
150     uint32_t CodeAlign = 1, RODataAlign = 1, RWDataAlign = 1;
151     computeTotalAllocSize(Obj, CodeSize, CodeAlign, RODataSize, RODataAlign,
152                           RWDataSize, RWDataAlign);
153     MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,
154                                   RWDataSize, RWDataAlign);
155   }
156 
157   // Used sections from the object file
158   ObjSectionToIDMap LocalSections;
159 
160   // Common symbols requiring allocation, with their sizes and alignments
161   CommonSymbolList CommonSymbols;
162 
163   // Parse symbols
164   DEBUG(dbgs() << "Parse symbols:\n");
165   for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
166        ++I) {
167     uint32_t Flags = I->getFlags();
168 
169     if (Flags & SymbolRef::SF_Common)
170       CommonSymbols.push_back(*I);
171     else {
172       ErrorOr<object::SymbolRef::Type> SymTypeOrErr = I->getType();
173       Check(SymTypeOrErr.getError());
174       object::SymbolRef::Type SymType = *SymTypeOrErr;
175 
176       // Get symbol name.
177       ErrorOr<StringRef> NameOrErr = I->getName();
178       Check(NameOrErr.getError());
179       StringRef Name = *NameOrErr;
180 
181       // Compute JIT symbol flags.
182       JITSymbolFlags RTDyldSymFlags = JITSymbolFlags::None;
183       if (Flags & SymbolRef::SF_Weak)
184         RTDyldSymFlags |= JITSymbolFlags::Weak;
185       if (Flags & SymbolRef::SF_Exported)
186         RTDyldSymFlags |= JITSymbolFlags::Exported;
187 
188       if (Flags & SymbolRef::SF_Absolute &&
189           SymType != object::SymbolRef::ST_File) {
190         auto Addr = I->getAddress();
191         Check(Addr.getError());
192         uint64_t SectOffset = *Addr;
193         unsigned SectionID = AbsoluteSymbolSection;
194 
195         DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name
196                      << " SID: " << SectionID << " Offset: "
197                      << format("%p", (uintptr_t)SectOffset)
198                      << " flags: " << Flags << "\n");
199         GlobalSymbolTable[Name] =
200           SymbolTableEntry(SectionID, SectOffset, RTDyldSymFlags);
201       } else if (SymType == object::SymbolRef::ST_Function ||
202                  SymType == object::SymbolRef::ST_Data ||
203                  SymType == object::SymbolRef::ST_Unknown ||
204                  SymType == object::SymbolRef::ST_Other) {
205 
206         ErrorOr<section_iterator> SIOrErr = I->getSection();
207         Check(SIOrErr.getError());
208         section_iterator SI = *SIOrErr;
209         if (SI == Obj.section_end())
210           continue;
211         // Get symbol offset.
212         uint64_t SectOffset;
213         Check(getOffset(*I, *SI, SectOffset));
214         bool IsCode = SI->isText();
215         unsigned SectionID = findOrEmitSection(Obj, *SI, IsCode, LocalSections);
216 
217         DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
218                      << " SID: " << SectionID << " Offset: "
219                      << format("%p", (uintptr_t)SectOffset)
220                      << " flags: " << Flags << "\n");
221         GlobalSymbolTable[Name] =
222           SymbolTableEntry(SectionID, SectOffset, RTDyldSymFlags);
223       }
224     }
225   }
226 
227   // Allocate common symbols
228   emitCommonSymbols(Obj, CommonSymbols);
229 
230   // Parse and process relocations
231   DEBUG(dbgs() << "Parse relocations:\n");
232   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
233        SI != SE; ++SI) {
234     unsigned SectionID = 0;
235     StubMap Stubs;
236     section_iterator RelocatedSection = SI->getRelocatedSection();
237 
238     if (RelocatedSection == SE)
239       continue;
240 
241     relocation_iterator I = SI->relocation_begin();
242     relocation_iterator E = SI->relocation_end();
243 
244     if (I == E && !ProcessAllSections)
245       continue;
246 
247     bool IsCode = RelocatedSection->isText();
248     SectionID =
249         findOrEmitSection(Obj, *RelocatedSection, IsCode, LocalSections);
250     DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
251 
252     for (; I != E;)
253       I = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs);
254 
255     // If there is an attached checker, notify it about the stubs for this
256     // section so that they can be verified.
257     if (Checker)
258       Checker->registerStubMap(Obj.getFileName(), SectionID, Stubs);
259   }
260 
261   // Give the subclasses a chance to tie-up any loose ends.
262   finalizeLoad(Obj, LocalSections);
263 
264 //   for (auto E : LocalSections)
265 //     llvm::dbgs() << "Added: " << E.first.getRawDataRefImpl() << " -> " << E.second << "\n";
266 
267   return LocalSections;
268 }
269 
270 // A helper method for computeTotalAllocSize.
271 // Computes the memory size required to allocate sections with the given sizes,
272 // assuming that all sections are allocated with the given alignment
273 static uint64_t
274 computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
275                                  uint64_t Alignment) {
276   uint64_t TotalSize = 0;
277   for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
278     uint64_t AlignedSize =
279         (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
280     TotalSize += AlignedSize;
281   }
282   return TotalSize;
283 }
284 
285 static bool isRequiredForExecution(const SectionRef Section) {
286   const ObjectFile *Obj = Section.getObject();
287   if (isa<object::ELFObjectFileBase>(Obj))
288     return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
289   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
290     const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
291     // Avoid loading zero-sized COFF sections.
292     // In PE files, VirtualSize gives the section size, and SizeOfRawData
293     // may be zero for sections with content. In Obj files, SizeOfRawData
294     // gives the section size, and VirtualSize is always zero. Hence
295     // the need to check for both cases below.
296     bool HasContent = (CoffSection->VirtualSize > 0)
297       || (CoffSection->SizeOfRawData > 0);
298     bool IsDiscardable = CoffSection->Characteristics &
299       (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
300     return HasContent && !IsDiscardable;
301   }
302 
303   assert(isa<MachOObjectFile>(Obj));
304   return true;
305 }
306 
307 static bool isReadOnlyData(const SectionRef Section) {
308   const ObjectFile *Obj = Section.getObject();
309   if (isa<object::ELFObjectFileBase>(Obj))
310     return !(ELFSectionRef(Section).getFlags() &
311              (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
312   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
313     return ((COFFObj->getCOFFSection(Section)->Characteristics &
314              (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
315              | COFF::IMAGE_SCN_MEM_READ
316              | COFF::IMAGE_SCN_MEM_WRITE))
317              ==
318              (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
319              | COFF::IMAGE_SCN_MEM_READ));
320 
321   assert(isa<MachOObjectFile>(Obj));
322   return false;
323 }
324 
325 static bool isZeroInit(const SectionRef Section) {
326   const ObjectFile *Obj = Section.getObject();
327   if (isa<object::ELFObjectFileBase>(Obj))
328     return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
329   if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
330     return COFFObj->getCOFFSection(Section)->Characteristics &
331             COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
332 
333   auto *MachO = cast<MachOObjectFile>(Obj);
334   unsigned SectionType = MachO->getSectionType(Section);
335   return SectionType == MachO::S_ZEROFILL ||
336          SectionType == MachO::S_GB_ZEROFILL;
337 }
338 
339 // Compute an upper bound of the memory size that is required to load all
340 // sections
341 void RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
342                                             uint64_t &CodeSize,
343                                             uint32_t &CodeAlign,
344                                             uint64_t &RODataSize,
345                                             uint32_t &RODataAlign,
346                                             uint64_t &RWDataSize,
347                                             uint32_t &RWDataAlign) {
348   // Compute the size of all sections required for execution
349   std::vector<uint64_t> CodeSectionSizes;
350   std::vector<uint64_t> ROSectionSizes;
351   std::vector<uint64_t> RWSectionSizes;
352 
353   // Collect sizes of all sections to be loaded;
354   // also determine the max alignment of all sections
355   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
356        SI != SE; ++SI) {
357     const SectionRef &Section = *SI;
358 
359     bool IsRequired = isRequiredForExecution(Section);
360 
361     // Consider only the sections that are required to be loaded for execution
362     if (IsRequired) {
363       StringRef Name;
364       uint64_t DataSize = Section.getSize();
365       uint64_t Alignment64 = Section.getAlignment();
366       bool IsCode = Section.isText();
367       bool IsReadOnly = isReadOnlyData(Section);
368       Check(Section.getName(Name));
369       unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
370 
371       uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
372       uint64_t SectionSize = DataSize + StubBufSize;
373 
374       // The .eh_frame section (at least on Linux) needs an extra four bytes
375       // padded
376       // with zeroes added at the end.  For MachO objects, this section has a
377       // slightly different name, so this won't have any effect for MachO
378       // objects.
379       if (Name == ".eh_frame")
380         SectionSize += 4;
381 
382       if (!SectionSize)
383         SectionSize = 1;
384 
385       if (IsCode) {
386         CodeAlign = std::max(CodeAlign, Alignment);
387         CodeSectionSizes.push_back(SectionSize);
388       } else if (IsReadOnly) {
389         RODataAlign = std::max(RODataAlign, Alignment);
390         ROSectionSizes.push_back(SectionSize);
391       } else {
392         RWDataAlign = std::max(RWDataAlign, Alignment);
393         RWSectionSizes.push_back(SectionSize);
394       }
395     }
396   }
397 
398   // Compute the size of all common symbols
399   uint64_t CommonSize = 0;
400   for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
401        ++I) {
402     uint32_t Flags = I->getFlags();
403     if (Flags & SymbolRef::SF_Common) {
404       // Add the common symbols to a list.  We'll allocate them all below.
405       uint64_t Size = I->getCommonSize();
406       CommonSize += Size;
407     }
408   }
409   if (CommonSize != 0) {
410     RWSectionSizes.push_back(CommonSize);
411   }
412 
413   // Compute the required allocation space for each different type of sections
414   // (code, read-only data, read-write data) assuming that all sections are
415   // allocated with the max alignment. Note that we cannot compute with the
416   // individual alignments of the sections, because then the required size
417   // depends on the order, in which the sections are allocated.
418   CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);
419   RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);
420   RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);
421 }
422 
423 // compute stub buffer size for the given section
424 unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
425                                                     const SectionRef &Section) {
426   unsigned StubSize = getMaxStubSize();
427   if (StubSize == 0) {
428     return 0;
429   }
430   // FIXME: this is an inefficient way to handle this. We should computed the
431   // necessary section allocation size in loadObject by walking all the sections
432   // once.
433   unsigned StubBufSize = 0;
434   for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
435        SI != SE; ++SI) {
436     section_iterator RelSecI = SI->getRelocatedSection();
437     if (!(RelSecI == Section))
438       continue;
439 
440     for (const RelocationRef &Reloc : SI->relocations())
441       if (relocationNeedsStub(Reloc))
442         StubBufSize += StubSize;
443   }
444 
445   // Get section data size and alignment
446   uint64_t DataSize = Section.getSize();
447   uint64_t Alignment64 = Section.getAlignment();
448 
449   // Add stubbuf size alignment
450   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
451   unsigned StubAlignment = getStubAlignment();
452   unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
453   if (StubAlignment > EndAlignment)
454     StubBufSize += StubAlignment - EndAlignment;
455   return StubBufSize;
456 }
457 
458 uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
459                                              unsigned Size) const {
460   uint64_t Result = 0;
461   if (IsTargetLittleEndian) {
462     Src += Size - 1;
463     while (Size--)
464       Result = (Result << 8) | *Src--;
465   } else
466     while (Size--)
467       Result = (Result << 8) | *Src++;
468 
469   return Result;
470 }
471 
472 void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
473                                           unsigned Size) const {
474   if (IsTargetLittleEndian) {
475     while (Size--) {
476       *Dst++ = Value & 0xFF;
477       Value >>= 8;
478     }
479   } else {
480     Dst += Size - 1;
481     while (Size--) {
482       *Dst-- = Value & 0xFF;
483       Value >>= 8;
484     }
485   }
486 }
487 
488 void RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
489                                         CommonSymbolList &CommonSymbols) {
490   if (CommonSymbols.empty())
491     return;
492 
493   uint64_t CommonSize = 0;
494   CommonSymbolList SymbolsToAllocate;
495 
496   DEBUG(dbgs() << "Processing common symbols...\n");
497 
498   for (const auto &Sym : CommonSymbols) {
499     ErrorOr<StringRef> NameOrErr = Sym.getName();
500     Check(NameOrErr.getError());
501     StringRef Name = *NameOrErr;
502 
503     // Skip common symbols already elsewhere.
504     if (GlobalSymbolTable.count(Name) ||
505         Resolver.findSymbolInLogicalDylib(Name)) {
506       DEBUG(dbgs() << "\tSkipping already emitted common symbol '" << Name
507                    << "'\n");
508       continue;
509     }
510 
511     uint32_t Align = Sym.getAlignment();
512     uint64_t Size = Sym.getCommonSize();
513 
514     CommonSize += Align + Size;
515     SymbolsToAllocate.push_back(Sym);
516   }
517 
518   // Allocate memory for the section
519   unsigned SectionID = Sections.size();
520   uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, sizeof(void *),
521                                              SectionID, StringRef(), false);
522   if (!Addr)
523     report_fatal_error("Unable to allocate memory for common symbols!");
524   uint64_t Offset = 0;
525   Sections.push_back(
526       SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));
527   memset(Addr, 0, CommonSize);
528 
529   DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID << " new addr: "
530                << format("%p", Addr) << " DataSize: " << CommonSize << "\n");
531 
532   // Assign the address of each symbol
533   for (auto &Sym : SymbolsToAllocate) {
534     uint32_t Align = Sym.getAlignment();
535     uint64_t Size = Sym.getCommonSize();
536     ErrorOr<StringRef> NameOrErr = Sym.getName();
537     Check(NameOrErr.getError());
538     StringRef Name = *NameOrErr;
539     if (Align) {
540       // This symbol has an alignment requirement.
541       uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
542       Addr += AlignOffset;
543       Offset += AlignOffset;
544     }
545     uint32_t Flags = Sym.getFlags();
546     JITSymbolFlags RTDyldSymFlags = JITSymbolFlags::None;
547     if (Flags & SymbolRef::SF_Weak)
548       RTDyldSymFlags |= JITSymbolFlags::Weak;
549     if (Flags & SymbolRef::SF_Exported)
550       RTDyldSymFlags |= JITSymbolFlags::Exported;
551     DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
552                  << format("%p", Addr) << "\n");
553     GlobalSymbolTable[Name] =
554       SymbolTableEntry(SectionID, Offset, RTDyldSymFlags);
555     Offset += Size;
556     Addr += Size;
557   }
558 
559   if (Checker)
560     Checker->registerSection(Obj.getFileName(), SectionID);
561 }
562 
563 unsigned RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
564                                       const SectionRef &Section, bool IsCode) {
565 
566   StringRef data;
567   uint64_t Alignment64 = Section.getAlignment();
568 
569   unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
570   unsigned PaddingSize = 0;
571   unsigned StubBufSize = 0;
572   StringRef Name;
573   bool IsRequired = isRequiredForExecution(Section);
574   bool IsVirtual = Section.isVirtual();
575   bool IsZeroInit = isZeroInit(Section);
576   bool IsReadOnly = isReadOnlyData(Section);
577   uint64_t DataSize = Section.getSize();
578   Check(Section.getName(Name));
579 
580   StubBufSize = computeSectionStubBufSize(Obj, Section);
581 
582   // The .eh_frame section (at least on Linux) needs an extra four bytes padded
583   // with zeroes added at the end.  For MachO objects, this section has a
584   // slightly different name, so this won't have any effect for MachO objects.
585   if (Name == ".eh_frame")
586     PaddingSize = 4;
587 
588   uintptr_t Allocate;
589   unsigned SectionID = Sections.size();
590   uint8_t *Addr;
591   const char *pData = nullptr;
592 
593   // If this section contains any bits (i.e. isn't a virtual or bss section),
594   // grab a reference to them.
595   if (!IsVirtual && !IsZeroInit) {
596     // In either case, set the location of the unrelocated section in memory,
597     // since we still process relocations for it even if we're not applying them.
598     Check(Section.getContents(data));
599     pData = data.data();
600   }
601 
602   // Code section alignment needs to be at least as high as stub alignment or
603   // padding calculations may by incorrect when the section is remapped to a
604   // higher alignment.
605   if (IsCode)
606     Alignment = std::max(Alignment, getStubAlignment());
607 
608   // Some sections, such as debug info, don't need to be loaded for execution.
609   // Leave those where they are.
610   if (IsRequired) {
611     Allocate = DataSize + PaddingSize + StubBufSize;
612     if (!Allocate)
613       Allocate = 1;
614     Addr = IsCode ? MemMgr.allocateCodeSection(Allocate, Alignment, SectionID,
615                                                Name)
616                   : MemMgr.allocateDataSection(Allocate, Alignment, SectionID,
617                                                Name, IsReadOnly);
618     if (!Addr)
619       report_fatal_error("Unable to allocate section memory!");
620 
621     // Zero-initialize or copy the data from the image
622     if (IsZeroInit || IsVirtual)
623       memset(Addr, 0, DataSize);
624     else
625       memcpy(Addr, pData, DataSize);
626 
627     // Fill in any extra bytes we allocated for padding
628     if (PaddingSize != 0) {
629       memset(Addr + DataSize, 0, PaddingSize);
630       // Update the DataSize variable so that the stub offset is set correctly.
631       DataSize += PaddingSize;
632     }
633 
634     DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
635                  << " obj addr: " << format("%p", pData)
636                  << " new addr: " << format("%p", Addr)
637                  << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
638                  << " Allocate: " << Allocate << "\n");
639   } else {
640     // Even if we didn't load the section, we need to record an entry for it
641     // to handle later processing (and by 'handle' I mean don't do anything
642     // with these sections).
643     Allocate = 0;
644     Addr = nullptr;
645     DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
646                  << " obj addr: " << format("%p", data.data()) << " new addr: 0"
647                  << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
648                  << " Allocate: " << Allocate << "\n");
649   }
650 
651   Sections.push_back(
652       SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));
653 
654   if (Checker)
655     Checker->registerSection(Obj.getFileName(), SectionID);
656 
657   return SectionID;
658 }
659 
660 unsigned RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
661                                             const SectionRef &Section,
662                                             bool IsCode,
663                                             ObjSectionToIDMap &LocalSections) {
664 
665   unsigned SectionID = 0;
666   ObjSectionToIDMap::iterator i = LocalSections.find(Section);
667   if (i != LocalSections.end())
668     SectionID = i->second;
669   else {
670     SectionID = emitSection(Obj, Section, IsCode);
671     LocalSections[Section] = SectionID;
672   }
673   return SectionID;
674 }
675 
676 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
677                                               unsigned SectionID) {
678   Relocations[SectionID].push_back(RE);
679 }
680 
681 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
682                                              StringRef SymbolName) {
683   // Relocation by symbol.  If the symbol is found in the global symbol table,
684   // create an appropriate section relocation.  Otherwise, add it to
685   // ExternalSymbolRelocations.
686   RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
687   if (Loc == GlobalSymbolTable.end()) {
688     ExternalSymbolRelocations[SymbolName].push_back(RE);
689   } else {
690     // Copy the RE since we want to modify its addend.
691     RelocationEntry RECopy = RE;
692     const auto &SymInfo = Loc->second;
693     RECopy.Addend += SymInfo.getOffset();
694     Relocations[SymInfo.getSectionID()].push_back(RECopy);
695   }
696 }
697 
698 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
699                                              unsigned AbiVariant) {
700   if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
701     // This stub has to be able to access the full address space,
702     // since symbol lookup won't necessarily find a handy, in-range,
703     // PLT stub for functions which could be anywhere.
704     // Stub can use ip0 (== x16) to calculate address
705     writeBytesUnaligned(0xd2e00010, Addr,    4); // movz ip0, #:abs_g3:<addr>
706     writeBytesUnaligned(0xf2c00010, Addr+4,  4); // movk ip0, #:abs_g2_nc:<addr>
707     writeBytesUnaligned(0xf2a00010, Addr+8,  4); // movk ip0, #:abs_g1_nc:<addr>
708     writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
709     writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
710 
711     return Addr;
712   } else if (Arch == Triple::arm || Arch == Triple::armeb) {
713     // TODO: There is only ARM far stub now. We should add the Thumb stub,
714     // and stubs for branches Thumb - ARM and ARM - Thumb.
715     writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc,<label>
716     return Addr + 4;
717   } else if (IsMipsO32ABI) {
718     // 0:   3c190000        lui     t9,%hi(addr).
719     // 4:   27390000        addiu   t9,t9,%lo(addr).
720     // 8:   03200008        jr      t9.
721     // c:   00000000        nop.
722     const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
723     const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
724 
725     writeBytesUnaligned(LuiT9Instr, Addr, 4);
726     writeBytesUnaligned(AdduiT9Instr, Addr+4, 4);
727     writeBytesUnaligned(JrT9Instr, Addr+8, 4);
728     writeBytesUnaligned(NopInstr, Addr+12, 4);
729     return Addr;
730   } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
731     // Depending on which version of the ELF ABI is in use, we need to
732     // generate one of two variants of the stub.  They both start with
733     // the same sequence to load the target address into r12.
734     writeInt32BE(Addr,    0x3D800000); // lis   r12, highest(addr)
735     writeInt32BE(Addr+4,  0x618C0000); // ori   r12, higher(addr)
736     writeInt32BE(Addr+8,  0x798C07C6); // sldi  r12, r12, 32
737     writeInt32BE(Addr+12, 0x658C0000); // oris  r12, r12, h(addr)
738     writeInt32BE(Addr+16, 0x618C0000); // ori   r12, r12, l(addr)
739     if (AbiVariant == 2) {
740       // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
741       // The address is already in r12 as required by the ABI.  Branch to it.
742       writeInt32BE(Addr+20, 0xF8410018); // std   r2,  24(r1)
743       writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
744       writeInt32BE(Addr+28, 0x4E800420); // bctr
745     } else {
746       // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
747       // Load the function address on r11 and sets it to control register. Also
748       // loads the function TOC in r2 and environment pointer to r11.
749       writeInt32BE(Addr+20, 0xF8410028); // std   r2,  40(r1)
750       writeInt32BE(Addr+24, 0xE96C0000); // ld    r11, 0(r12)
751       writeInt32BE(Addr+28, 0xE84C0008); // ld    r2,  0(r12)
752       writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
753       writeInt32BE(Addr+36, 0xE96C0010); // ld    r11, 16(r2)
754       writeInt32BE(Addr+40, 0x4E800420); // bctr
755     }
756     return Addr;
757   } else if (Arch == Triple::systemz) {
758     writeInt16BE(Addr,    0xC418);     // lgrl %r1,.+8
759     writeInt16BE(Addr+2,  0x0000);
760     writeInt16BE(Addr+4,  0x0004);
761     writeInt16BE(Addr+6,  0x07F1);     // brc 15,%r1
762     // 8-byte address stored at Addr + 8
763     return Addr;
764   } else if (Arch == Triple::x86_64) {
765     *Addr      = 0xFF; // jmp
766     *(Addr+1)  = 0x25; // rip
767     // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
768   } else if (Arch == Triple::x86) {
769     *Addr      = 0xE9; // 32-bit pc-relative jump.
770   }
771   return Addr;
772 }
773 
774 // Assign an address to a symbol name and resolve all the relocations
775 // associated with it.
776 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
777                                              uint64_t Addr) {
778   // The address to use for relocation resolution is not
779   // the address of the local section buffer. We must be doing
780   // a remote execution environment of some sort. Relocations can't
781   // be applied until all the sections have been moved.  The client must
782   // trigger this with a call to MCJIT::finalize() or
783   // RuntimeDyld::resolveRelocations().
784   //
785   // Addr is a uint64_t because we can't assume the pointer width
786   // of the target is the same as that of the host. Just use a generic
787   // "big enough" type.
788   DEBUG(dbgs() << "Reassigning address for section " << SectionID << " ("
789                << Sections[SectionID].getName() << "): "
790                << format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())
791                << " -> " << format("0x%016" PRIx64, Addr) << "\n");
792   Sections[SectionID].setLoadAddress(Addr);
793 }
794 
795 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
796                                             uint64_t Value) {
797   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
798     const RelocationEntry &RE = Relocs[i];
799     // Ignore relocations for sections that were not loaded
800     if (Sections[RE.SectionID].getAddress() == nullptr)
801       continue;
802     resolveRelocation(RE, Value);
803   }
804 }
805 
806 void RuntimeDyldImpl::resolveExternalSymbols() {
807   while (!ExternalSymbolRelocations.empty()) {
808     StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
809 
810     StringRef Name = i->first();
811     if (Name.size() == 0) {
812       // This is an absolute symbol, use an address of zero.
813       DEBUG(dbgs() << "Resolving absolute relocations."
814                    << "\n");
815       RelocationList &Relocs = i->second;
816       resolveRelocationList(Relocs, 0);
817     } else {
818       uint64_t Addr = 0;
819       RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
820       if (Loc == GlobalSymbolTable.end()) {
821         // This is an external symbol, try to get its address from the symbol
822         // resolver.
823         Addr = Resolver.findSymbol(Name.data()).getAddress();
824         // The call to getSymbolAddress may have caused additional modules to
825         // be loaded, which may have added new entries to the
826         // ExternalSymbolRelocations map.  Consquently, we need to update our
827         // iterator.  This is also why retrieval of the relocation list
828         // associated with this symbol is deferred until below this point.
829         // New entries may have been added to the relocation list.
830         i = ExternalSymbolRelocations.find(Name);
831       } else {
832         // We found the symbol in our global table.  It was probably in a
833         // Module that we loaded previously.
834         const auto &SymInfo = Loc->second;
835         Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
836                SymInfo.getOffset();
837       }
838 
839       // FIXME: Implement error handling that doesn't kill the host program!
840       if (!Addr)
841         report_fatal_error("Program used external function '" + Name +
842                            "' which could not be resolved!");
843 
844       // If Resolver returned UINT64_MAX, the client wants to handle this symbol
845       // manually and we shouldn't resolve its relocations.
846       if (Addr != UINT64_MAX) {
847         DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
848                      << format("0x%lx", Addr) << "\n");
849         // This list may have been updated when we called getSymbolAddress, so
850         // don't change this code to get the list earlier.
851         RelocationList &Relocs = i->second;
852         resolveRelocationList(Relocs, Addr);
853       }
854     }
855 
856     ExternalSymbolRelocations.erase(i);
857   }
858 }
859 
860 //===----------------------------------------------------------------------===//
861 // RuntimeDyld class implementation
862 
863 uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
864                                           const object::SectionRef &Sec) const {
865 
866   auto I = ObjSecToIDMap.find(Sec);
867   if (I != ObjSecToIDMap.end())
868     return RTDyld.Sections[I->second].getLoadAddress();
869 
870   return 0;
871 }
872 
873 void RuntimeDyld::MemoryManager::anchor() {}
874 void RuntimeDyld::SymbolResolver::anchor() {}
875 
876 RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
877                          RuntimeDyld::SymbolResolver &Resolver)
878     : MemMgr(MemMgr), Resolver(Resolver) {
879   // FIXME: There's a potential issue lurking here if a single instance of
880   // RuntimeDyld is used to load multiple objects.  The current implementation
881   // associates a single memory manager with a RuntimeDyld instance.  Even
882   // though the public class spawns a new 'impl' instance for each load,
883   // they share a single memory manager.  This can become a problem when page
884   // permissions are applied.
885   Dyld = nullptr;
886   ProcessAllSections = false;
887   Checker = nullptr;
888 }
889 
890 RuntimeDyld::~RuntimeDyld() {}
891 
892 static std::unique_ptr<RuntimeDyldCOFF>
893 createRuntimeDyldCOFF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
894                       RuntimeDyld::SymbolResolver &Resolver,
895                       bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
896   std::unique_ptr<RuntimeDyldCOFF> Dyld =
897     RuntimeDyldCOFF::create(Arch, MM, Resolver);
898   Dyld->setProcessAllSections(ProcessAllSections);
899   Dyld->setRuntimeDyldChecker(Checker);
900   return Dyld;
901 }
902 
903 static std::unique_ptr<RuntimeDyldELF>
904 createRuntimeDyldELF(RuntimeDyld::MemoryManager &MM,
905                      RuntimeDyld::SymbolResolver &Resolver,
906                      bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
907   std::unique_ptr<RuntimeDyldELF> Dyld(new RuntimeDyldELF(MM, Resolver));
908   Dyld->setProcessAllSections(ProcessAllSections);
909   Dyld->setRuntimeDyldChecker(Checker);
910   return Dyld;
911 }
912 
913 static std::unique_ptr<RuntimeDyldMachO>
914 createRuntimeDyldMachO(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
915                        RuntimeDyld::SymbolResolver &Resolver,
916                        bool ProcessAllSections,
917                        RuntimeDyldCheckerImpl *Checker) {
918   std::unique_ptr<RuntimeDyldMachO> Dyld =
919     RuntimeDyldMachO::create(Arch, MM, Resolver);
920   Dyld->setProcessAllSections(ProcessAllSections);
921   Dyld->setRuntimeDyldChecker(Checker);
922   return Dyld;
923 }
924 
925 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
926 RuntimeDyld::loadObject(const ObjectFile &Obj) {
927   if (!Dyld) {
928     if (Obj.isELF())
929       Dyld = createRuntimeDyldELF(MemMgr, Resolver, ProcessAllSections, Checker);
930     else if (Obj.isMachO())
931       Dyld = createRuntimeDyldMachO(
932                static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
933                ProcessAllSections, Checker);
934     else if (Obj.isCOFF())
935       Dyld = createRuntimeDyldCOFF(
936                static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
937                ProcessAllSections, Checker);
938     else
939       report_fatal_error("Incompatible object format!");
940   }
941 
942   if (!Dyld->isCompatibleFile(Obj))
943     report_fatal_error("Incompatible object format!");
944 
945   auto LoadedObjInfo = Dyld->loadObject(Obj);
946   MemMgr.notifyObjectLoaded(*this, Obj);
947   return LoadedObjInfo;
948 }
949 
950 void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
951   if (!Dyld)
952     return nullptr;
953   return Dyld->getSymbolLocalAddress(Name);
954 }
955 
956 RuntimeDyld::SymbolInfo RuntimeDyld::getSymbol(StringRef Name) const {
957   if (!Dyld)
958     return nullptr;
959   return Dyld->getSymbol(Name);
960 }
961 
962 void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
963 
964 void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
965   Dyld->reassignSectionAddress(SectionID, Addr);
966 }
967 
968 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
969                                     uint64_t TargetAddress) {
970   Dyld->mapSectionAddress(LocalAddress, TargetAddress);
971 }
972 
973 bool RuntimeDyld::hasError() { return Dyld->hasError(); }
974 
975 StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
976 
977 void RuntimeDyld::finalizeWithMemoryManagerLocking() {
978   bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;
979   MemMgr.FinalizationLocked = true;
980   resolveRelocations();
981   registerEHFrames();
982   if (!MemoryFinalizationLocked) {
983     MemMgr.finalizeMemory();
984     MemMgr.FinalizationLocked = false;
985   }
986 }
987 
988 void RuntimeDyld::registerEHFrames() {
989   if (Dyld)
990     Dyld->registerEHFrames();
991 }
992 
993 void RuntimeDyld::deregisterEHFrames() {
994   if (Dyld)
995     Dyld->deregisterEHFrames();
996 }
997 
998 } // end namespace llvm
999