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/ManagedStatic.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/MutexGuard.h"
27 using namespace llvm::object;
29 #define DEBUG_TYPE "dyld"
33 enum RuntimeDyldErrorCode {
34 GenericRTDyldError = 1
37 // FIXME: This class is only here to support the transition to llvm::Error. It
38 // will be removed once this transition is complete. Clients should prefer to
39 // deal with the Error value directly, rather than converting to error_code.
40 class RuntimeDyldErrorCategory : public std::error_category {
42 const char *name() const noexcept override { return "runtimedyld"; }
44 std::string message(int Condition) const override {
45 switch (static_cast<RuntimeDyldErrorCode>(Condition)) {
46 case GenericRTDyldError: return "Generic RuntimeDyld error";
48 llvm_unreachable("Unrecognized RuntimeDyldErrorCode");
52 static ManagedStatic<RuntimeDyldErrorCategory> RTDyldErrorCategory;
56 char RuntimeDyldError::ID = 0;
58 void RuntimeDyldError::log(raw_ostream &OS) const {
62 std::error_code RuntimeDyldError::convertToErrorCode() const {
63 return std::error_code(GenericRTDyldError, *RTDyldErrorCategory);
66 // Empty out-of-line virtual destructor as the key function.
67 RuntimeDyldImpl::~RuntimeDyldImpl() {}
69 // Pin LoadedObjectInfo's vtables to this file.
70 void RuntimeDyld::LoadedObjectInfo::anchor() {}
74 void RuntimeDyldImpl::registerEHFrames() {}
76 void RuntimeDyldImpl::deregisterEHFrames() {
77 MemMgr.deregisterEHFrames();
81 static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
82 dbgs() << "----- Contents of section " << S.getName() << " " << State
85 if (S.getAddress() == nullptr) {
86 dbgs() << "\n <section not emitted>\n";
90 const unsigned ColsPerRow = 16;
92 uint8_t *DataAddr = S.getAddress();
93 uint64_t LoadAddr = S.getLoadAddress();
95 unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
96 unsigned BytesRemaining = S.getSize();
99 dbgs() << "\n" << format("0x%016" PRIx64,
100 LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
101 while (StartPadding--)
105 while (BytesRemaining > 0) {
106 if ((LoadAddr & (ColsPerRow - 1)) == 0)
107 dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
109 dbgs() << " " << format("%02x", *DataAddr);
120 // Resolve the relocations for all symbols we currently know about.
121 void RuntimeDyldImpl::resolveRelocations() {
122 MutexGuard locked(lock);
124 // Print out the sections prior to relocation.
126 for (int i = 0, e = Sections.size(); i != e; ++i)
127 dumpSectionMemory(Sections[i], "before relocations");
130 // First, resolve relocations associated with external symbols.
131 resolveExternalSymbols();
133 // Iterate over all outstanding relocations
134 for (auto it = Relocations.begin(), e = Relocations.end(); it != e; ++it) {
135 // The Section here (Sections[i]) refers to the section in which the
136 // symbol for the relocation is located. The SectionID in the relocation
137 // entry provides the section to which the relocation will be applied.
139 uint64_t Addr = Sections[Idx].getLoadAddress();
140 DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"
141 << format("%p", (uintptr_t)Addr) << "\n");
142 resolveRelocationList(it->second, Addr);
146 // Print out sections after relocation.
148 for (int i = 0, e = Sections.size(); i != e; ++i)
149 dumpSectionMemory(Sections[i], "after relocations");
154 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
155 uint64_t TargetAddress) {
156 MutexGuard locked(lock);
157 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
158 if (Sections[i].getAddress() == LocalAddress) {
159 reassignSectionAddress(i, TargetAddress);
163 llvm_unreachable("Attempting to remap address of unknown section!");
166 static Error getOffset(const SymbolRef &Sym, SectionRef Sec,
168 Expected<uint64_t> AddressOrErr = Sym.getAddress();
170 return AddressOrErr.takeError();
171 Result = *AddressOrErr - Sec.getAddress();
172 return Error::success();
175 Expected<RuntimeDyldImpl::ObjSectionToIDMap>
176 RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
177 MutexGuard locked(lock);
179 // Save information about our target
180 Arch = (Triple::ArchType)Obj.getArch();
181 IsTargetLittleEndian = Obj.isLittleEndian();
184 // Compute the memory size required to load all sections to be loaded
185 // and pass this information to the memory manager
186 if (MemMgr.needsToReserveAllocationSpace()) {
187 uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;
188 uint32_t CodeAlign = 1, RODataAlign = 1, RWDataAlign = 1;
189 if (auto Err = computeTotalAllocSize(Obj,
191 RODataSize, RODataAlign,
192 RWDataSize, RWDataAlign))
193 return std::move(Err);
194 MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,
195 RWDataSize, RWDataAlign);
198 // Used sections from the object file
199 ObjSectionToIDMap LocalSections;
201 // Common symbols requiring allocation, with their sizes and alignments
202 CommonSymbolList CommonSymbols;
205 DEBUG(dbgs() << "Parse symbols:\n");
206 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
208 uint32_t Flags = I->getFlags();
210 // Skip undefined symbols.
211 if (Flags & SymbolRef::SF_Undefined)
214 if (Flags & SymbolRef::SF_Common)
215 CommonSymbols.push_back(*I);
218 // Get the symbol type.
219 object::SymbolRef::Type SymType;
220 if (auto SymTypeOrErr = I->getType())
221 SymType = *SymTypeOrErr;
223 return SymTypeOrErr.takeError();
227 if (auto NameOrErr = I->getName())
230 return NameOrErr.takeError();
232 // Compute JIT symbol flags.
233 JITSymbolFlags JITSymFlags = JITSymbolFlags::fromObjectSymbol(*I);
235 // If this is a weak definition, check to see if there's a strong one.
236 // If there is, skip this symbol (we won't be providing it: the strong
237 // definition will). If there's no strong definition, make this definition
239 if (JITSymFlags.isWeak()) {
240 // First check whether there's already a definition in this instance.
241 // FIXME: Override existing weak definitions with strong ones.
242 if (GlobalSymbolTable.count(Name))
244 // Then check the symbol resolver to see if there's a definition
245 // elsewhere in this logical dylib.
246 if (auto Sym = Resolver.findSymbolInLogicalDylib(Name))
247 if (Sym.getFlags().isStrongDefinition())
250 JITSymFlags &= ~JITSymbolFlags::Weak;
253 if (Flags & SymbolRef::SF_Absolute &&
254 SymType != object::SymbolRef::ST_File) {
256 if (auto AddrOrErr = I->getAddress())
259 return AddrOrErr.takeError();
261 unsigned SectionID = AbsoluteSymbolSection;
263 DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name
264 << " SID: " << SectionID << " Offset: "
265 << format("%p", (uintptr_t)Addr)
266 << " flags: " << Flags << "\n");
267 GlobalSymbolTable[Name] =
268 SymbolTableEntry(SectionID, Addr, JITSymFlags);
269 } else if (SymType == object::SymbolRef::ST_Function ||
270 SymType == object::SymbolRef::ST_Data ||
271 SymType == object::SymbolRef::ST_Unknown ||
272 SymType == object::SymbolRef::ST_Other) {
274 section_iterator SI = Obj.section_end();
275 if (auto SIOrErr = I->getSection())
278 return SIOrErr.takeError();
280 if (SI == Obj.section_end())
283 // Get symbol offset.
285 if (auto Err = getOffset(*I, *SI, SectOffset))
286 return std::move(Err);
288 bool IsCode = SI->isText();
290 if (auto SectionIDOrErr = findOrEmitSection(Obj, *SI, IsCode,
292 SectionID = *SectionIDOrErr;
294 return SectionIDOrErr.takeError();
296 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
297 << " SID: " << SectionID << " Offset: "
298 << format("%p", (uintptr_t)SectOffset)
299 << " flags: " << Flags << "\n");
300 GlobalSymbolTable[Name] =
301 SymbolTableEntry(SectionID, SectOffset, JITSymFlags);
306 // Allocate common symbols
307 if (auto Err = emitCommonSymbols(Obj, CommonSymbols))
308 return std::move(Err);
310 // Parse and process relocations
311 DEBUG(dbgs() << "Parse relocations:\n");
312 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
315 section_iterator RelocatedSection = SI->getRelocatedSection();
317 if (RelocatedSection == SE)
320 relocation_iterator I = SI->relocation_begin();
321 relocation_iterator E = SI->relocation_end();
323 if (I == E && !ProcessAllSections)
326 bool IsCode = RelocatedSection->isText();
327 unsigned SectionID = 0;
328 if (auto SectionIDOrErr = findOrEmitSection(Obj, *RelocatedSection, IsCode,
330 SectionID = *SectionIDOrErr;
332 return SectionIDOrErr.takeError();
334 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
337 if (auto IOrErr = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs))
340 return IOrErr.takeError();
342 // If there is an attached checker, notify it about the stubs for this
343 // section so that they can be verified.
345 Checker->registerStubMap(Obj.getFileName(), SectionID, Stubs);
348 // Give the subclasses a chance to tie-up any loose ends.
349 if (auto Err = finalizeLoad(Obj, LocalSections))
350 return std::move(Err);
352 // for (auto E : LocalSections)
353 // llvm::dbgs() << "Added: " << E.first.getRawDataRefImpl() << " -> " << E.second << "\n";
355 return LocalSections;
358 // A helper method for computeTotalAllocSize.
359 // Computes the memory size required to allocate sections with the given sizes,
360 // assuming that all sections are allocated with the given alignment
362 computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
363 uint64_t Alignment) {
364 uint64_t TotalSize = 0;
365 for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
366 uint64_t AlignedSize =
367 (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
368 TotalSize += AlignedSize;
373 static bool isRequiredForExecution(const SectionRef Section) {
374 const ObjectFile *Obj = Section.getObject();
375 if (isa<object::ELFObjectFileBase>(Obj))
376 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
377 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
378 const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
379 // Avoid loading zero-sized COFF sections.
380 // In PE files, VirtualSize gives the section size, and SizeOfRawData
381 // may be zero for sections with content. In Obj files, SizeOfRawData
382 // gives the section size, and VirtualSize is always zero. Hence
383 // the need to check for both cases below.
385 (CoffSection->VirtualSize > 0) || (CoffSection->SizeOfRawData > 0);
387 CoffSection->Characteristics &
388 (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
389 return HasContent && !IsDiscardable;
392 assert(isa<MachOObjectFile>(Obj));
396 static bool isReadOnlyData(const SectionRef Section) {
397 const ObjectFile *Obj = Section.getObject();
398 if (isa<object::ELFObjectFileBase>(Obj))
399 return !(ELFSectionRef(Section).getFlags() &
400 (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
401 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
402 return ((COFFObj->getCOFFSection(Section)->Characteristics &
403 (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
404 | COFF::IMAGE_SCN_MEM_READ
405 | COFF::IMAGE_SCN_MEM_WRITE))
407 (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
408 | COFF::IMAGE_SCN_MEM_READ));
410 assert(isa<MachOObjectFile>(Obj));
414 static bool isZeroInit(const SectionRef Section) {
415 const ObjectFile *Obj = Section.getObject();
416 if (isa<object::ELFObjectFileBase>(Obj))
417 return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
418 if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
419 return COFFObj->getCOFFSection(Section)->Characteristics &
420 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
422 auto *MachO = cast<MachOObjectFile>(Obj);
423 unsigned SectionType = MachO->getSectionType(Section);
424 return SectionType == MachO::S_ZEROFILL ||
425 SectionType == MachO::S_GB_ZEROFILL;
428 // Compute an upper bound of the memory size that is required to load all
430 Error RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
433 uint64_t &RODataSize,
434 uint32_t &RODataAlign,
435 uint64_t &RWDataSize,
436 uint32_t &RWDataAlign) {
437 // Compute the size of all sections required for execution
438 std::vector<uint64_t> CodeSectionSizes;
439 std::vector<uint64_t> ROSectionSizes;
440 std::vector<uint64_t> RWSectionSizes;
442 // Collect sizes of all sections to be loaded;
443 // also determine the max alignment of all sections
444 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
446 const SectionRef &Section = *SI;
448 bool IsRequired = isRequiredForExecution(Section) || ProcessAllSections;
450 // Consider only the sections that are required to be loaded for execution
452 uint64_t DataSize = Section.getSize();
453 uint64_t Alignment64 = Section.getAlignment();
454 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
455 bool IsCode = Section.isText();
456 bool IsReadOnly = isReadOnlyData(Section);
459 if (auto EC = Section.getName(Name))
460 return errorCodeToError(EC);
462 uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
463 uint64_t SectionSize = DataSize + StubBufSize;
465 // The .eh_frame section (at least on Linux) needs an extra four bytes
467 // with zeroes added at the end. For MachO objects, this section has a
468 // slightly different name, so this won't have any effect for MachO
470 if (Name == ".eh_frame")
477 CodeAlign = std::max(CodeAlign, Alignment);
478 CodeSectionSizes.push_back(SectionSize);
479 } else if (IsReadOnly) {
480 RODataAlign = std::max(RODataAlign, Alignment);
481 ROSectionSizes.push_back(SectionSize);
483 RWDataAlign = std::max(RWDataAlign, Alignment);
484 RWSectionSizes.push_back(SectionSize);
489 // Compute Global Offset Table size. If it is not zero we
490 // also update alignment, which is equal to a size of a
492 if (unsigned GotSize = computeGOTSize(Obj)) {
493 RWSectionSizes.push_back(GotSize);
494 RWDataAlign = std::max<uint32_t>(RWDataAlign, getGOTEntrySize());
497 // Compute the size of all common symbols
498 uint64_t CommonSize = 0;
499 uint32_t CommonAlign = 1;
500 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
502 uint32_t Flags = I->getFlags();
503 if (Flags & SymbolRef::SF_Common) {
504 // Add the common symbols to a list. We'll allocate them all below.
505 uint64_t Size = I->getCommonSize();
506 uint32_t Align = I->getAlignment();
507 // If this is the first common symbol, use its alignment as the alignment
508 // for the common symbols section.
511 CommonSize = alignTo(CommonSize, Align) + Size;
514 if (CommonSize != 0) {
515 RWSectionSizes.push_back(CommonSize);
516 RWDataAlign = std::max(RWDataAlign, CommonAlign);
519 // Compute the required allocation space for each different type of sections
520 // (code, read-only data, read-write data) assuming that all sections are
521 // allocated with the max alignment. Note that we cannot compute with the
522 // individual alignments of the sections, because then the required size
523 // depends on the order, in which the sections are allocated.
524 CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);
525 RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);
526 RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);
528 return Error::success();
532 unsigned RuntimeDyldImpl::computeGOTSize(const ObjectFile &Obj) {
533 size_t GotEntrySize = getGOTEntrySize();
538 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
541 for (const RelocationRef &Reloc : SI->relocations())
542 if (relocationNeedsGot(Reloc))
543 GotSize += GotEntrySize;
549 // compute stub buffer size for the given section
550 unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
551 const SectionRef &Section) {
552 unsigned StubSize = getMaxStubSize();
556 // FIXME: this is an inefficient way to handle this. We should computed the
557 // necessary section allocation size in loadObject by walking all the sections
559 unsigned StubBufSize = 0;
560 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
562 section_iterator RelSecI = SI->getRelocatedSection();
563 if (!(RelSecI == Section))
566 for (const RelocationRef &Reloc : SI->relocations())
567 if (relocationNeedsStub(Reloc))
568 StubBufSize += StubSize;
571 // Get section data size and alignment
572 uint64_t DataSize = Section.getSize();
573 uint64_t Alignment64 = Section.getAlignment();
575 // Add stubbuf size alignment
576 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
577 unsigned StubAlignment = getStubAlignment();
578 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
579 if (StubAlignment > EndAlignment)
580 StubBufSize += StubAlignment - EndAlignment;
584 uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
585 unsigned Size) const {
587 if (IsTargetLittleEndian) {
590 Result = (Result << 8) | *Src--;
593 Result = (Result << 8) | *Src++;
598 void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
599 unsigned Size) const {
600 if (IsTargetLittleEndian) {
602 *Dst++ = Value & 0xFF;
608 *Dst-- = Value & 0xFF;
614 Error RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
615 CommonSymbolList &CommonSymbols) {
616 if (CommonSymbols.empty())
617 return Error::success();
619 uint64_t CommonSize = 0;
620 uint32_t CommonAlign = CommonSymbols.begin()->getAlignment();
621 CommonSymbolList SymbolsToAllocate;
623 DEBUG(dbgs() << "Processing common symbols...\n");
625 for (const auto &Sym : CommonSymbols) {
627 if (auto NameOrErr = Sym.getName())
630 return NameOrErr.takeError();
632 // Skip common symbols already elsewhere.
633 if (GlobalSymbolTable.count(Name)) {
634 DEBUG(dbgs() << "\tSkipping already emitted common symbol '" << Name
639 if (auto Sym = Resolver.findSymbolInLogicalDylib(Name)) {
640 if (!Sym.getFlags().isCommon()) {
641 DEBUG(dbgs() << "\tSkipping common symbol '" << Name
642 << "' in favor of stronger definition.\n");
646 uint32_t Align = Sym.getAlignment();
647 uint64_t Size = Sym.getCommonSize();
649 CommonSize = alignTo(CommonSize, Align) + Size;
651 SymbolsToAllocate.push_back(Sym);
654 // Allocate memory for the section
655 unsigned SectionID = Sections.size();
656 uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, CommonAlign, SectionID,
657 "<common symbols>", false);
659 report_fatal_error("Unable to allocate memory for common symbols!");
662 SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));
663 memset(Addr, 0, CommonSize);
665 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID << " new addr: "
666 << format("%p", Addr) << " DataSize: " << CommonSize << "\n");
668 // Assign the address of each symbol
669 for (auto &Sym : SymbolsToAllocate) {
670 uint32_t Align = Sym.getAlignment();
671 uint64_t Size = Sym.getCommonSize();
673 if (auto NameOrErr = Sym.getName())
676 return NameOrErr.takeError();
678 // This symbol has an alignment requirement.
679 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
681 Offset += AlignOffset;
683 JITSymbolFlags JITSymFlags = JITSymbolFlags::fromObjectSymbol(Sym);
684 DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
685 << format("%p", Addr) << "\n");
686 GlobalSymbolTable[Name] =
687 SymbolTableEntry(SectionID, Offset, JITSymFlags);
693 Checker->registerSection(Obj.getFileName(), SectionID);
695 return Error::success();
699 RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
700 const SectionRef &Section,
703 uint64_t Alignment64 = Section.getAlignment();
705 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
706 unsigned PaddingSize = 0;
707 unsigned StubBufSize = 0;
708 bool IsRequired = isRequiredForExecution(Section);
709 bool IsVirtual = Section.isVirtual();
710 bool IsZeroInit = isZeroInit(Section);
711 bool IsReadOnly = isReadOnlyData(Section);
712 uint64_t DataSize = Section.getSize();
715 if (auto EC = Section.getName(Name))
716 return errorCodeToError(EC);
718 StubBufSize = computeSectionStubBufSize(Obj, Section);
720 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
721 // with zeroes added at the end. For MachO objects, this section has a
722 // slightly different name, so this won't have any effect for MachO objects.
723 if (Name == ".eh_frame")
727 unsigned SectionID = Sections.size();
729 const char *pData = nullptr;
731 // If this section contains any bits (i.e. isn't a virtual or bss section),
732 // grab a reference to them.
733 if (!IsVirtual && !IsZeroInit) {
734 // In either case, set the location of the unrelocated section in memory,
735 // since we still process relocations for it even if we're not applying them.
736 if (auto EC = Section.getContents(data))
737 return errorCodeToError(EC);
741 // Code section alignment needs to be at least as high as stub alignment or
742 // padding calculations may by incorrect when the section is remapped to a
745 Alignment = std::max(Alignment, getStubAlignment());
747 // Some sections, such as debug info, don't need to be loaded for execution.
748 // Process those only if explicitly requested.
749 if (IsRequired || ProcessAllSections) {
750 Allocate = DataSize + PaddingSize + StubBufSize;
753 Addr = IsCode ? MemMgr.allocateCodeSection(Allocate, Alignment, SectionID,
755 : MemMgr.allocateDataSection(Allocate, Alignment, SectionID,
758 report_fatal_error("Unable to allocate section memory!");
760 // Zero-initialize or copy the data from the image
761 if (IsZeroInit || IsVirtual)
762 memset(Addr, 0, DataSize);
764 memcpy(Addr, pData, DataSize);
766 // Fill in any extra bytes we allocated for padding
767 if (PaddingSize != 0) {
768 memset(Addr + DataSize, 0, PaddingSize);
769 // Update the DataSize variable so that the stub offset is set correctly.
770 DataSize += PaddingSize;
773 DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
774 << " obj addr: " << format("%p", pData)
775 << " new addr: " << format("%p", Addr)
776 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
777 << " Allocate: " << Allocate << "\n");
779 // Even if we didn't load the section, we need to record an entry for it
780 // to handle later processing (and by 'handle' I mean don't do anything
781 // with these sections).
784 DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
785 << " obj addr: " << format("%p", data.data()) << " new addr: 0"
786 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
787 << " Allocate: " << Allocate << "\n");
791 SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));
793 // Debug info sections are linked as if their load address was zero
795 Sections.back().setLoadAddress(0);
798 Checker->registerSection(Obj.getFileName(), SectionID);
804 RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
805 const SectionRef &Section,
807 ObjSectionToIDMap &LocalSections) {
809 unsigned SectionID = 0;
810 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
811 if (i != LocalSections.end())
812 SectionID = i->second;
814 if (auto SectionIDOrErr = emitSection(Obj, Section, IsCode))
815 SectionID = *SectionIDOrErr;
817 return SectionIDOrErr.takeError();
818 LocalSections[Section] = SectionID;
823 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
824 unsigned SectionID) {
825 Relocations[SectionID].push_back(RE);
828 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
829 StringRef SymbolName) {
830 // Relocation by symbol. If the symbol is found in the global symbol table,
831 // create an appropriate section relocation. Otherwise, add it to
832 // ExternalSymbolRelocations.
833 RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
834 if (Loc == GlobalSymbolTable.end()) {
835 ExternalSymbolRelocations[SymbolName].push_back(RE);
837 // Copy the RE since we want to modify its addend.
838 RelocationEntry RECopy = RE;
839 const auto &SymInfo = Loc->second;
840 RECopy.Addend += SymInfo.getOffset();
841 Relocations[SymInfo.getSectionID()].push_back(RECopy);
845 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
846 unsigned AbiVariant) {
847 if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
848 // This stub has to be able to access the full address space,
849 // since symbol lookup won't necessarily find a handy, in-range,
850 // PLT stub for functions which could be anywhere.
851 // Stub can use ip0 (== x16) to calculate address
852 writeBytesUnaligned(0xd2e00010, Addr, 4); // movz ip0, #:abs_g3:<addr>
853 writeBytesUnaligned(0xf2c00010, Addr+4, 4); // movk ip0, #:abs_g2_nc:<addr>
854 writeBytesUnaligned(0xf2a00010, Addr+8, 4); // movk ip0, #:abs_g1_nc:<addr>
855 writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
856 writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
859 } else if (Arch == Triple::arm || Arch == Triple::armeb) {
860 // TODO: There is only ARM far stub now. We should add the Thumb stub,
861 // and stubs for branches Thumb - ARM and ARM - Thumb.
862 writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc,<label>
864 } else if (IsMipsO32ABI) {
865 // 0: 3c190000 lui t9,%hi(addr).
866 // 4: 27390000 addiu t9,t9,%lo(addr).
867 // 8: 03200008 jr t9.
869 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
870 const unsigned NopInstr = 0x0;
871 unsigned JrT9Instr = 0x03200008;
872 if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_32R6)
873 JrT9Instr = 0x03200009;
875 writeBytesUnaligned(LuiT9Instr, Addr, 4);
876 writeBytesUnaligned(AdduiT9Instr, Addr+4, 4);
877 writeBytesUnaligned(JrT9Instr, Addr+8, 4);
878 writeBytesUnaligned(NopInstr, Addr+12, 4);
880 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
881 // Depending on which version of the ELF ABI is in use, we need to
882 // generate one of two variants of the stub. They both start with
883 // the same sequence to load the target address into r12.
884 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
885 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
886 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
887 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
888 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
889 if (AbiVariant == 2) {
890 // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
891 // The address is already in r12 as required by the ABI. Branch to it.
892 writeInt32BE(Addr+20, 0xF8410018); // std r2, 24(r1)
893 writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
894 writeInt32BE(Addr+28, 0x4E800420); // bctr
896 // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
897 // Load the function address on r11 and sets it to control register. Also
898 // loads the function TOC in r2 and environment pointer to r11.
899 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
900 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
901 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
902 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
903 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
904 writeInt32BE(Addr+40, 0x4E800420); // bctr
907 } else if (Arch == Triple::systemz) {
908 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
909 writeInt16BE(Addr+2, 0x0000);
910 writeInt16BE(Addr+4, 0x0004);
911 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
912 // 8-byte address stored at Addr + 8
914 } else if (Arch == Triple::x86_64) {
916 *(Addr+1) = 0x25; // rip
917 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
918 } else if (Arch == Triple::x86) {
919 *Addr = 0xE9; // 32-bit pc-relative jump.
924 // Assign an address to a symbol name and resolve all the relocations
925 // associated with it.
926 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
928 // The address to use for relocation resolution is not
929 // the address of the local section buffer. We must be doing
930 // a remote execution environment of some sort. Relocations can't
931 // be applied until all the sections have been moved. The client must
932 // trigger this with a call to MCJIT::finalize() or
933 // RuntimeDyld::resolveRelocations().
935 // Addr is a uint64_t because we can't assume the pointer width
936 // of the target is the same as that of the host. Just use a generic
937 // "big enough" type.
938 DEBUG(dbgs() << "Reassigning address for section " << SectionID << " ("
939 << Sections[SectionID].getName() << "): "
940 << format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())
941 << " -> " << format("0x%016" PRIx64, Addr) << "\n");
942 Sections[SectionID].setLoadAddress(Addr);
945 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
947 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
948 const RelocationEntry &RE = Relocs[i];
949 // Ignore relocations for sections that were not loaded
950 if (Sections[RE.SectionID].getAddress() == nullptr)
952 resolveRelocation(RE, Value);
956 void RuntimeDyldImpl::resolveExternalSymbols() {
957 while (!ExternalSymbolRelocations.empty()) {
958 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
960 StringRef Name = i->first();
961 if (Name.size() == 0) {
962 // This is an absolute symbol, use an address of zero.
963 DEBUG(dbgs() << "Resolving absolute relocations."
965 RelocationList &Relocs = i->second;
966 resolveRelocationList(Relocs, 0);
969 RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
970 if (Loc == GlobalSymbolTable.end()) {
971 // This is an external symbol, try to get its address from the symbol
973 // First search for the symbol in this logical dylib.
974 Addr = Resolver.findSymbolInLogicalDylib(Name.data()).getAddress();
975 // If that fails, try searching for an external symbol.
977 Addr = Resolver.findSymbol(Name.data()).getAddress();
978 // The call to getSymbolAddress may have caused additional modules to
979 // be loaded, which may have added new entries to the
980 // ExternalSymbolRelocations map. Consquently, we need to update our
981 // iterator. This is also why retrieval of the relocation list
982 // associated with this symbol is deferred until below this point.
983 // New entries may have been added to the relocation list.
984 i = ExternalSymbolRelocations.find(Name);
986 // We found the symbol in our global table. It was probably in a
987 // Module that we loaded previously.
988 const auto &SymInfo = Loc->second;
989 Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
993 // FIXME: Implement error handling that doesn't kill the host program!
995 report_fatal_error("Program used external function '" + Name +
996 "' which could not be resolved!");
998 // If Resolver returned UINT64_MAX, the client wants to handle this symbol
999 // manually and we shouldn't resolve its relocations.
1000 if (Addr != UINT64_MAX) {
1001 DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
1002 << format("0x%lx", Addr) << "\n");
1003 // This list may have been updated when we called getSymbolAddress, so
1004 // don't change this code to get the list earlier.
1005 RelocationList &Relocs = i->second;
1006 resolveRelocationList(Relocs, Addr);
1010 ExternalSymbolRelocations.erase(i);
1014 //===----------------------------------------------------------------------===//
1015 // RuntimeDyld class implementation
1017 uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
1018 const object::SectionRef &Sec) const {
1020 auto I = ObjSecToIDMap.find(Sec);
1021 if (I != ObjSecToIDMap.end())
1022 return RTDyld.Sections[I->second].getLoadAddress();
1027 void RuntimeDyld::MemoryManager::anchor() {}
1028 void JITSymbolResolver::anchor() {}
1030 RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
1031 JITSymbolResolver &Resolver)
1032 : MemMgr(MemMgr), Resolver(Resolver) {
1033 // FIXME: There's a potential issue lurking here if a single instance of
1034 // RuntimeDyld is used to load multiple objects. The current implementation
1035 // associates a single memory manager with a RuntimeDyld instance. Even
1036 // though the public class spawns a new 'impl' instance for each load,
1037 // they share a single memory manager. This can become a problem when page
1038 // permissions are applied.
1040 ProcessAllSections = false;
1044 RuntimeDyld::~RuntimeDyld() {}
1046 static std::unique_ptr<RuntimeDyldCOFF>
1047 createRuntimeDyldCOFF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
1048 JITSymbolResolver &Resolver, bool ProcessAllSections,
1049 RuntimeDyldCheckerImpl *Checker) {
1050 std::unique_ptr<RuntimeDyldCOFF> Dyld =
1051 RuntimeDyldCOFF::create(Arch, MM, Resolver);
1052 Dyld->setProcessAllSections(ProcessAllSections);
1053 Dyld->setRuntimeDyldChecker(Checker);
1057 static std::unique_ptr<RuntimeDyldELF>
1058 createRuntimeDyldELF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
1059 JITSymbolResolver &Resolver, bool ProcessAllSections,
1060 RuntimeDyldCheckerImpl *Checker) {
1061 std::unique_ptr<RuntimeDyldELF> Dyld =
1062 RuntimeDyldELF::create(Arch, MM, Resolver);
1063 Dyld->setProcessAllSections(ProcessAllSections);
1064 Dyld->setRuntimeDyldChecker(Checker);
1068 static std::unique_ptr<RuntimeDyldMachO>
1069 createRuntimeDyldMachO(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
1070 JITSymbolResolver &Resolver,
1071 bool ProcessAllSections,
1072 RuntimeDyldCheckerImpl *Checker) {
1073 std::unique_ptr<RuntimeDyldMachO> Dyld =
1074 RuntimeDyldMachO::create(Arch, MM, Resolver);
1075 Dyld->setProcessAllSections(ProcessAllSections);
1076 Dyld->setRuntimeDyldChecker(Checker);
1080 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
1081 RuntimeDyld::loadObject(const ObjectFile &Obj) {
1085 createRuntimeDyldELF(static_cast<Triple::ArchType>(Obj.getArch()),
1086 MemMgr, Resolver, ProcessAllSections, Checker);
1087 else if (Obj.isMachO())
1088 Dyld = createRuntimeDyldMachO(
1089 static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
1090 ProcessAllSections, Checker);
1091 else if (Obj.isCOFF())
1092 Dyld = createRuntimeDyldCOFF(
1093 static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
1094 ProcessAllSections, Checker);
1096 report_fatal_error("Incompatible object format!");
1099 if (!Dyld->isCompatibleFile(Obj))
1100 report_fatal_error("Incompatible object format!");
1102 auto LoadedObjInfo = Dyld->loadObject(Obj);
1103 MemMgr.notifyObjectLoaded(*this, Obj);
1104 return LoadedObjInfo;
1107 void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
1110 return Dyld->getSymbolLocalAddress(Name);
1113 JITEvaluatedSymbol RuntimeDyld::getSymbol(StringRef Name) const {
1116 return Dyld->getSymbol(Name);
1119 void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
1121 void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
1122 Dyld->reassignSectionAddress(SectionID, Addr);
1125 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
1126 uint64_t TargetAddress) {
1127 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
1130 bool RuntimeDyld::hasError() { return Dyld->hasError(); }
1132 StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
1134 void RuntimeDyld::finalizeWithMemoryManagerLocking() {
1135 bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;
1136 MemMgr.FinalizationLocked = true;
1137 resolveRelocations();
1139 if (!MemoryFinalizationLocked) {
1140 MemMgr.finalizeMemory();
1141 MemMgr.FinalizationLocked = false;
1145 void RuntimeDyld::registerEHFrames() {
1147 Dyld->registerEHFrames();
1150 void RuntimeDyld::deregisterEHFrames() {
1152 Dyld->deregisterEHFrames();
1155 } // end namespace llvm