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