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 JITSymbolFlags RTDyldSymFlags = JITSymbolFlags::None;
201 if (Flags & SymbolRef::SF_Weak)
202 RTDyldSymFlags |= JITSymbolFlags::Weak;
203 if (Flags & SymbolRef::SF_Exported)
204 RTDyldSymFlags |= JITSymbolFlags::Exported;
205 GlobalSymbolTable[Name] =
206 SymbolTableEntry(SectionID, SectOffset, RTDyldSymFlags);
211 // Allocate common symbols
212 emitCommonSymbols(Obj, CommonSymbols);
214 // Parse and process relocations
215 DEBUG(dbgs() << "Parse relocations:\n");
216 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
218 unsigned SectionID = 0;
220 section_iterator RelocatedSection = SI->getRelocatedSection();
222 if (RelocatedSection == SE)
225 relocation_iterator I = SI->relocation_begin();
226 relocation_iterator E = SI->relocation_end();
228 if (I == E && !ProcessAllSections)
231 bool IsCode = RelocatedSection->isText();
233 findOrEmitSection(Obj, *RelocatedSection, IsCode, LocalSections);
234 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
237 I = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs);
239 // If there is an attached checker, notify it about the stubs for this
240 // section so that they can be verified.
242 Checker->registerStubMap(Obj.getFileName(), SectionID, Stubs);
245 // Give the subclasses a chance to tie-up any loose ends.
246 finalizeLoad(Obj, LocalSections);
248 unsigned SectionsAddedEndIdx = Sections.size();
250 return std::make_pair(SectionsAddedBeginIdx, SectionsAddedEndIdx);
253 // A helper method for computeTotalAllocSize.
254 // Computes the memory size required to allocate sections with the given sizes,
255 // assuming that all sections are allocated with the given alignment
257 computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
258 uint64_t Alignment) {
259 uint64_t TotalSize = 0;
260 for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
261 uint64_t AlignedSize =
262 (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
263 TotalSize += AlignedSize;
268 static bool isRequiredForExecution(const SectionRef &Section) {
269 const ObjectFile *Obj = Section.getObject();
270 if (auto *ELFObj = dyn_cast<object::ELFObjectFileBase>(Obj))
271 return ELFObj->getSectionFlags(Section) & ELF::SHF_ALLOC;
272 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
273 const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
274 // Avoid loading zero-sized COFF sections.
275 // In PE files, VirtualSize gives the section size, and SizeOfRawData
276 // may be zero for sections with content. In Obj files, SizeOfRawData
277 // gives the section size, and VirtualSize is always zero. Hence
278 // the need to check for both cases below.
279 bool HasContent = (CoffSection->VirtualSize > 0)
280 || (CoffSection->SizeOfRawData > 0);
281 bool IsDiscardable = CoffSection->Characteristics &
282 (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
283 return HasContent && !IsDiscardable;
286 assert(isa<MachOObjectFile>(Obj));
290 static bool isReadOnlyData(const SectionRef &Section) {
291 const ObjectFile *Obj = Section.getObject();
292 if (auto *ELFObj = dyn_cast<object::ELFObjectFileBase>(Obj))
293 return !(ELFObj->getSectionFlags(Section) &
294 (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
295 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
296 return ((COFFObj->getCOFFSection(Section)->Characteristics &
297 (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
298 | COFF::IMAGE_SCN_MEM_READ
299 | COFF::IMAGE_SCN_MEM_WRITE))
301 (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
302 | COFF::IMAGE_SCN_MEM_READ));
304 assert(isa<MachOObjectFile>(Obj));
308 static bool isZeroInit(const SectionRef &Section) {
309 const ObjectFile *Obj = Section.getObject();
310 if (auto *ELFObj = dyn_cast<object::ELFObjectFileBase>(Obj))
311 return ELFObj->getSectionType(Section) == ELF::SHT_NOBITS;
312 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
313 return COFFObj->getCOFFSection(Section)->Characteristics &
314 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
316 auto *MachO = cast<MachOObjectFile>(Obj);
317 unsigned SectionType = MachO->getSectionType(Section);
318 return SectionType == MachO::S_ZEROFILL ||
319 SectionType == MachO::S_GB_ZEROFILL;
322 // Compute an upper bound of the memory size that is required to load all
324 void RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
326 uint64_t &DataSizeRO,
327 uint64_t &DataSizeRW) {
328 // Compute the size of all sections required for execution
329 std::vector<uint64_t> CodeSectionSizes;
330 std::vector<uint64_t> ROSectionSizes;
331 std::vector<uint64_t> RWSectionSizes;
332 uint64_t MaxAlignment = sizeof(void *);
334 // Collect sizes of all sections to be loaded;
335 // also determine the max alignment of all sections
336 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
338 const SectionRef &Section = *SI;
340 bool IsRequired = isRequiredForExecution(Section);
342 // Consider only the sections that are required to be loaded for execution
345 uint64_t DataSize = Section.getSize();
346 uint64_t Alignment64 = Section.getAlignment();
347 bool IsCode = Section.isText();
348 bool IsReadOnly = isReadOnlyData(Section);
349 Check(Section.getName(Name));
350 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
352 uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
353 uint64_t SectionSize = DataSize + StubBufSize;
355 // The .eh_frame section (at least on Linux) needs an extra four bytes
357 // with zeroes added at the end. For MachO objects, this section has a
358 // slightly different name, so this won't have any effect for MachO
360 if (Name == ".eh_frame")
363 if (SectionSize > 0) {
364 // save the total size of the section
366 CodeSectionSizes.push_back(SectionSize);
367 } else if (IsReadOnly) {
368 ROSectionSizes.push_back(SectionSize);
370 RWSectionSizes.push_back(SectionSize);
372 // update the max alignment
373 if (Alignment > MaxAlignment) {
374 MaxAlignment = Alignment;
380 // Compute the size of all common symbols
381 uint64_t CommonSize = 0;
382 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
384 uint32_t Flags = I->getFlags();
385 if (Flags & SymbolRef::SF_Common) {
386 // Add the common symbols to a list. We'll allocate them all below.
388 Check(I->getSize(Size));
392 if (CommonSize != 0) {
393 RWSectionSizes.push_back(CommonSize);
396 // Compute the required allocation space for each different type of sections
397 // (code, read-only data, read-write data) assuming that all sections are
398 // allocated with the max alignment. Note that we cannot compute with the
399 // individual alignments of the sections, because then the required size
400 // depends on the order, in which the sections are allocated.
401 CodeSize = computeAllocationSizeForSections(CodeSectionSizes, MaxAlignment);
402 DataSizeRO = computeAllocationSizeForSections(ROSectionSizes, MaxAlignment);
403 DataSizeRW = computeAllocationSizeForSections(RWSectionSizes, MaxAlignment);
406 // compute stub buffer size for the given section
407 unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
408 const SectionRef &Section) {
409 unsigned StubSize = getMaxStubSize();
413 // FIXME: this is an inefficient way to handle this. We should computed the
414 // necessary section allocation size in loadObject by walking all the sections
416 unsigned StubBufSize = 0;
417 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
419 section_iterator RelSecI = SI->getRelocatedSection();
420 if (!(RelSecI == Section))
423 for (const RelocationRef &Reloc : SI->relocations()) {
425 StubBufSize += StubSize;
429 // Get section data size and alignment
430 uint64_t DataSize = Section.getSize();
431 uint64_t Alignment64 = Section.getAlignment();
433 // Add stubbuf size alignment
434 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
435 unsigned StubAlignment = getStubAlignment();
436 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
437 if (StubAlignment > EndAlignment)
438 StubBufSize += StubAlignment - EndAlignment;
442 uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
443 unsigned Size) const {
445 if (IsTargetLittleEndian) {
448 Result = (Result << 8) | *Src--;
451 Result = (Result << 8) | *Src++;
456 void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
457 unsigned Size) const {
458 if (IsTargetLittleEndian) {
460 *Dst++ = Value & 0xFF;
466 *Dst-- = Value & 0xFF;
472 void RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
473 CommonSymbolList &CommonSymbols) {
474 if (CommonSymbols.empty())
477 uint64_t CommonSize = 0;
478 CommonSymbolList SymbolsToAllocate;
480 DEBUG(dbgs() << "Processing common symbols...\n");
482 for (const auto &Sym : CommonSymbols) {
484 Check(Sym.getName(Name));
486 // Skip common symbols already elsewhere.
487 if (GlobalSymbolTable.count(Name) ||
488 Resolver.findSymbolInLogicalDylib(Name)) {
489 DEBUG(dbgs() << "\tSkipping already emitted common symbol '" << Name
496 Check(Sym.getAlignment(Align));
497 Check(Sym.getSize(Size));
499 CommonSize += Align + Size;
500 SymbolsToAllocate.push_back(Sym);
503 // Allocate memory for the section
504 unsigned SectionID = Sections.size();
505 uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, sizeof(void *),
506 SectionID, StringRef(), false);
508 report_fatal_error("Unable to allocate memory for common symbols!");
510 Sections.push_back(SectionEntry("<common symbols>", Addr, CommonSize, 0));
511 memset(Addr, 0, CommonSize);
513 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID << " new addr: "
514 << format("%p", Addr) << " DataSize: " << CommonSize << "\n");
516 // Assign the address of each symbol
517 for (auto &Sym : SymbolsToAllocate) {
521 Check(Sym.getAlignment(Align));
522 Check(Sym.getSize(Size));
523 Check(Sym.getName(Name));
525 // This symbol has an alignment requirement.
526 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
528 Offset += AlignOffset;
530 uint32_t Flags = Sym.getFlags();
531 JITSymbolFlags RTDyldSymFlags = JITSymbolFlags::None;
532 if (Flags & SymbolRef::SF_Weak)
533 RTDyldSymFlags |= JITSymbolFlags::Weak;
534 if (Flags & SymbolRef::SF_Exported)
535 RTDyldSymFlags |= JITSymbolFlags::Exported;
536 DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
537 << format("%p", Addr) << "\n");
538 GlobalSymbolTable[Name] =
539 SymbolTableEntry(SectionID, Offset, RTDyldSymFlags);
545 unsigned RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
546 const SectionRef &Section, bool IsCode) {
549 uint64_t Alignment64 = Section.getAlignment();
551 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
552 unsigned PaddingSize = 0;
553 unsigned StubBufSize = 0;
555 bool IsRequired = isRequiredForExecution(Section);
556 bool IsVirtual = Section.isVirtual();
557 bool IsZeroInit = isZeroInit(Section);
558 bool IsReadOnly = isReadOnlyData(Section);
559 uint64_t DataSize = Section.getSize();
560 Check(Section.getName(Name));
562 StubBufSize = computeSectionStubBufSize(Obj, Section);
564 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
565 // with zeroes added at the end. For MachO objects, this section has a
566 // slightly different name, so this won't have any effect for MachO objects.
567 if (Name == ".eh_frame")
571 unsigned SectionID = Sections.size();
573 const char *pData = nullptr;
575 // Some sections, such as debug info, don't need to be loaded for execution.
576 // Leave those where they are.
578 Check(Section.getContents(data));
579 Allocate = DataSize + PaddingSize + StubBufSize;
580 Addr = IsCode ? MemMgr.allocateCodeSection(Allocate, Alignment, SectionID,
582 : MemMgr.allocateDataSection(Allocate, Alignment, SectionID,
585 report_fatal_error("Unable to allocate section memory!");
587 // Virtual sections have no data in the object image, so leave pData = 0
591 // Zero-initialize or copy the data from the image
592 if (IsZeroInit || IsVirtual)
593 memset(Addr, 0, DataSize);
595 memcpy(Addr, pData, DataSize);
597 // Fill in any extra bytes we allocated for padding
598 if (PaddingSize != 0) {
599 memset(Addr + DataSize, 0, PaddingSize);
600 // Update the DataSize variable so that the stub offset is set correctly.
601 DataSize += PaddingSize;
604 DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
605 << " obj addr: " << format("%p", pData)
606 << " new addr: " << format("%p", Addr)
607 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
608 << " Allocate: " << Allocate << "\n");
610 // Even if we didn't load the section, we need to record an entry for it
611 // to handle later processing (and by 'handle' I mean don't do anything
612 // with these sections).
615 DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
616 << " obj addr: " << format("%p", data.data()) << " new addr: 0"
617 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
618 << " Allocate: " << Allocate << "\n");
621 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
624 Checker->registerSection(Obj.getFileName(), SectionID);
629 unsigned RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
630 const SectionRef &Section,
632 ObjSectionToIDMap &LocalSections) {
634 unsigned SectionID = 0;
635 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
636 if (i != LocalSections.end())
637 SectionID = i->second;
639 SectionID = emitSection(Obj, Section, IsCode);
640 LocalSections[Section] = SectionID;
645 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
646 unsigned SectionID) {
647 Relocations[SectionID].push_back(RE);
650 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
651 StringRef SymbolName) {
652 // Relocation by symbol. If the symbol is found in the global symbol table,
653 // create an appropriate section relocation. Otherwise, add it to
654 // ExternalSymbolRelocations.
655 RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
656 if (Loc == GlobalSymbolTable.end()) {
657 ExternalSymbolRelocations[SymbolName].push_back(RE);
659 // Copy the RE since we want to modify its addend.
660 RelocationEntry RECopy = RE;
661 const auto &SymInfo = Loc->second;
662 RECopy.Addend += SymInfo.getOffset();
663 Relocations[SymInfo.getSectionID()].push_back(RECopy);
667 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
668 unsigned AbiVariant) {
669 if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
670 // This stub has to be able to access the full address space,
671 // since symbol lookup won't necessarily find a handy, in-range,
672 // PLT stub for functions which could be anywhere.
673 // Stub can use ip0 (== x16) to calculate address
674 writeBytesUnaligned(0xd2e00010, Addr, 4); // movz ip0, #:abs_g3:<addr>
675 writeBytesUnaligned(0xf2c00010, Addr+4, 4); // movk ip0, #:abs_g2_nc:<addr>
676 writeBytesUnaligned(0xf2a00010, Addr+8, 4); // movk ip0, #:abs_g1_nc:<addr>
677 writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
678 writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
681 } else if (Arch == Triple::arm || Arch == Triple::armeb) {
682 // TODO: There is only ARM far stub now. We should add the Thumb stub,
683 // and stubs for branches Thumb - ARM and ARM - Thumb.
684 writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc,<label>
686 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
687 // 0: 3c190000 lui t9,%hi(addr).
688 // 4: 27390000 addiu t9,t9,%lo(addr).
689 // 8: 03200008 jr t9.
691 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
692 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
694 writeBytesUnaligned(LuiT9Instr, Addr, 4);
695 writeBytesUnaligned(AdduiT9Instr, Addr+4, 4);
696 writeBytesUnaligned(JrT9Instr, Addr+8, 4);
697 writeBytesUnaligned(NopInstr, Addr+12, 4);
699 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
700 // Depending on which version of the ELF ABI is in use, we need to
701 // generate one of two variants of the stub. They both start with
702 // the same sequence to load the target address into r12.
703 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
704 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
705 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
706 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
707 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
708 if (AbiVariant == 2) {
709 // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
710 // The address is already in r12 as required by the ABI. Branch to it.
711 writeInt32BE(Addr+20, 0xF8410018); // std r2, 24(r1)
712 writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
713 writeInt32BE(Addr+28, 0x4E800420); // bctr
715 // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
716 // Load the function address on r11 and sets it to control register. Also
717 // loads the function TOC in r2 and environment pointer to r11.
718 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
719 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
720 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
721 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
722 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
723 writeInt32BE(Addr+40, 0x4E800420); // bctr
726 } else if (Arch == Triple::systemz) {
727 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
728 writeInt16BE(Addr+2, 0x0000);
729 writeInt16BE(Addr+4, 0x0004);
730 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
731 // 8-byte address stored at Addr + 8
733 } else if (Arch == Triple::x86_64) {
735 *(Addr+1) = 0x25; // rip
736 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
737 } else if (Arch == Triple::x86) {
738 *Addr = 0xE9; // 32-bit pc-relative jump.
743 // Assign an address to a symbol name and resolve all the relocations
744 // associated with it.
745 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
747 // The address to use for relocation resolution is not
748 // the address of the local section buffer. We must be doing
749 // a remote execution environment of some sort. Relocations can't
750 // be applied until all the sections have been moved. The client must
751 // trigger this with a call to MCJIT::finalize() or
752 // RuntimeDyld::resolveRelocations().
754 // Addr is a uint64_t because we can't assume the pointer width
755 // of the target is the same as that of the host. Just use a generic
756 // "big enough" type.
757 DEBUG(dbgs() << "Reassigning address for section "
758 << SectionID << " (" << Sections[SectionID].Name << "): "
759 << format("0x%016" PRIx64, Sections[SectionID].LoadAddress) << " -> "
760 << format("0x%016" PRIx64, Addr) << "\n");
761 Sections[SectionID].LoadAddress = Addr;
764 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
766 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
767 const RelocationEntry &RE = Relocs[i];
768 // Ignore relocations for sections that were not loaded
769 if (Sections[RE.SectionID].Address == nullptr)
771 resolveRelocation(RE, Value);
775 void RuntimeDyldImpl::resolveExternalSymbols() {
776 while (!ExternalSymbolRelocations.empty()) {
777 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
779 StringRef Name = i->first();
780 if (Name.size() == 0) {
781 // This is an absolute symbol, use an address of zero.
782 DEBUG(dbgs() << "Resolving absolute relocations."
784 RelocationList &Relocs = i->second;
785 resolveRelocationList(Relocs, 0);
788 RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
789 if (Loc == GlobalSymbolTable.end()) {
790 // This is an external symbol, try to get its address from the symbol
792 Addr = Resolver.findSymbol(Name.data()).getAddress();
793 // The call to getSymbolAddress may have caused additional modules to
794 // be loaded, which may have added new entries to the
795 // ExternalSymbolRelocations map. Consquently, we need to update our
796 // iterator. This is also why retrieval of the relocation list
797 // associated with this symbol is deferred until below this point.
798 // New entries may have been added to the relocation list.
799 i = ExternalSymbolRelocations.find(Name);
801 // We found the symbol in our global table. It was probably in a
802 // Module that we loaded previously.
803 const auto &SymInfo = Loc->second;
804 Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
808 // FIXME: Implement error handling that doesn't kill the host program!
810 report_fatal_error("Program used external function '" + Name +
811 "' which could not be resolved!");
813 updateGOTEntries(Name, Addr);
814 DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
815 << format("0x%lx", Addr) << "\n");
816 // This list may have been updated when we called getSymbolAddress, so
817 // don't change this code to get the list earlier.
818 RelocationList &Relocs = i->second;
819 resolveRelocationList(Relocs, Addr);
822 ExternalSymbolRelocations.erase(i);
826 //===----------------------------------------------------------------------===//
827 // RuntimeDyld class implementation
829 uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
830 StringRef SectionName) const {
831 for (unsigned I = BeginIdx; I != EndIdx; ++I)
832 if (RTDyld.Sections[I].Name == SectionName)
833 return RTDyld.Sections[I].LoadAddress;
838 void RuntimeDyld::MemoryManager::anchor() {}
839 void RuntimeDyld::SymbolResolver::anchor() {}
841 RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
842 RuntimeDyld::SymbolResolver &Resolver)
843 : MemMgr(MemMgr), Resolver(Resolver) {
844 // FIXME: There's a potential issue lurking here if a single instance of
845 // RuntimeDyld is used to load multiple objects. The current implementation
846 // associates a single memory manager with a RuntimeDyld instance. Even
847 // though the public class spawns a new 'impl' instance for each load,
848 // they share a single memory manager. This can become a problem when page
849 // permissions are applied.
851 ProcessAllSections = false;
855 RuntimeDyld::~RuntimeDyld() {}
857 static std::unique_ptr<RuntimeDyldCOFF>
858 createRuntimeDyldCOFF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
859 RuntimeDyld::SymbolResolver &Resolver,
860 bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
861 std::unique_ptr<RuntimeDyldCOFF> Dyld =
862 RuntimeDyldCOFF::create(Arch, MM, Resolver);
863 Dyld->setProcessAllSections(ProcessAllSections);
864 Dyld->setRuntimeDyldChecker(Checker);
868 static std::unique_ptr<RuntimeDyldELF>
869 createRuntimeDyldELF(RuntimeDyld::MemoryManager &MM,
870 RuntimeDyld::SymbolResolver &Resolver,
871 bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
872 std::unique_ptr<RuntimeDyldELF> Dyld(new RuntimeDyldELF(MM, Resolver));
873 Dyld->setProcessAllSections(ProcessAllSections);
874 Dyld->setRuntimeDyldChecker(Checker);
878 static std::unique_ptr<RuntimeDyldMachO>
879 createRuntimeDyldMachO(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
880 RuntimeDyld::SymbolResolver &Resolver,
881 bool ProcessAllSections,
882 RuntimeDyldCheckerImpl *Checker) {
883 std::unique_ptr<RuntimeDyldMachO> Dyld =
884 RuntimeDyldMachO::create(Arch, MM, Resolver);
885 Dyld->setProcessAllSections(ProcessAllSections);
886 Dyld->setRuntimeDyldChecker(Checker);
890 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
891 RuntimeDyld::loadObject(const ObjectFile &Obj) {
894 Dyld = createRuntimeDyldELF(MemMgr, Resolver, ProcessAllSections, Checker);
895 else if (Obj.isMachO())
896 Dyld = createRuntimeDyldMachO(
897 static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
898 ProcessAllSections, Checker);
899 else if (Obj.isCOFF())
900 Dyld = createRuntimeDyldCOFF(
901 static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
902 ProcessAllSections, Checker);
904 report_fatal_error("Incompatible object format!");
907 if (!Dyld->isCompatibleFile(Obj))
908 report_fatal_error("Incompatible object format!");
910 return Dyld->loadObject(Obj);
913 void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
916 return Dyld->getSymbolLocalAddress(Name);
919 RuntimeDyld::SymbolInfo RuntimeDyld::getSymbol(StringRef Name) const {
922 return Dyld->getSymbol(Name);
925 void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
927 void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
928 Dyld->reassignSectionAddress(SectionID, Addr);
931 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
932 uint64_t TargetAddress) {
933 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
936 bool RuntimeDyld::hasError() { return Dyld->hasError(); }
938 StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
940 void RuntimeDyld::registerEHFrames() {
942 Dyld->registerEHFrames();
945 void RuntimeDyld::deregisterEHFrames() {
947 Dyld->deregisterEHFrames();
950 } // end namespace llvm