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