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