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,
61 LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
62 while (StartPadding--)
66 while (BytesRemaining > 0) {
67 if ((LoadAddr & (ColsPerRow - 1)) == 0)
68 dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
70 dbgs() << " " << format("%02x", *DataAddr);
81 // Resolve the relocations for all symbols we currently know about.
82 void RuntimeDyldImpl::resolveRelocations() {
83 MutexGuard locked(lock);
85 // First, resolve relocations associated with external symbols.
86 resolveExternalSymbols();
88 // Just iterate over the sections we have and resolve all the relocations
89 // in them. Gross overkill, but it gets the job done.
90 for (int i = 0, e = Sections.size(); i != e; ++i) {
91 // The Section here (Sections[i]) refers to the section in which the
92 // symbol for the relocation is located. The SectionID in the relocation
93 // entry provides the section to which the relocation will be applied.
94 uint64_t Addr = Sections[i].LoadAddress;
95 DEBUG(dbgs() << "Resolving relocations Section #" << i << "\t"
96 << format("%p", (uintptr_t)Addr) << "\n");
97 DEBUG(dumpSectionMemory(Sections[i], "before relocations"));
98 resolveRelocationList(Relocations[i], Addr);
99 DEBUG(dumpSectionMemory(Sections[i], "after relocations"));
100 Relocations.erase(i);
104 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
105 uint64_t TargetAddress) {
106 MutexGuard locked(lock);
107 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
108 if (Sections[i].Address == LocalAddress) {
109 reassignSectionAddress(i, TargetAddress);
113 llvm_unreachable("Attempting to remap address of unknown section!");
116 static std::error_code getOffset(const SymbolRef &Sym, uint64_t &Result) {
117 ErrorOr<uint64_t> AddressOrErr = Sym.getAddress();
118 if (std::error_code EC = AddressOrErr.getError())
120 uint64_t Address = *AddressOrErr;
122 if (Address == UnknownAddress) {
123 Result = UnknownAddress;
124 return std::error_code();
127 const ObjectFile *Obj = Sym.getObject();
128 section_iterator SecI(Obj->section_begin());
129 if (std::error_code EC = Sym.getSection(SecI))
132 if (SecI == Obj->section_end()) {
133 Result = UnknownAddress;
134 return std::error_code();
137 uint64_t SectionAddress = SecI->getAddress();
138 Result = Address - SectionAddress;
139 return std::error_code();
142 std::pair<unsigned, unsigned>
143 RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
144 MutexGuard locked(lock);
146 // Grab the first Section ID. We'll use this later to construct the underlying
147 // range for the returned LoadedObjectInfo.
148 unsigned SectionsAddedBeginIdx = Sections.size();
150 // Save information about our target
151 Arch = (Triple::ArchType)Obj.getArch();
152 IsTargetLittleEndian = Obj.isLittleEndian();
155 // Compute the memory size required to load all sections to be loaded
156 // and pass this information to the memory manager
157 if (MemMgr.needsToReserveAllocationSpace()) {
158 uint64_t CodeSize = 0, DataSizeRO = 0, DataSizeRW = 0;
159 computeTotalAllocSize(Obj, CodeSize, DataSizeRO, DataSizeRW);
160 MemMgr.reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
163 // Used sections from the object file
164 ObjSectionToIDMap LocalSections;
166 // Common symbols requiring allocation, with their sizes and alignments
167 CommonSymbolList CommonSymbols;
170 DEBUG(dbgs() << "Parse symbols:\n");
171 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
173 uint32_t Flags = I->getFlags();
175 bool IsCommon = Flags & SymbolRef::SF_Common;
177 CommonSymbols.push_back(*I);
179 object::SymbolRef::Type SymType = I->getType();
181 if (SymType == object::SymbolRef::ST_Function ||
182 SymType == object::SymbolRef::ST_Data ||
183 SymType == object::SymbolRef::ST_Unknown) {
185 ErrorOr<StringRef> NameOrErr = I->getName();
186 Check(NameOrErr.getError());
187 StringRef Name = *NameOrErr;
189 Check(getOffset(*I, SectOffset));
190 section_iterator SI = Obj.section_end();
191 Check(I->getSection(SI));
192 if (SI == Obj.section_end())
194 StringRef SectionData;
195 Check(SI->getContents(SectionData));
196 bool IsCode = SI->isText();
198 findOrEmitSection(Obj, *SI, IsCode, LocalSections);
199 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
200 << " SID: " << SectionID << " Offset: "
201 << format("%p", (uintptr_t)SectOffset)
202 << " flags: " << Flags << "\n");
203 JITSymbolFlags RTDyldSymFlags = JITSymbolFlags::None;
204 if (Flags & SymbolRef::SF_Weak)
205 RTDyldSymFlags |= JITSymbolFlags::Weak;
206 if (Flags & SymbolRef::SF_Exported)
207 RTDyldSymFlags |= JITSymbolFlags::Exported;
208 GlobalSymbolTable[Name] =
209 SymbolTableEntry(SectionID, SectOffset, RTDyldSymFlags);
214 // Allocate common symbols
215 emitCommonSymbols(Obj, CommonSymbols);
217 // Parse and process relocations
218 DEBUG(dbgs() << "Parse relocations:\n");
219 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
221 unsigned SectionID = 0;
223 section_iterator RelocatedSection = SI->getRelocatedSection();
225 if (RelocatedSection == SE)
228 relocation_iterator I = SI->relocation_begin();
229 relocation_iterator E = SI->relocation_end();
231 if (I == E && !ProcessAllSections)
234 bool IsCode = RelocatedSection->isText();
236 findOrEmitSection(Obj, *RelocatedSection, IsCode, LocalSections);
237 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
240 I = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs);
242 // If there is an attached checker, notify it about the stubs for this
243 // section so that they can be verified.
245 Checker->registerStubMap(Obj.getFileName(), SectionID, Stubs);
248 // Give the subclasses a chance to tie-up any loose ends.
249 finalizeLoad(Obj, LocalSections);
251 unsigned SectionsAddedEndIdx = Sections.size();
253 return std::make_pair(SectionsAddedBeginIdx, SectionsAddedEndIdx);
256 // A helper method for computeTotalAllocSize.
257 // Computes the memory size required to allocate sections with the given sizes,
258 // assuming that all sections are allocated with the given alignment
260 computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
261 uint64_t Alignment) {
262 uint64_t TotalSize = 0;
263 for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
264 uint64_t AlignedSize =
265 (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
266 TotalSize += AlignedSize;
271 static bool isRequiredForExecution(const SectionRef Section) {
272 const ObjectFile *Obj = Section.getObject();
273 if (isa<object::ELFObjectFileBase>(Obj))
274 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
275 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
276 const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
277 // Avoid loading zero-sized COFF sections.
278 // In PE files, VirtualSize gives the section size, and SizeOfRawData
279 // may be zero for sections with content. In Obj files, SizeOfRawData
280 // gives the section size, and VirtualSize is always zero. Hence
281 // the need to check for both cases below.
282 bool HasContent = (CoffSection->VirtualSize > 0)
283 || (CoffSection->SizeOfRawData > 0);
284 bool IsDiscardable = CoffSection->Characteristics &
285 (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
286 return HasContent && !IsDiscardable;
289 assert(isa<MachOObjectFile>(Obj));
293 static bool isReadOnlyData(const SectionRef Section) {
294 const ObjectFile *Obj = Section.getObject();
295 if (isa<object::ELFObjectFileBase>(Obj))
296 return !(ELFSectionRef(Section).getFlags() &
297 (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
298 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
299 return ((COFFObj->getCOFFSection(Section)->Characteristics &
300 (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
301 | COFF::IMAGE_SCN_MEM_READ
302 | COFF::IMAGE_SCN_MEM_WRITE))
304 (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
305 | COFF::IMAGE_SCN_MEM_READ));
307 assert(isa<MachOObjectFile>(Obj));
311 static bool isZeroInit(const SectionRef Section) {
312 const ObjectFile *Obj = Section.getObject();
313 if (isa<object::ELFObjectFileBase>(Obj))
314 return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
315 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
316 return COFFObj->getCOFFSection(Section)->Characteristics &
317 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
319 auto *MachO = cast<MachOObjectFile>(Obj);
320 unsigned SectionType = MachO->getSectionType(Section);
321 return SectionType == MachO::S_ZEROFILL ||
322 SectionType == MachO::S_GB_ZEROFILL;
325 // Compute an upper bound of the memory size that is required to load all
327 void RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
329 uint64_t &DataSizeRO,
330 uint64_t &DataSizeRW) {
331 // Compute the size of all sections required for execution
332 std::vector<uint64_t> CodeSectionSizes;
333 std::vector<uint64_t> ROSectionSizes;
334 std::vector<uint64_t> RWSectionSizes;
335 uint64_t MaxAlignment = sizeof(void *);
337 // Collect sizes of all sections to be loaded;
338 // also determine the max alignment of all sections
339 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
341 const SectionRef &Section = *SI;
343 bool IsRequired = isRequiredForExecution(Section);
345 // Consider only the sections that are required to be loaded for execution
348 uint64_t DataSize = Section.getSize();
349 uint64_t Alignment64 = Section.getAlignment();
350 bool IsCode = Section.isText();
351 bool IsReadOnly = isReadOnlyData(Section);
352 Check(Section.getName(Name));
353 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
355 uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
356 uint64_t SectionSize = DataSize + StubBufSize;
358 // The .eh_frame section (at least on Linux) needs an extra four bytes
360 // with zeroes added at the end. For MachO objects, this section has a
361 // slightly different name, so this won't have any effect for MachO
363 if (Name == ".eh_frame")
370 CodeSectionSizes.push_back(SectionSize);
371 } else if (IsReadOnly) {
372 ROSectionSizes.push_back(SectionSize);
374 RWSectionSizes.push_back(SectionSize);
377 // update the max alignment
378 if (Alignment > MaxAlignment) {
379 MaxAlignment = Alignment;
384 // Compute the size of all common symbols
385 uint64_t CommonSize = 0;
386 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
388 uint32_t Flags = I->getFlags();
389 if (Flags & SymbolRef::SF_Common) {
390 // Add the common symbols to a list. We'll allocate them all below.
391 uint64_t Size = I->getCommonSize();
395 if (CommonSize != 0) {
396 RWSectionSizes.push_back(CommonSize);
399 // Compute the required allocation space for each different type of sections
400 // (code, read-only data, read-write data) assuming that all sections are
401 // allocated with the max alignment. Note that we cannot compute with the
402 // individual alignments of the sections, because then the required size
403 // depends on the order, in which the sections are allocated.
404 CodeSize = computeAllocationSizeForSections(CodeSectionSizes, MaxAlignment);
405 DataSizeRO = computeAllocationSizeForSections(ROSectionSizes, MaxAlignment);
406 DataSizeRW = computeAllocationSizeForSections(RWSectionSizes, MaxAlignment);
409 // compute stub buffer size for the given section
410 unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
411 const SectionRef &Section) {
412 unsigned StubSize = getMaxStubSize();
416 // FIXME: this is an inefficient way to handle this. We should computed the
417 // necessary section allocation size in loadObject by walking all the sections
419 unsigned StubBufSize = 0;
420 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
422 section_iterator RelSecI = SI->getRelocatedSection();
423 if (!(RelSecI == Section))
426 for (const RelocationRef &Reloc : SI->relocations()) {
428 StubBufSize += StubSize;
432 // Get section data size and alignment
433 uint64_t DataSize = Section.getSize();
434 uint64_t Alignment64 = Section.getAlignment();
436 // Add stubbuf size alignment
437 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
438 unsigned StubAlignment = getStubAlignment();
439 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
440 if (StubAlignment > EndAlignment)
441 StubBufSize += StubAlignment - EndAlignment;
445 uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
446 unsigned Size) const {
448 if (IsTargetLittleEndian) {
451 Result = (Result << 8) | *Src--;
454 Result = (Result << 8) | *Src++;
459 void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
460 unsigned Size) const {
461 if (IsTargetLittleEndian) {
463 *Dst++ = Value & 0xFF;
469 *Dst-- = Value & 0xFF;
475 void RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
476 CommonSymbolList &CommonSymbols) {
477 if (CommonSymbols.empty())
480 uint64_t CommonSize = 0;
481 CommonSymbolList SymbolsToAllocate;
483 DEBUG(dbgs() << "Processing common symbols...\n");
485 for (const auto &Sym : CommonSymbols) {
486 ErrorOr<StringRef> NameOrErr = Sym.getName();
487 Check(NameOrErr.getError());
488 StringRef Name = *NameOrErr;
490 // Skip common symbols already elsewhere.
491 if (GlobalSymbolTable.count(Name) ||
492 Resolver.findSymbolInLogicalDylib(Name)) {
493 DEBUG(dbgs() << "\tSkipping already emitted common symbol '" << Name
498 uint32_t Align = Sym.getAlignment();
499 uint64_t Size = Sym.getCommonSize();
501 CommonSize += Align + Size;
502 SymbolsToAllocate.push_back(Sym);
505 // Allocate memory for the section
506 unsigned SectionID = Sections.size();
507 uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, sizeof(void *),
508 SectionID, StringRef(), false);
510 report_fatal_error("Unable to allocate memory for common symbols!");
512 Sections.push_back(SectionEntry("<common symbols>", Addr, CommonSize, 0));
513 memset(Addr, 0, CommonSize);
515 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID << " new addr: "
516 << format("%p", Addr) << " DataSize: " << CommonSize << "\n");
518 // Assign the address of each symbol
519 for (auto &Sym : SymbolsToAllocate) {
520 uint32_t Align = Sym.getAlignment();
521 uint64_t Size = Sym.getCommonSize();
522 ErrorOr<StringRef> NameOrErr = Sym.getName();
523 Check(NameOrErr.getError());
524 StringRef Name = *NameOrErr;
526 // This symbol has an alignment requirement.
527 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
529 Offset += AlignOffset;
531 uint32_t Flags = Sym.getFlags();
532 JITSymbolFlags RTDyldSymFlags = JITSymbolFlags::None;
533 if (Flags & SymbolRef::SF_Weak)
534 RTDyldSymFlags |= JITSymbolFlags::Weak;
535 if (Flags & SymbolRef::SF_Exported)
536 RTDyldSymFlags |= JITSymbolFlags::Exported;
537 DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
538 << format("%p", Addr) << "\n");
539 GlobalSymbolTable[Name] =
540 SymbolTableEntry(SectionID, Offset, RTDyldSymFlags);
546 unsigned RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
547 const SectionRef &Section, bool IsCode) {
550 uint64_t Alignment64 = Section.getAlignment();
552 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
553 unsigned PaddingSize = 0;
554 unsigned StubBufSize = 0;
556 bool IsRequired = isRequiredForExecution(Section);
557 bool IsVirtual = Section.isVirtual();
558 bool IsZeroInit = isZeroInit(Section);
559 bool IsReadOnly = isReadOnlyData(Section);
560 uint64_t DataSize = Section.getSize();
561 Check(Section.getName(Name));
563 StubBufSize = computeSectionStubBufSize(Obj, Section);
565 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
566 // with zeroes added at the end. For MachO objects, this section has a
567 // slightly different name, so this won't have any effect for MachO objects.
568 if (Name == ".eh_frame")
572 unsigned SectionID = Sections.size();
574 const char *pData = nullptr;
576 // In either case, set the location of the unrelocated section in memory,
577 // since we still process relocations for it even if we're not applying them.
578 Check(Section.getContents(data));
579 // Virtual sections have no data in the object image, so leave pData = 0
583 // Some sections, such as debug info, don't need to be loaded for execution.
584 // Leave those where they are.
586 Allocate = DataSize + PaddingSize + StubBufSize;
589 Addr = IsCode ? MemMgr.allocateCodeSection(Allocate, Alignment, SectionID,
591 : MemMgr.allocateDataSection(Allocate, Alignment, SectionID,
594 report_fatal_error("Unable to allocate section memory!");
596 // Zero-initialize or copy the data from the image
597 if (IsZeroInit || IsVirtual)
598 memset(Addr, 0, DataSize);
600 memcpy(Addr, pData, DataSize);
602 // Fill in any extra bytes we allocated for padding
603 if (PaddingSize != 0) {
604 memset(Addr + DataSize, 0, PaddingSize);
605 // Update the DataSize variable so that the stub offset is set correctly.
606 DataSize += PaddingSize;
609 DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
610 << " obj addr: " << format("%p", pData)
611 << " new addr: " << format("%p", Addr)
612 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
613 << " Allocate: " << Allocate << "\n");
615 // Even if we didn't load the section, we need to record an entry for it
616 // to handle later processing (and by 'handle' I mean don't do anything
617 // with these sections).
620 DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
621 << " obj addr: " << format("%p", data.data()) << " new addr: 0"
622 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
623 << " Allocate: " << Allocate << "\n");
626 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
629 Checker->registerSection(Obj.getFileName(), SectionID);
634 unsigned RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
635 const SectionRef &Section,
637 ObjSectionToIDMap &LocalSections) {
639 unsigned SectionID = 0;
640 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
641 if (i != LocalSections.end())
642 SectionID = i->second;
644 SectionID = emitSection(Obj, Section, IsCode);
645 LocalSections[Section] = SectionID;
650 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
651 unsigned SectionID) {
652 Relocations[SectionID].push_back(RE);
655 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
656 StringRef SymbolName) {
657 // Relocation by symbol. If the symbol is found in the global symbol table,
658 // create an appropriate section relocation. Otherwise, add it to
659 // ExternalSymbolRelocations.
660 RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
661 if (Loc == GlobalSymbolTable.end()) {
662 ExternalSymbolRelocations[SymbolName].push_back(RE);
664 // Copy the RE since we want to modify its addend.
665 RelocationEntry RECopy = RE;
666 const auto &SymInfo = Loc->second;
667 RECopy.Addend += SymInfo.getOffset();
668 Relocations[SymInfo.getSectionID()].push_back(RECopy);
672 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
673 unsigned AbiVariant) {
674 if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
675 // This stub has to be able to access the full address space,
676 // since symbol lookup won't necessarily find a handy, in-range,
677 // PLT stub for functions which could be anywhere.
678 // Stub can use ip0 (== x16) to calculate address
679 writeBytesUnaligned(0xd2e00010, Addr, 4); // movz ip0, #:abs_g3:<addr>
680 writeBytesUnaligned(0xf2c00010, Addr+4, 4); // movk ip0, #:abs_g2_nc:<addr>
681 writeBytesUnaligned(0xf2a00010, Addr+8, 4); // movk ip0, #:abs_g1_nc:<addr>
682 writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
683 writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
686 } else if (Arch == Triple::arm || Arch == Triple::armeb) {
687 // TODO: There is only ARM far stub now. We should add the Thumb stub,
688 // and stubs for branches Thumb - ARM and ARM - Thumb.
689 writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc,<label>
691 } else if (IsMipsO32ABI) {
692 // 0: 3c190000 lui t9,%hi(addr).
693 // 4: 27390000 addiu t9,t9,%lo(addr).
694 // 8: 03200008 jr t9.
696 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
697 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
699 writeBytesUnaligned(LuiT9Instr, Addr, 4);
700 writeBytesUnaligned(AdduiT9Instr, Addr+4, 4);
701 writeBytesUnaligned(JrT9Instr, Addr+8, 4);
702 writeBytesUnaligned(NopInstr, Addr+12, 4);
704 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
705 // Depending on which version of the ELF ABI is in use, we need to
706 // generate one of two variants of the stub. They both start with
707 // the same sequence to load the target address into r12.
708 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
709 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
710 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
711 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
712 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
713 if (AbiVariant == 2) {
714 // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
715 // The address is already in r12 as required by the ABI. Branch to it.
716 writeInt32BE(Addr+20, 0xF8410018); // std r2, 24(r1)
717 writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
718 writeInt32BE(Addr+28, 0x4E800420); // bctr
720 // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
721 // Load the function address on r11 and sets it to control register. Also
722 // loads the function TOC in r2 and environment pointer to r11.
723 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
724 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
725 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
726 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
727 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
728 writeInt32BE(Addr+40, 0x4E800420); // bctr
731 } else if (Arch == Triple::systemz) {
732 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
733 writeInt16BE(Addr+2, 0x0000);
734 writeInt16BE(Addr+4, 0x0004);
735 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
736 // 8-byte address stored at Addr + 8
738 } else if (Arch == Triple::x86_64) {
740 *(Addr+1) = 0x25; // rip
741 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
742 } else if (Arch == Triple::x86) {
743 *Addr = 0xE9; // 32-bit pc-relative jump.
748 // Assign an address to a symbol name and resolve all the relocations
749 // associated with it.
750 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
752 // The address to use for relocation resolution is not
753 // the address of the local section buffer. We must be doing
754 // a remote execution environment of some sort. Relocations can't
755 // be applied until all the sections have been moved. The client must
756 // trigger this with a call to MCJIT::finalize() or
757 // RuntimeDyld::resolveRelocations().
759 // Addr is a uint64_t because we can't assume the pointer width
760 // of the target is the same as that of the host. Just use a generic
761 // "big enough" type.
762 DEBUG(dbgs() << "Reassigning address for section "
763 << SectionID << " (" << Sections[SectionID].Name << "): "
764 << format("0x%016" PRIx64, Sections[SectionID].LoadAddress) << " -> "
765 << format("0x%016" PRIx64, Addr) << "\n");
766 Sections[SectionID].LoadAddress = Addr;
769 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
771 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
772 const RelocationEntry &RE = Relocs[i];
773 // Ignore relocations for sections that were not loaded
774 if (Sections[RE.SectionID].Address == nullptr)
776 resolveRelocation(RE, Value);
780 void RuntimeDyldImpl::resolveExternalSymbols() {
781 while (!ExternalSymbolRelocations.empty()) {
782 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
784 StringRef Name = i->first();
785 if (Name.size() == 0) {
786 // This is an absolute symbol, use an address of zero.
787 DEBUG(dbgs() << "Resolving absolute relocations."
789 RelocationList &Relocs = i->second;
790 resolveRelocationList(Relocs, 0);
793 RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
794 if (Loc == GlobalSymbolTable.end()) {
795 // This is an external symbol, try to get its address from the symbol
797 Addr = Resolver.findSymbol(Name.data()).getAddress();
798 // The call to getSymbolAddress may have caused additional modules to
799 // be loaded, which may have added new entries to the
800 // ExternalSymbolRelocations map. Consquently, we need to update our
801 // iterator. This is also why retrieval of the relocation list
802 // associated with this symbol is deferred until below this point.
803 // New entries may have been added to the relocation list.
804 i = ExternalSymbolRelocations.find(Name);
806 // We found the symbol in our global table. It was probably in a
807 // Module that we loaded previously.
808 const auto &SymInfo = Loc->second;
809 Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
813 // FIXME: Implement error handling that doesn't kill the host program!
815 report_fatal_error("Program used external function '" + Name +
816 "' which could not be resolved!");
818 DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
819 << format("0x%lx", Addr) << "\n");
820 // This list may have been updated when we called getSymbolAddress, so
821 // don't change this code to get the list earlier.
822 RelocationList &Relocs = i->second;
823 resolveRelocationList(Relocs, Addr);
826 ExternalSymbolRelocations.erase(i);
830 //===----------------------------------------------------------------------===//
831 // RuntimeDyld class implementation
833 uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
834 StringRef SectionName) const {
835 for (unsigned I = BeginIdx; I != EndIdx; ++I)
836 if (RTDyld.Sections[I].Name == SectionName)
837 return RTDyld.Sections[I].LoadAddress;
842 void RuntimeDyld::MemoryManager::anchor() {}
843 void RuntimeDyld::SymbolResolver::anchor() {}
845 RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
846 RuntimeDyld::SymbolResolver &Resolver)
847 : MemMgr(MemMgr), Resolver(Resolver) {
848 // FIXME: There's a potential issue lurking here if a single instance of
849 // RuntimeDyld is used to load multiple objects. The current implementation
850 // associates a single memory manager with a RuntimeDyld instance. Even
851 // though the public class spawns a new 'impl' instance for each load,
852 // they share a single memory manager. This can become a problem when page
853 // permissions are applied.
855 ProcessAllSections = false;
859 RuntimeDyld::~RuntimeDyld() {}
861 static std::unique_ptr<RuntimeDyldCOFF>
862 createRuntimeDyldCOFF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
863 RuntimeDyld::SymbolResolver &Resolver,
864 bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
865 std::unique_ptr<RuntimeDyldCOFF> Dyld =
866 RuntimeDyldCOFF::create(Arch, MM, Resolver);
867 Dyld->setProcessAllSections(ProcessAllSections);
868 Dyld->setRuntimeDyldChecker(Checker);
872 static std::unique_ptr<RuntimeDyldELF>
873 createRuntimeDyldELF(RuntimeDyld::MemoryManager &MM,
874 RuntimeDyld::SymbolResolver &Resolver,
875 bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
876 std::unique_ptr<RuntimeDyldELF> Dyld(new RuntimeDyldELF(MM, Resolver));
877 Dyld->setProcessAllSections(ProcessAllSections);
878 Dyld->setRuntimeDyldChecker(Checker);
882 static std::unique_ptr<RuntimeDyldMachO>
883 createRuntimeDyldMachO(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
884 RuntimeDyld::SymbolResolver &Resolver,
885 bool ProcessAllSections,
886 RuntimeDyldCheckerImpl *Checker) {
887 std::unique_ptr<RuntimeDyldMachO> Dyld =
888 RuntimeDyldMachO::create(Arch, MM, Resolver);
889 Dyld->setProcessAllSections(ProcessAllSections);
890 Dyld->setRuntimeDyldChecker(Checker);
894 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
895 RuntimeDyld::loadObject(const ObjectFile &Obj) {
898 Dyld = createRuntimeDyldELF(MemMgr, Resolver, ProcessAllSections, Checker);
899 else if (Obj.isMachO())
900 Dyld = createRuntimeDyldMachO(
901 static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
902 ProcessAllSections, Checker);
903 else if (Obj.isCOFF())
904 Dyld = createRuntimeDyldCOFF(
905 static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
906 ProcessAllSections, Checker);
908 report_fatal_error("Incompatible object format!");
911 if (!Dyld->isCompatibleFile(Obj))
912 report_fatal_error("Incompatible object format!");
914 return Dyld->loadObject(Obj);
917 void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
920 return Dyld->getSymbolLocalAddress(Name);
923 RuntimeDyld::SymbolInfo RuntimeDyld::getSymbol(StringRef Name) const {
926 return Dyld->getSymbol(Name);
929 void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
931 void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
932 Dyld->reassignSectionAddress(SectionID, Addr);
935 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
936 uint64_t TargetAddress) {
937 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
940 bool RuntimeDyld::hasError() { return Dyld->hasError(); }
942 StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
944 void RuntimeDyld::registerEHFrames() {
946 Dyld->registerEHFrames();
949 void RuntimeDyld::deregisterEHFrames() {
951 Dyld->deregisterEHFrames();
954 } // end namespace llvm