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