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 "JITRegistrar.h"
16 #include "ObjectImageCommon.h"
17 #include "RuntimeDyldCheckerImpl.h"
18 #include "RuntimeDyldELF.h"
19 #include "RuntimeDyldImpl.h"
20 #include "RuntimeDyldMachO.h"
21 #include "llvm/Object/ELF.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 the JITRegistrar's and ObjectImage*'s vtables to this file.
34 void JITRegistrar::anchor() {}
35 void ObjectImage::anchor() {}
36 void ObjectImageCommon::anchor() {}
40 void RuntimeDyldImpl::registerEHFrames() {}
42 void RuntimeDyldImpl::deregisterEHFrames() {}
44 static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
45 dbgs() << "----- Contents of section " << S.Name << " " << State << " -----";
47 const unsigned ColsPerRow = 16;
49 uint8_t *DataAddr = S.Address;
50 uint64_t LoadAddr = S.LoadAddress;
52 unsigned StartPadding = LoadAddr & 7;
53 unsigned BytesRemaining = S.Size;
56 dbgs() << "\n" << format("0x%08x", LoadAddr & ~(ColsPerRow - 1)) << ":";
57 while (StartPadding--)
61 while (BytesRemaining > 0) {
62 if ((LoadAddr & (ColsPerRow - 1)) == 0)
63 dbgs() << "\n" << format("0x%08x", LoadAddr) << ":";
65 dbgs() << " " << format("%02x", *DataAddr);
75 // Resolve the relocations for all symbols we currently know about.
76 void RuntimeDyldImpl::resolveRelocations() {
77 MutexGuard locked(lock);
79 // First, resolve relocations associated with external symbols.
80 resolveExternalSymbols();
82 // Just iterate over the sections we have and resolve all the relocations
83 // in them. Gross overkill, but it gets the job done.
84 for (int i = 0, e = Sections.size(); i != e; ++i) {
85 // The Section here (Sections[i]) refers to the section in which the
86 // symbol for the relocation is located. The SectionID in the relocation
87 // entry provides the section to which the relocation will be applied.
88 uint64_t Addr = Sections[i].LoadAddress;
89 DEBUG(dbgs() << "Resolving relocations Section #" << i << "\t"
90 << format("0x%x", Addr) << "\n");
91 DEBUG(dumpSectionMemory(Sections[i], "before relocations"));
92 resolveRelocationList(Relocations[i], Addr);
93 DEBUG(dumpSectionMemory(Sections[i], "after relocations"));
98 void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
99 uint64_t TargetAddress) {
100 MutexGuard locked(lock);
101 for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
102 if (Sections[i].Address == LocalAddress) {
103 reassignSectionAddress(i, TargetAddress);
107 llvm_unreachable("Attempting to remap address of unknown section!");
110 static std::error_code getOffset(const SymbolRef &Sym, uint64_t &Result) {
112 if (std::error_code EC = Sym.getAddress(Address))
115 if (Address == UnknownAddressOrSize) {
116 Result = UnknownAddressOrSize;
117 return object_error::success;
120 const ObjectFile *Obj = Sym.getObject();
121 section_iterator SecI(Obj->section_begin());
122 if (std::error_code EC = Sym.getSection(SecI))
125 if (SecI == Obj->section_end()) {
126 Result = UnknownAddressOrSize;
127 return object_error::success;
130 uint64_t SectionAddress;
131 if (std::error_code EC = SecI->getAddress(SectionAddress))
134 Result = Address - SectionAddress;
135 return object_error::success;
138 ObjectImage *RuntimeDyldImpl::loadObject(ObjectImage *InputObject) {
139 MutexGuard locked(lock);
141 std::unique_ptr<ObjectImage> Obj(InputObject);
145 // Save information about our target
146 Arch = (Triple::ArchType)Obj->getArch();
147 IsTargetLittleEndian = Obj->getObjectFile()->isLittleEndian();
149 // Compute the memory size required to load all sections to be loaded
150 // and pass this information to the memory manager
151 if (MemMgr->needsToReserveAllocationSpace()) {
152 uint64_t CodeSize = 0, DataSizeRO = 0, DataSizeRW = 0;
153 computeTotalAllocSize(*Obj, CodeSize, DataSizeRO, DataSizeRW);
154 MemMgr->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
157 // Symbols found in this object
158 StringMap<SymbolLoc> LocalSymbols;
159 // Used sections from the object file
160 ObjSectionToIDMap LocalSections;
162 // Common symbols requiring allocation, with their sizes and alignments
163 CommonSymbolMap CommonSymbols;
164 // Maximum required total memory to allocate all common symbols
165 uint64_t CommonSize = 0;
168 DEBUG(dbgs() << "Parse symbols:\n");
169 for (symbol_iterator I = Obj->begin_symbols(), E = Obj->end_symbols(); I != E;
171 object::SymbolRef::Type SymType;
173 Check(I->getType(SymType));
174 Check(I->getName(Name));
176 uint32_t Flags = I->getFlags();
178 bool IsCommon = Flags & SymbolRef::SF_Common;
180 // Add the common symbols to a list. We'll allocate them all below.
181 if (!GlobalSymbolTable.count(Name)) {
183 Check(I->getAlignment(Align));
185 Check(I->getSize(Size));
186 CommonSize += Size + Align;
187 CommonSymbols[*I] = CommonSymbolInfo(Size, Align);
190 if (SymType == object::SymbolRef::ST_Function ||
191 SymType == object::SymbolRef::ST_Data ||
192 SymType == object::SymbolRef::ST_Unknown) {
194 StringRef SectionData;
196 section_iterator SI = Obj->end_sections();
197 Check(getOffset(*I, SectOffset));
198 Check(I->getSection(SI));
199 if (SI == Obj->end_sections())
201 Check(SI->getContents(SectionData));
202 Check(SI->isText(IsCode));
204 findOrEmitSection(*Obj, *SI, IsCode, LocalSections);
205 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
206 DEBUG(dbgs() << "\tOffset: " << format("%p", (uintptr_t)SectOffset)
207 << " flags: " << Flags << " SID: " << SectionID);
208 GlobalSymbolTable[Name] = SymbolLoc(SectionID, SectOffset);
211 DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
214 // Allocate common symbols
216 emitCommonSymbols(*Obj, CommonSymbols, CommonSize, GlobalSymbolTable);
218 // Parse and process relocations
219 DEBUG(dbgs() << "Parse relocations:\n");
220 for (section_iterator SI = Obj->begin_sections(), SE = Obj->end_sections();
222 unsigned SectionID = 0;
224 section_iterator RelocatedSection = SI->getRelocatedSection();
226 relocation_iterator I = SI->relocation_begin();
227 relocation_iterator E = SI->relocation_end();
229 if (I == E && !ProcessAllSections)
233 Check(RelocatedSection->isText(IsCode));
235 findOrEmitSection(*Obj, *RelocatedSection, IsCode, LocalSections);
236 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
239 I = processRelocationRef(SectionID, I, *Obj, LocalSections, LocalSymbols,
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->getImageName(), SectionID, Stubs);
248 // Give the subclasses a chance to tie-up any loose ends.
249 finalizeLoad(*Obj, LocalSections);
251 return Obj.release();
254 // A helper method for computeTotalAllocSize.
255 // Computes the memory size required to allocate sections with the given sizes,
256 // assuming that all sections are allocated with the given alignment
258 computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
259 uint64_t Alignment) {
260 uint64_t TotalSize = 0;
261 for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
262 uint64_t AlignedSize =
263 (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
264 TotalSize += AlignedSize;
269 // Compute an upper bound of the memory size that is required to load all
271 void RuntimeDyldImpl::computeTotalAllocSize(ObjectImage &Obj,
273 uint64_t &DataSizeRO,
274 uint64_t &DataSizeRW) {
275 // Compute the size of all sections required for execution
276 std::vector<uint64_t> CodeSectionSizes;
277 std::vector<uint64_t> ROSectionSizes;
278 std::vector<uint64_t> RWSectionSizes;
279 uint64_t MaxAlignment = sizeof(void *);
281 // Collect sizes of all sections to be loaded;
282 // also determine the max alignment of all sections
283 for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
285 const SectionRef &Section = *SI;
288 Check(Section.isRequiredForExecution(IsRequired));
290 // Consider only the sections that are required to be loaded for execution
292 uint64_t DataSize = 0;
293 uint64_t Alignment64 = 0;
295 bool IsReadOnly = false;
297 Check(Section.getSize(DataSize));
298 Check(Section.getAlignment(Alignment64));
299 Check(Section.isText(IsCode));
300 Check(Section.isReadOnlyData(IsReadOnly));
301 Check(Section.getName(Name));
302 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
304 uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
305 uint64_t SectionSize = DataSize + StubBufSize;
307 // The .eh_frame section (at least on Linux) needs an extra four bytes
309 // with zeroes added at the end. For MachO objects, this section has a
310 // slightly different name, so this won't have any effect for MachO
312 if (Name == ".eh_frame")
315 if (SectionSize > 0) {
316 // save the total size of the section
318 CodeSectionSizes.push_back(SectionSize);
319 } else if (IsReadOnly) {
320 ROSectionSizes.push_back(SectionSize);
322 RWSectionSizes.push_back(SectionSize);
324 // update the max alignment
325 if (Alignment > MaxAlignment) {
326 MaxAlignment = Alignment;
332 // Compute the size of all common symbols
333 uint64_t CommonSize = 0;
334 for (symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols(); I != E;
336 uint32_t Flags = I->getFlags();
337 if (Flags & SymbolRef::SF_Common) {
338 // Add the common symbols to a list. We'll allocate them all below.
340 Check(I->getSize(Size));
344 if (CommonSize != 0) {
345 RWSectionSizes.push_back(CommonSize);
348 // Compute the required allocation space for each different type of sections
349 // (code, read-only data, read-write data) assuming that all sections are
350 // allocated with the max alignment. Note that we cannot compute with the
351 // individual alignments of the sections, because then the required size
352 // depends on the order, in which the sections are allocated.
353 CodeSize = computeAllocationSizeForSections(CodeSectionSizes, MaxAlignment);
354 DataSizeRO = computeAllocationSizeForSections(ROSectionSizes, MaxAlignment);
355 DataSizeRW = computeAllocationSizeForSections(RWSectionSizes, MaxAlignment);
358 // compute stub buffer size for the given section
359 unsigned RuntimeDyldImpl::computeSectionStubBufSize(ObjectImage &Obj,
360 const SectionRef &Section) {
361 unsigned StubSize = getMaxStubSize();
365 // FIXME: this is an inefficient way to handle this. We should computed the
366 // necessary section allocation size in loadObject by walking all the sections
368 unsigned StubBufSize = 0;
369 for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
371 section_iterator RelSecI = SI->getRelocatedSection();
372 if (!(RelSecI == Section))
375 for (const RelocationRef &Reloc : SI->relocations()) {
377 StubBufSize += StubSize;
381 // Get section data size and alignment
382 uint64_t Alignment64;
384 Check(Section.getSize(DataSize));
385 Check(Section.getAlignment(Alignment64));
387 // Add stubbuf size alignment
388 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
389 unsigned StubAlignment = getStubAlignment();
390 unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
391 if (StubAlignment > EndAlignment)
392 StubBufSize += StubAlignment - EndAlignment;
396 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
397 const CommonSymbolMap &CommonSymbols,
399 SymbolTableMap &SymbolTable) {
400 // Allocate memory for the section
401 unsigned SectionID = Sections.size();
402 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, sizeof(void *),
403 SectionID, StringRef(), false);
405 report_fatal_error("Unable to allocate memory for common symbols!");
407 Sections.push_back(SectionEntry("<common symbols>", Addr, TotalSize, 0));
408 memset(Addr, 0, TotalSize);
410 DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID << " new addr: "
411 << format("%p", Addr) << " DataSize: " << TotalSize << "\n");
413 // Assign the address of each symbol
414 for (CommonSymbolMap::const_iterator it = CommonSymbols.begin(),
415 itEnd = CommonSymbols.end(); it != itEnd; ++it) {
416 uint64_t Size = it->second.first;
417 uint64_t Align = it->second.second;
419 it->first.getName(Name);
421 // This symbol has an alignment requirement.
422 uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
424 Offset += AlignOffset;
425 DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
426 << format("%p\n", Addr));
428 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
429 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
435 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
436 const SectionRef &Section, bool IsCode) {
439 uint64_t Alignment64;
440 Check(Section.getContents(data));
441 Check(Section.getAlignment(Alignment64));
443 unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
449 unsigned PaddingSize = 0;
450 unsigned StubBufSize = 0;
452 Check(Section.isRequiredForExecution(IsRequired));
453 Check(Section.isVirtual(IsVirtual));
454 Check(Section.isZeroInit(IsZeroInit));
455 Check(Section.isReadOnlyData(IsReadOnly));
456 Check(Section.getSize(DataSize));
457 Check(Section.getName(Name));
459 StubBufSize = computeSectionStubBufSize(Obj, Section);
461 // The .eh_frame section (at least on Linux) needs an extra four bytes padded
462 // with zeroes added at the end. For MachO objects, this section has a
463 // slightly different name, so this won't have any effect for MachO objects.
464 if (Name == ".eh_frame")
468 unsigned SectionID = Sections.size();
470 const char *pData = nullptr;
472 // Some sections, such as debug info, don't need to be loaded for execution.
473 // Leave those where they are.
475 Allocate = DataSize + PaddingSize + StubBufSize;
476 Addr = IsCode ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID,
478 : MemMgr->allocateDataSection(Allocate, Alignment, SectionID,
481 report_fatal_error("Unable to allocate section memory!");
483 // Virtual sections have no data in the object image, so leave pData = 0
487 // Zero-initialize or copy the data from the image
488 if (IsZeroInit || IsVirtual)
489 memset(Addr, 0, DataSize);
491 memcpy(Addr, pData, DataSize);
493 // Fill in any extra bytes we allocated for padding
494 if (PaddingSize != 0) {
495 memset(Addr + DataSize, 0, PaddingSize);
496 // Update the DataSize variable so that the stub offset is set correctly.
497 DataSize += PaddingSize;
500 DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
501 << " obj addr: " << format("%p", pData)
502 << " new addr: " << format("%p", Addr)
503 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
504 << " Allocate: " << Allocate << "\n");
505 Obj.updateSectionAddress(Section, (uint64_t)Addr);
507 // Even if we didn't load the section, we need to record an entry for it
508 // to handle later processing (and by 'handle' I mean don't do anything
509 // with these sections).
512 DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
513 << " obj addr: " << format("%p", data.data()) << " new addr: 0"
514 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
515 << " Allocate: " << Allocate << "\n");
518 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
522 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
523 const SectionRef &Section,
525 ObjSectionToIDMap &LocalSections) {
527 unsigned SectionID = 0;
528 ObjSectionToIDMap::iterator i = LocalSections.find(Section);
529 if (i != LocalSections.end())
530 SectionID = i->second;
532 SectionID = emitSection(Obj, Section, IsCode);
533 LocalSections[Section] = SectionID;
538 void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
539 unsigned SectionID) {
540 Relocations[SectionID].push_back(RE);
543 void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
544 StringRef SymbolName) {
545 // Relocation by symbol. If the symbol is found in the global symbol table,
546 // create an appropriate section relocation. Otherwise, add it to
547 // ExternalSymbolRelocations.
548 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
549 if (Loc == GlobalSymbolTable.end()) {
550 ExternalSymbolRelocations[SymbolName].push_back(RE);
552 // Copy the RE since we want to modify its addend.
553 RelocationEntry RECopy = RE;
554 RECopy.Addend += Loc->second.second;
555 Relocations[Loc->second.first].push_back(RECopy);
559 uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
560 unsigned AbiVariant) {
561 if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
562 // This stub has to be able to access the full address space,
563 // since symbol lookup won't necessarily find a handy, in-range,
564 // PLT stub for functions which could be anywhere.
565 uint32_t *StubAddr = (uint32_t *)Addr;
567 // Stub can use ip0 (== x16) to calculate address
568 *StubAddr = 0xd2e00010; // movz ip0, #:abs_g3:<addr>
570 *StubAddr = 0xf2c00010; // movk ip0, #:abs_g2_nc:<addr>
572 *StubAddr = 0xf2a00010; // movk ip0, #:abs_g1_nc:<addr>
574 *StubAddr = 0xf2800010; // movk ip0, #:abs_g0_nc:<addr>
576 *StubAddr = 0xd61f0200; // br ip0
579 } else if (Arch == Triple::arm || Arch == Triple::armeb) {
580 // TODO: There is only ARM far stub now. We should add the Thumb stub,
581 // and stubs for branches Thumb - ARM and ARM - Thumb.
582 uint32_t *StubAddr = (uint32_t *)Addr;
583 *StubAddr = 0xe51ff004; // ldr pc,<label>
584 return (uint8_t *)++StubAddr;
585 } else if (Arch == Triple::mipsel || Arch == Triple::mips) {
586 uint32_t *StubAddr = (uint32_t *)Addr;
587 // 0: 3c190000 lui t9,%hi(addr).
588 // 4: 27390000 addiu t9,t9,%lo(addr).
589 // 8: 03200008 jr t9.
591 const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
592 const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
594 *StubAddr = LuiT9Instr;
596 *StubAddr = AdduiT9Instr;
598 *StubAddr = JrT9Instr;
600 *StubAddr = NopInstr;
602 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
603 // Depending on which version of the ELF ABI is in use, we need to
604 // generate one of two variants of the stub. They both start with
605 // the same sequence to load the target address into r12.
606 writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
607 writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
608 writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
609 writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
610 writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
611 if (AbiVariant == 2) {
612 // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
613 // The address is already in r12 as required by the ABI. Branch to it.
614 writeInt32BE(Addr+20, 0xF8410018); // std r2, 24(r1)
615 writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
616 writeInt32BE(Addr+28, 0x4E800420); // bctr
618 // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
619 // Load the function address on r11 and sets it to control register. Also
620 // loads the function TOC in r2 and environment pointer to r11.
621 writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
622 writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
623 writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
624 writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
625 writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
626 writeInt32BE(Addr+40, 0x4E800420); // bctr
629 } else if (Arch == Triple::systemz) {
630 writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
631 writeInt16BE(Addr+2, 0x0000);
632 writeInt16BE(Addr+4, 0x0004);
633 writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
634 // 8-byte address stored at Addr + 8
636 } else if (Arch == Triple::x86_64) {
638 *(Addr+1) = 0x25; // rip
639 // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
640 } else if (Arch == Triple::x86) {
641 *Addr = 0xE9; // 32-bit pc-relative jump.
646 // Assign an address to a symbol name and resolve all the relocations
647 // associated with it.
648 void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
650 // The address to use for relocation resolution is not
651 // the address of the local section buffer. We must be doing
652 // a remote execution environment of some sort. Relocations can't
653 // be applied until all the sections have been moved. The client must
654 // trigger this with a call to MCJIT::finalize() or
655 // RuntimeDyld::resolveRelocations().
657 // Addr is a uint64_t because we can't assume the pointer width
658 // of the target is the same as that of the host. Just use a generic
659 // "big enough" type.
660 Sections[SectionID].LoadAddress = Addr;
663 void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
665 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
666 const RelocationEntry &RE = Relocs[i];
667 // Ignore relocations for sections that were not loaded
668 if (Sections[RE.SectionID].Address == nullptr)
670 resolveRelocation(RE, Value);
674 void RuntimeDyldImpl::resolveExternalSymbols() {
675 while (!ExternalSymbolRelocations.empty()) {
676 StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
678 StringRef Name = i->first();
679 if (Name.size() == 0) {
680 // This is an absolute symbol, use an address of zero.
681 DEBUG(dbgs() << "Resolving absolute relocations."
683 RelocationList &Relocs = i->second;
684 resolveRelocationList(Relocs, 0);
687 SymbolTableMap::const_iterator Loc = GlobalSymbolTable.find(Name);
688 if (Loc == GlobalSymbolTable.end()) {
689 // This is an external symbol, try to get its address from
691 Addr = MemMgr->getSymbolAddress(Name.data());
692 // The call to getSymbolAddress may have caused additional modules to
693 // be loaded, which may have added new entries to the
694 // ExternalSymbolRelocations map. Consquently, we need to update our
695 // iterator. This is also why retrieval of the relocation list
696 // associated with this symbol is deferred until below this point.
697 // New entries may have been added to the relocation list.
698 i = ExternalSymbolRelocations.find(Name);
700 // We found the symbol in our global table. It was probably in a
701 // Module that we loaded previously.
702 SymbolLoc SymLoc = Loc->second;
703 Addr = getSectionLoadAddress(SymLoc.first) + SymLoc.second;
706 // FIXME: Implement error handling that doesn't kill the host program!
708 report_fatal_error("Program used external function '" + Name +
709 "' which could not be resolved!");
711 updateGOTEntries(Name, Addr);
712 DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
713 << format("0x%lx", Addr) << "\n");
714 // This list may have been updated when we called getSymbolAddress, so
715 // don't change this code to get the list earlier.
716 RelocationList &Relocs = i->second;
717 resolveRelocationList(Relocs, Addr);
720 ExternalSymbolRelocations.erase(i);
724 //===----------------------------------------------------------------------===//
725 // RuntimeDyld class implementation
726 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
727 // FIXME: There's a potential issue lurking here if a single instance of
728 // RuntimeDyld is used to load multiple objects. The current implementation
729 // associates a single memory manager with a RuntimeDyld instance. Even
730 // though the public class spawns a new 'impl' instance for each load,
731 // they share a single memory manager. This can become a problem when page
732 // permissions are applied.
735 ProcessAllSections = false;
739 RuntimeDyld::~RuntimeDyld() { delete Dyld; }
741 static std::unique_ptr<RuntimeDyldELF>
742 createRuntimeDyldELF(RTDyldMemoryManager *MM, bool ProcessAllSections,
743 RuntimeDyldCheckerImpl *Checker) {
744 std::unique_ptr<RuntimeDyldELF> Dyld(new RuntimeDyldELF(MM));
745 Dyld->setProcessAllSections(ProcessAllSections);
746 Dyld->setRuntimeDyldChecker(Checker);
750 static std::unique_ptr<RuntimeDyldMachO>
751 createRuntimeDyldMachO(Triple::ArchType Arch, RTDyldMemoryManager *MM,
752 bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
753 std::unique_ptr<RuntimeDyldMachO> Dyld(RuntimeDyldMachO::create(Arch, MM));
754 Dyld->setProcessAllSections(ProcessAllSections);
755 Dyld->setRuntimeDyldChecker(Checker);
759 ObjectImage *RuntimeDyld::loadObject(std::unique_ptr<ObjectFile> InputObject) {
760 std::unique_ptr<ObjectImage> InputImage;
762 ObjectFile &Obj = *InputObject;
764 if (InputObject->isELF()) {
765 InputImage.reset(RuntimeDyldELF::createObjectImageFromFile(std::move(InputObject)));
767 Dyld = createRuntimeDyldELF(MM, ProcessAllSections, Checker).release();
768 } else if (InputObject->isMachO()) {
769 InputImage.reset(RuntimeDyldMachO::createObjectImageFromFile(std::move(InputObject)));
771 Dyld = createRuntimeDyldMachO(
772 static_cast<Triple::ArchType>(InputImage->getArch()),
773 MM, ProcessAllSections, Checker).release();
775 report_fatal_error("Incompatible object format!");
777 if (!Dyld->isCompatibleFile(&Obj))
778 report_fatal_error("Incompatible object format!");
780 Dyld->loadObject(InputImage.get());
781 return InputImage.release();
784 ObjectImage *RuntimeDyld::loadObject(ObjectBuffer *InputBuffer) {
785 std::unique_ptr<ObjectImage> InputImage;
786 sys::fs::file_magic Type = sys::fs::identify_magic(InputBuffer->getBuffer());
789 case sys::fs::file_magic::elf_relocatable:
790 case sys::fs::file_magic::elf_executable:
791 case sys::fs::file_magic::elf_shared_object:
792 case sys::fs::file_magic::elf_core:
793 InputImage.reset(RuntimeDyldELF::createObjectImage(InputBuffer));
795 Dyld = createRuntimeDyldELF(MM, ProcessAllSections, Checker).release();
797 case sys::fs::file_magic::macho_object:
798 case sys::fs::file_magic::macho_executable:
799 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
800 case sys::fs::file_magic::macho_core:
801 case sys::fs::file_magic::macho_preload_executable:
802 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
803 case sys::fs::file_magic::macho_dynamic_linker:
804 case sys::fs::file_magic::macho_bundle:
805 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
806 case sys::fs::file_magic::macho_dsym_companion:
807 InputImage.reset(RuntimeDyldMachO::createObjectImage(InputBuffer));
809 Dyld = createRuntimeDyldMachO(
810 static_cast<Triple::ArchType>(InputImage->getArch()),
811 MM, ProcessAllSections, Checker).release();
813 case sys::fs::file_magic::unknown:
814 case sys::fs::file_magic::bitcode:
815 case sys::fs::file_magic::archive:
816 case sys::fs::file_magic::coff_object:
817 case sys::fs::file_magic::coff_import_library:
818 case sys::fs::file_magic::pecoff_executable:
819 case sys::fs::file_magic::macho_universal_binary:
820 case sys::fs::file_magic::windows_resource:
821 report_fatal_error("Incompatible object format!");
824 if (!Dyld->isCompatibleFormat(InputBuffer))
825 report_fatal_error("Incompatible object format!");
827 Dyld->loadObject(InputImage.get());
828 return InputImage.release();
831 void *RuntimeDyld::getSymbolAddress(StringRef Name) {
834 return Dyld->getSymbolAddress(Name);
837 uint64_t RuntimeDyld::getSymbolLoadAddress(StringRef Name) {
840 return Dyld->getSymbolLoadAddress(Name);
843 void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
845 void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
846 Dyld->reassignSectionAddress(SectionID, Addr);
849 void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
850 uint64_t TargetAddress) {
851 Dyld->mapSectionAddress(LocalAddress, TargetAddress);
854 bool RuntimeDyld::hasError() { return Dyld->hasError(); }
856 StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
858 void RuntimeDyld::registerEHFrames() {
860 Dyld->registerEHFrames();
863 void RuntimeDyld::deregisterEHFrames() {
865 Dyld->deregisterEHFrames();
868 } // end namespace llvm