1 //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation of the MC-JIT runtime dynamic linker.
12 //===----------------------------------------------------------------------===//
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"
26 using namespace llvm::object;
28 #define DEBUG_TYPE "dyld"
30 // Empty out-of-line virtual destructor as the key function.
31 RuntimeDyldImpl::~RuntimeDyldImpl() {}
33 // Pin LoadedObjectInfo's vtables to this file.
34 void RuntimeDyld::LoadedObjectInfo::anchor() {}
38 void RuntimeDyldImpl::registerEHFrames() {}
40 void RuntimeDyldImpl::deregisterEHFrames() {}
43 static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
44 dbgs() << "----- Contents of section " << S.Name << " " << State << " -----";
46 if (S.Address == nullptr) {
47 dbgs() << "\n <section not emitted>\n";
51 const unsigned ColsPerRow = 16;
53 uint8_t *DataAddr = S.Address;
54 uint64_t LoadAddr = S.LoadAddress;
56 unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
57 unsigned BytesRemaining = S.Size;
60 dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr & ~(ColsPerRow - 1)) << ":";
61 while (StartPadding--)
65 while (BytesRemaining > 0) {
66 if ((LoadAddr & (ColsPerRow - 1)) == 0)
67 dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
69 dbgs() << " " << format("%02x", *DataAddr);
80 // Resolve the relocations for all symbols we currently know about.
81 void RuntimeDyldImpl::resolveRelocations() {
82 MutexGuard locked(lock);
84 // First, resolve relocations associated with external symbols.
85 resolveExternalSymbols();
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"));
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);
112 llvm_unreachable("Attempting to remap address of unknown section!");
115 static std::error_code getOffset(const SymbolRef &Sym, uint64_t &Result) {
117 if (std::error_code EC = Sym.getAddress(Address))
120 if (Address == UnknownAddressOrSize) {
121 Result = UnknownAddressOrSize;
122 return object_error::success;
125 const ObjectFile *Obj = Sym.getObject();
126 section_iterator SecI(Obj->section_begin());
127 if (std::error_code EC = Sym.getSection(SecI))
130 if (SecI == Obj->section_end()) {
131 Result = UnknownAddressOrSize;
132 return object_error::success;
135 uint64_t SectionAddress = SecI->getAddress();
136 Result = Address - SectionAddress;
137 return object_error::success;
140 std::pair<unsigned, unsigned>
141 RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
142 MutexGuard locked(lock);
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();
148 // Save information about our target
149 Arch = (Triple::ArchType)Obj.getArch();
150 IsTargetLittleEndian = Obj.isLittleEndian();
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);
160 // Used sections from the object file
161 ObjSectionToIDMap LocalSections;
163 // Common symbols requiring allocation, with their sizes and alignments
164 CommonSymbolList CommonSymbols;
167 DEBUG(dbgs() << "Parse symbols:\n");
168 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
170 uint32_t Flags = I->getFlags();
172 bool IsCommon = Flags & SymbolRef::SF_Common;
174 CommonSymbols.push_back(*I);
176 object::SymbolRef::Type SymType;
177 Check(I->getType(SymType));
179 if (SymType == object::SymbolRef::ST_Function ||
180 SymType == object::SymbolRef::ST_Data ||
181 SymType == object::SymbolRef::ST_Unknown) {
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())
191 StringRef SectionData;
192 Check(SI->getContents(SectionData));
193 bool IsCode = SI->isText();
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);
208 // Allocate common symbols
209 emitCommonSymbols(Obj, CommonSymbols);
211 // Parse and process relocations
212 DEBUG(dbgs() << "Parse relocations:\n");
213 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
215 unsigned SectionID = 0;
217 section_iterator RelocatedSection = SI->getRelocatedSection();
219 if (RelocatedSection == SE)
222 relocation_iterator I = SI->relocation_begin();
223 relocation_iterator E = SI->relocation_end();
225 if (I == E && !ProcessAllSections)
228 bool IsCode = RelocatedSection->isText();
230 findOrEmitSection(Obj, *RelocatedSection, IsCode, LocalSections);
231 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
234 I = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs);
236 // If there is an attached checker, notify it about the stubs for this
237 // section so that they can be verified.
239 Checker->registerStubMap(Obj.getFileName(), SectionID, Stubs);
242 // Give the subclasses a chance to tie-up any loose ends.
243 finalizeLoad(Obj, LocalSections);
245 unsigned SectionsAddedEndIdx = Sections.size();
247 return std::make_pair(SectionsAddedBeginIdx, SectionsAddedEndIdx);
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
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;
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;
283 assert(isa<MachOObjectFile>(Obj));
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))
298 (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
299 | COFF::IMAGE_SCN_MEM_READ));
301 assert(isa<MachOObjectFile>(Obj));
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;
313 auto *MachO = cast<MachOObjectFile>(Obj);
314 unsigned SectionType = MachO->getSectionType(Section);
315 return SectionType == MachO::S_ZEROFILL ||
316 SectionType == MachO::S_GB_ZEROFILL;
319 // Compute an upper bound of the memory size that is required to load all
321 void RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
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 *);
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();
335 const SectionRef &Section = *SI;
337 bool IsRequired = isRequiredForExecution(Section);
339 // Consider only the sections that are required to be loaded for execution
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;
349 uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
350 uint64_t SectionSize = DataSize + StubBufSize;
352 // The .eh_frame section (at least on Linux) needs an extra four bytes
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
357 if (Name == ".eh_frame")
360 if (SectionSize > 0) {
361 // save the total size of the section
363 CodeSectionSizes.push_back(SectionSize);
364 } else if (IsReadOnly) {
365 ROSectionSizes.push_back(SectionSize);
367 RWSectionSizes.push_back(SectionSize);
369 // update the max alignment
370 if (Alignment > MaxAlignment) {
371 MaxAlignment = Alignment;
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;
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.
385 Check(I->getSize(Size));
389 if (CommonSize != 0) {
390 RWSectionSizes.push_back(CommonSize);
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);
403 // compute stub buffer size for the given section
404 unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
405 const SectionRef &Section) {
406 unsigned StubSize = getMaxStubSize();
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
413 unsigned StubBufSize = 0;
414 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
416 section_iterator RelSecI = SI->getRelocatedSection();
417 if (!(RelSecI == Section))
420 for (const RelocationRef &Reloc : SI->relocations()) {
422 StubBufSize += StubSize;
426 // Get section data size and alignment
427 uint64_t DataSize = Section.getSize();
428 uint64_t Alignment64 = Section.getAlignment();
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;
439 uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
440 unsigned Size) const {
442 if (IsTargetLittleEndian) {
445 Result = (Result << 8) | *Src--;
448 Result = (Result << 8) | *Src++;
453 void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
454 unsigned Size) const {
455 if (IsTargetLittleEndian) {
457 *Dst++ = Value & 0xFF;
463 *Dst-- = Value & 0xFF;
469 void RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
470 CommonSymbolList &CommonSymbols) {
471 if (CommonSymbols.empty())
474 uint64_t CommonSize = 0;
475 CommonSymbolList SymbolsToAllocate;
477 DEBUG(dbgs() << "Processing common symbols...\n");
479 for (const auto &Sym : CommonSymbols) {
481 Check(Sym.getName(Name));
483 // Skip common symbols already elsewhere.
484 if (GlobalSymbolTable.count(Name) ||
485 MemMgr->getSymbolAddressInLogicalDylib(Name)) {
486 DEBUG(dbgs() << "\tSkipping already emitted common symbol '" << Name
493 Check(Sym.getAlignment(Align));
494 Check(Sym.getSize(Size));
496 CommonSize += Align + Size;
497 SymbolsToAllocate.push_back(Sym);
500 // Allocate memory for the section
501 unsigned SectionID = Sections.size();
502 uint8_t *Addr = MemMgr->allocateDataSection(CommonSize, sizeof(void *),
503 SectionID, StringRef(), false);
505 report_fatal_error("Unable to allocate memory for common symbols!");
507 Sections.push_back(SectionEntry("<common symbols>", Addr, CommonSize, 0));
508 memset(Addr, 0, CommonSize);
510 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID << " new addr: "
511 << format("%p", Addr) << " DataSize: " << CommonSize << "\n");
513 // Assign the address of each symbol
514 for (auto &Sym : SymbolsToAllocate) {
518 Check(Sym.getAlignment(Align));
519 Check(Sym.getSize(Size));
520 Check(Sym.getName(Name));
522 // This symbol has an alignment requirement.
523 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
525 Offset += AlignOffset;
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);
539 unsigned RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
540 const SectionRef &Section, bool IsCode) {
543 uint64_t Alignment64 = Section.getAlignment();
545 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
546 unsigned PaddingSize = 0;
547 unsigned StubBufSize = 0;
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));
556 StubBufSize = computeSectionStubBufSize(Obj, Section);
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")
565 unsigned SectionID = Sections.size();
567 const char *pData = nullptr;
569 // Some sections, such as debug info, don't need to be loaded for execution.
570 // Leave those where they are.
572 Check(Section.getContents(data));
573 Allocate = DataSize + PaddingSize + StubBufSize;
574 Addr = IsCode ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID,
576 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID,
579 report_fatal_error("Unable to allocate section memory!");
581 // Virtual sections have no data in the object image, so leave pData = 0
585 // Zero-initialize or copy the data from the image
586 if (IsZeroInit || IsVirtual)
587 memset(Addr, 0, DataSize);
589 memcpy(Addr, pData, DataSize);
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;
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");
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).
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");
615 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
618 Checker->registerSection(Obj.getFileName(), SectionID);
623 unsigned RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
624 const SectionRef &Section,
626 ObjSectionToIDMap &LocalSections) {
628 unsigned SectionID = 0;
629 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
630 if (i != LocalSections.end())
631 SectionID = i->second;
633 SectionID = emitSection(Obj, Section, IsCode);
634 LocalSections[Section] = SectionID;
639 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
640 unsigned SectionID) {
641 Relocations[SectionID].push_back(RE);
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);
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);
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
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>
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.
685 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
686 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
688 writeBytesUnaligned(LuiT9Instr, Addr, 4);
689 writeBytesUnaligned(AdduiT9Instr, Addr+4, 4);
690 writeBytesUnaligned(JrT9Instr, Addr+8, 4);
691 writeBytesUnaligned(NopInstr, Addr+12, 4);
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
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
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
727 } else if (Arch == Triple::x86_64) {
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.
737 // Assign an address to a symbol name and resolve all the relocations
738 // associated with it.
739 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
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().
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;
758 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
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)
765 resolveRelocation(RE, Value);
769 void RuntimeDyldImpl::resolveExternalSymbols() {
770 while (!ExternalSymbolRelocations.empty()) {
771 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
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."
778 RelocationList &Relocs = i->second;
779 resolveRelocationList(Relocs, 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
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);
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()) +
802 // FIXME: Implement error handling that doesn't kill the host program!
804 report_fatal_error("Program used external function '" + Name +
805 "' which could not be resolved!");
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);
816 ExternalSymbolRelocations.erase(i);
820 //===----------------------------------------------------------------------===//
821 // RuntimeDyld class implementation
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;
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.
841 ProcessAllSections = false;
845 RuntimeDyld::~RuntimeDyld() {}
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);
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);
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);
874 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
875 RuntimeDyld::loadObject(const ObjectFile &Obj) {
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);
888 report_fatal_error("Incompatible object format!");
891 if (!Dyld->isCompatibleFile(Obj))
892 report_fatal_error("Incompatible object format!");
894 return Dyld->loadObject(Obj);
897 void *RuntimeDyld::getSymbolAddress(StringRef Name) const {
900 return Dyld->getSymbolAddress(Name);
903 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) const {
906 return Dyld->getSymbolLoadAddress(Name);
909 uint64_t RuntimeDyld::getExportedSymbolLoadAddress(StringRef Name) const {
912 return Dyld->getExportedSymbolLoadAddress(Name);
915 void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
917 void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
918 Dyld->reassignSectionAddress(SectionID, Addr);
921 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
922 uint64_t TargetAddress) {
923 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
926 bool RuntimeDyld::hasError() { return Dyld->hasError(); }
928 StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
930 void RuntimeDyld::registerEHFrames() {
932 Dyld->registerEHFrames();
935 void RuntimeDyld::deregisterEHFrames() {
937 Dyld->deregisterEHFrames();
940 } // end namespace llvm