1 //===-- RuntimeDyldELF.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 ELF support for the MC-JIT runtime dynamic linker.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dyld"
15 #include "RuntimeDyldELF.h"
16 #include "JITRegistrar.h"
17 #include "ObjectImageCommon.h"
18 #include "llvm/ADT/IntervalMap.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ExecutionEngine/ObjectBuffer.h"
24 #include "llvm/ExecutionEngine/ObjectImage.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Object/ObjectFile.h"
27 #include "llvm/Support/ELF.h"
28 #include "llvm/Support/MemoryBuffer.h"
31 using namespace llvm::object;
36 error_code check(error_code Err) {
38 report_fatal_error(Err.message());
45 : public ELFObjectFile<ELFT> {
46 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
48 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
49 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
51 Elf_Rel_Impl<ELFT, false> Elf_Rel;
53 Elf_Rel_Impl<ELFT, true> Elf_Rela;
55 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
57 typedef typename ELFDataTypeTypedefHelper<
58 ELFT>::value_type addr_type;
61 DyldELFObject(MemoryBuffer *Wrapper, error_code &ec);
63 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
64 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr);
66 // Methods for type inquiry through isa, cast and dyn_cast
67 static inline bool classof(const Binary *v) {
68 return (isa<ELFObjectFile<ELFT> >(v)
69 && classof(cast<ELFObjectFile
72 static inline bool classof(
73 const ELFObjectFile<ELFT> *v) {
74 return v->isDyldType();
79 class ELFObjectImage : public ObjectImageCommon {
81 DyldELFObject<ELFT> *DyldObj;
85 ELFObjectImage(ObjectBuffer *Input,
86 DyldELFObject<ELFT> *Obj)
87 : ObjectImageCommon(Input, Obj),
91 virtual ~ELFObjectImage() {
93 deregisterWithDebugger();
96 // Subclasses can override these methods to update the image with loaded
97 // addresses for sections and common symbols
98 virtual void updateSectionAddress(const SectionRef &Sec, uint64_t Addr)
100 DyldObj->updateSectionAddress(Sec, Addr);
103 virtual void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr)
105 DyldObj->updateSymbolAddress(Sym, Addr);
108 virtual void registerWithDebugger()
110 JITRegistrar::getGDBRegistrar().registerObject(*Buffer);
113 virtual void deregisterWithDebugger()
115 JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer);
119 // The MemoryBuffer passed into this constructor is just a wrapper around the
120 // actual memory. Ultimately, the Binary parent class will take ownership of
121 // this MemoryBuffer object but not the underlying memory.
123 DyldELFObject<ELFT>::DyldELFObject(MemoryBuffer *Wrapper, error_code &ec)
124 : ELFObjectFile<ELFT>(Wrapper, ec) {
125 this->isDyldELFObject = true;
129 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
131 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
132 Elf_Shdr *shdr = const_cast<Elf_Shdr*>(
133 reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
135 // This assumes the address passed in matches the target address bitness
136 // The template-based type cast handles everything else.
137 shdr->sh_addr = static_cast<addr_type>(Addr);
141 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
144 Elf_Sym *sym = const_cast<Elf_Sym*>(
145 ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
147 // This assumes the address passed in matches the target address bitness
148 // The template-based type cast handles everything else.
149 sym->st_value = static_cast<addr_type>(Addr);
156 void RuntimeDyldELF::registerEHFrames() {
159 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
160 SID EHFrameSID = UnregisteredEHFrameSections[i];
161 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
162 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
163 size_t EHFrameSize = Sections[EHFrameSID].Size;
164 MemMgr->registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
165 RegisteredEHFrameSections.push_back(EHFrameSID);
167 UnregisteredEHFrameSections.clear();
170 void RuntimeDyldELF::deregisterEHFrames() {
173 for (int i = 0, e = RegisteredEHFrameSections.size(); i != e; ++i) {
174 SID EHFrameSID = RegisteredEHFrameSections[i];
175 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
176 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
177 size_t EHFrameSize = Sections[EHFrameSID].Size;
178 MemMgr->deregisterEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
180 RegisteredEHFrameSections.clear();
183 ObjectImage *RuntimeDyldELF::createObjectImageFromFile(object::ObjectFile *ObjFile) {
188 MemoryBuffer* Buffer = MemoryBuffer::getMemBuffer(ObjFile->getData(),
192 if (ObjFile->getBytesInAddress() == 4 && ObjFile->isLittleEndian()) {
193 DyldELFObject<ELFType<support::little, 2, false> > *Obj =
194 new DyldELFObject<ELFType<support::little, 2, false> >(Buffer, ec);
195 return new ELFObjectImage<ELFType<support::little, 2, false> >(NULL, Obj);
197 else if (ObjFile->getBytesInAddress() == 4 && !ObjFile->isLittleEndian()) {
198 DyldELFObject<ELFType<support::big, 2, false> > *Obj =
199 new DyldELFObject<ELFType<support::big, 2, false> >(Buffer, ec);
200 return new ELFObjectImage<ELFType<support::big, 2, false> >(NULL, Obj);
202 else if (ObjFile->getBytesInAddress() == 8 && !ObjFile->isLittleEndian()) {
203 DyldELFObject<ELFType<support::big, 2, true> > *Obj =
204 new DyldELFObject<ELFType<support::big, 2, true> >(Buffer, ec);
205 return new ELFObjectImage<ELFType<support::big, 2, true> >(NULL, Obj);
207 else if (ObjFile->getBytesInAddress() == 8 && ObjFile->isLittleEndian()) {
208 DyldELFObject<ELFType<support::little, 2, true> > *Obj =
209 new DyldELFObject<ELFType<support::little, 2, true> >(Buffer, ec);
210 return new ELFObjectImage<ELFType<support::little, 2, true> >(NULL, Obj);
213 llvm_unreachable("Unexpected ELF format");
216 ObjectImage *RuntimeDyldELF::createObjectImage(ObjectBuffer *Buffer) {
217 if (Buffer->getBufferSize() < ELF::EI_NIDENT)
218 llvm_unreachable("Unexpected ELF object size");
219 std::pair<unsigned char, unsigned char> Ident = std::make_pair(
220 (uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS],
221 (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
224 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) {
225 DyldELFObject<ELFType<support::little, 4, false> > *Obj =
226 new DyldELFObject<ELFType<support::little, 4, false> >(
227 Buffer->getMemBuffer(), ec);
228 return new ELFObjectImage<ELFType<support::little, 4, false> >(Buffer, Obj);
230 else if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB) {
231 DyldELFObject<ELFType<support::big, 4, false> > *Obj =
232 new DyldELFObject<ELFType<support::big, 4, false> >(
233 Buffer->getMemBuffer(), ec);
234 return new ELFObjectImage<ELFType<support::big, 4, false> >(Buffer, Obj);
236 else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB) {
237 DyldELFObject<ELFType<support::big, 8, true> > *Obj =
238 new DyldELFObject<ELFType<support::big, 8, true> >(
239 Buffer->getMemBuffer(), ec);
240 return new ELFObjectImage<ELFType<support::big, 8, true> >(Buffer, Obj);
242 else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB) {
243 DyldELFObject<ELFType<support::little, 8, true> > *Obj =
244 new DyldELFObject<ELFType<support::little, 8, true> >(
245 Buffer->getMemBuffer(), ec);
246 return new ELFObjectImage<ELFType<support::little, 8, true> >(Buffer, Obj);
249 llvm_unreachable("Unexpected ELF format");
252 RuntimeDyldELF::~RuntimeDyldELF() {
255 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
260 uint64_t SymOffset) {
263 llvm_unreachable("Relocation type not implemented yet!");
265 case ELF::R_X86_64_64: {
266 uint64_t *Target = reinterpret_cast<uint64_t*>(Section.Address + Offset);
267 *Target = Value + Addend;
268 DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend))
269 << " at " << format("%p\n",Target));
272 case ELF::R_X86_64_32:
273 case ELF::R_X86_64_32S: {
275 assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
276 (Type == ELF::R_X86_64_32S &&
277 ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
278 uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
279 uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
280 *Target = TruncatedAddr;
281 DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr)
282 << " at " << format("%p\n",Target));
285 case ELF::R_X86_64_GOTPCREL: {
286 // findGOTEntry returns the 'G + GOT' part of the relocation calculation
287 // based on the load/target address of the GOT (not the current/local addr).
288 uint64_t GOTAddr = findGOTEntry(Value, SymOffset);
289 uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
290 uint64_t FinalAddress = Section.LoadAddress + Offset;
291 // The processRelocationRef method combines the symbol offset and the addend
292 // and in most cases that's what we want. For this relocation type, we need
293 // the raw addend, so we subtract the symbol offset to get it.
294 int64_t RealOffset = GOTAddr + Addend - SymOffset - FinalAddress;
295 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
296 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
297 *Target = TruncOffset;
300 case ELF::R_X86_64_PC32: {
301 // Get the placeholder value from the generated object since
302 // a previous relocation attempt may have overwritten the loaded version
303 uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
305 uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
306 uint64_t FinalAddress = Section.LoadAddress + Offset;
307 int64_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
308 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
309 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
310 *Target = TruncOffset;
313 case ELF::R_X86_64_PC64: {
314 // Get the placeholder value from the generated object since
315 // a previous relocation attempt may have overwritten the loaded version
316 uint64_t *Placeholder = reinterpret_cast<uint64_t*>(Section.ObjAddress
318 uint64_t *Target = reinterpret_cast<uint64_t*>(Section.Address + Offset);
319 uint64_t FinalAddress = Section.LoadAddress + Offset;
320 *Target = *Placeholder + Value + Addend - FinalAddress;
326 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
332 case ELF::R_386_32: {
333 // Get the placeholder value from the generated object since
334 // a previous relocation attempt may have overwritten the loaded version
335 uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
337 uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
338 *Target = *Placeholder + Value + Addend;
341 case ELF::R_386_PC32: {
342 // Get the placeholder value from the generated object since
343 // a previous relocation attempt may have overwritten the loaded version
344 uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
346 uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
347 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
348 uint32_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
349 *Target = RealOffset;
353 // There are other relocation types, but it appears these are the
354 // only ones currently used by the LLVM ELF object writer
355 llvm_unreachable("Relocation type not implemented yet!");
360 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
365 uint32_t *TargetPtr = reinterpret_cast<uint32_t*>(Section.Address + Offset);
366 uint64_t FinalAddress = Section.LoadAddress + Offset;
368 DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
369 << format("%llx", Section.Address + Offset)
370 << " FinalAddress: 0x" << format("%llx",FinalAddress)
371 << " Value: 0x" << format("%llx",Value)
372 << " Type: 0x" << format("%x",Type)
373 << " Addend: 0x" << format("%llx",Addend)
378 llvm_unreachable("Relocation type not implemented yet!");
380 case ELF::R_AARCH64_ABS64: {
381 uint64_t *TargetPtr = reinterpret_cast<uint64_t*>(Section.Address + Offset);
382 *TargetPtr = Value + Addend;
385 case ELF::R_AARCH64_PREL32: {
386 uint64_t Result = Value + Addend - FinalAddress;
387 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
388 static_cast<int64_t>(Result) <= UINT32_MAX);
389 *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU);
392 case ELF::R_AARCH64_CALL26: // fallthrough
393 case ELF::R_AARCH64_JUMP26: {
394 // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
396 uint64_t BranchImm = Value + Addend - FinalAddress;
398 // "Check that -2^27 <= result < 2^27".
399 assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) &&
400 static_cast<int64_t>(BranchImm) < (1LL << 27));
402 // AArch64 code is emitted with .rela relocations. The data already in any
403 // bits affected by the relocation on entry is garbage.
404 *TargetPtr &= 0xfc000000U;
405 // Immediate goes in bits 25:0 of B and BL.
406 *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2;
409 case ELF::R_AARCH64_MOVW_UABS_G3: {
410 uint64_t Result = Value + Addend;
412 // AArch64 code is emitted with .rela relocations. The data already in any
413 // bits affected by the relocation on entry is garbage.
414 *TargetPtr &= 0xffe0001fU;
415 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
416 *TargetPtr |= Result >> (48 - 5);
417 // Shift must be "lsl #48", in bits 22:21
418 assert((*TargetPtr >> 21 & 0x3) == 3 && "invalid shift for relocation");
421 case ELF::R_AARCH64_MOVW_UABS_G2_NC: {
422 uint64_t Result = Value + Addend;
424 // AArch64 code is emitted with .rela relocations. The data already in any
425 // bits affected by the relocation on entry is garbage.
426 *TargetPtr &= 0xffe0001fU;
427 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
428 *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5));
429 // Shift must be "lsl #32", in bits 22:21
430 assert((*TargetPtr >> 21 & 0x3) == 2 && "invalid shift for relocation");
433 case ELF::R_AARCH64_MOVW_UABS_G1_NC: {
434 uint64_t Result = Value + Addend;
436 // AArch64 code is emitted with .rela relocations. The data already in any
437 // bits affected by the relocation on entry is garbage.
438 *TargetPtr &= 0xffe0001fU;
439 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
440 *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5));
441 // Shift must be "lsl #16", in bits 22:2
442 assert((*TargetPtr >> 21 & 0x3) == 1 && "invalid shift for relocation");
445 case ELF::R_AARCH64_MOVW_UABS_G0_NC: {
446 uint64_t Result = Value + Addend;
448 // AArch64 code is emitted with .rela relocations. The data already in any
449 // bits affected by the relocation on entry is garbage.
450 *TargetPtr &= 0xffe0001fU;
451 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
452 *TargetPtr |= ((Result & 0xffffU) << 5);
453 // Shift must be "lsl #0", in bits 22:21.
454 assert((*TargetPtr >> 21 & 0x3) == 0 && "invalid shift for relocation");
460 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
465 // TODO: Add Thumb relocations.
466 uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress +
468 uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
469 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
472 DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
473 << Section.Address + Offset
474 << " FinalAddress: " << format("%p",FinalAddress)
475 << " Value: " << format("%x",Value)
476 << " Type: " << format("%x",Type)
477 << " Addend: " << format("%x",Addend)
482 llvm_unreachable("Not implemented relocation type!");
484 case ELF::R_ARM_NONE:
486 // Write a 32bit value to relocation address, taking into account the
487 // implicit addend encoded in the target.
488 case ELF::R_ARM_PREL31:
489 case ELF::R_ARM_TARGET1:
490 case ELF::R_ARM_ABS32:
491 *TargetPtr = *Placeholder + Value;
493 // Write first 16 bit of 32 bit value to the mov instruction.
494 // Last 4 bit should be shifted.
495 case ELF::R_ARM_MOVW_ABS_NC:
496 // We are not expecting any other addend in the relocation address.
497 // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
498 // non-contiguous fields.
499 assert((*Placeholder & 0x000F0FFF) == 0);
500 Value = Value & 0xFFFF;
501 *TargetPtr = *Placeholder | (Value & 0xFFF);
502 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
504 // Write last 16 bit of 32 bit value to the mov instruction.
505 // Last 4 bit should be shifted.
506 case ELF::R_ARM_MOVT_ABS:
507 // We are not expecting any other addend in the relocation address.
508 // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
509 assert((*Placeholder & 0x000F0FFF) == 0);
511 Value = (Value >> 16) & 0xFFFF;
512 *TargetPtr = *Placeholder | (Value & 0xFFF);
513 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
515 // Write 24 bit relative value to the branch instruction.
516 case ELF::R_ARM_PC24 : // Fall through.
517 case ELF::R_ARM_CALL : // Fall through.
518 case ELF::R_ARM_JUMP24: {
519 int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
520 RelValue = (RelValue & 0x03FFFFFC) >> 2;
521 assert((*TargetPtr & 0xFFFFFF) == 0xFFFFFE);
522 *TargetPtr &= 0xFF000000;
523 *TargetPtr |= RelValue;
526 case ELF::R_ARM_PRIVATE_0:
527 // This relocation is reserved by the ARM ELF ABI for internal use. We
528 // appropriate it here to act as an R_ARM_ABS32 without any addend for use
529 // in the stubs created during JIT (which can't put an addend into the
530 // original object file).
536 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
541 uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress +
543 uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
546 DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
547 << Section.Address + Offset
549 << format("%p",Section.LoadAddress + Offset)
550 << " Value: " << format("%x",Value)
551 << " Type: " << format("%x",Type)
552 << " Addend: " << format("%x",Addend)
557 llvm_unreachable("Not implemented relocation type!");
560 *TargetPtr = Value + (*Placeholder);
563 *TargetPtr = ((*Placeholder) & 0xfc000000) | (( Value & 0x0fffffff) >> 2);
565 case ELF::R_MIPS_HI16:
566 // Get the higher 16-bits. Also add 1 if bit 15 is 1.
567 Value += ((*Placeholder) & 0x0000ffff) << 16;
568 *TargetPtr = ((*Placeholder) & 0xffff0000) |
569 (((Value + 0x8000) >> 16) & 0xffff);
571 case ELF::R_MIPS_LO16:
572 Value += ((*Placeholder) & 0x0000ffff);
573 *TargetPtr = ((*Placeholder) & 0xffff0000) | (Value & 0xffff);
575 case ELF::R_MIPS_UNUSED1:
576 // Similar to ELF::R_ARM_PRIVATE_0, R_MIPS_UNUSED1 and R_MIPS_UNUSED2
577 // are used for internal JIT purpose. These relocations are similar to
578 // R_MIPS_HI16 and R_MIPS_LO16, but they do not take any addend into
580 *TargetPtr = ((*TargetPtr) & 0xffff0000) |
581 (((Value + 0x8000) >> 16) & 0xffff);
583 case ELF::R_MIPS_UNUSED2:
584 *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
589 // Return the .TOC. section address to R_PPC64_TOC relocations.
590 uint64_t RuntimeDyldELF::findPPC64TOC() const {
591 // The TOC consists of sections .got, .toc, .tocbss, .plt in that
592 // order. The TOC starts where the first of these sections starts.
593 SectionList::const_iterator it = Sections.begin();
594 SectionList::const_iterator ite = Sections.end();
595 for (; it != ite; ++it) {
596 if (it->Name == ".got" ||
597 it->Name == ".toc" ||
598 it->Name == ".tocbss" ||
603 // This may happen for
604 // * references to TOC base base (sym@toc, .odp relocation) without
606 // In this case just use the first section (which is usually
607 // the .odp) since the code won't reference the .toc base
609 it = Sections.begin();
612 // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
613 // thus permitting a full 64 Kbytes segment.
614 return it->LoadAddress + 0x8000;
617 // Returns the sections and offset associated with the ODP entry referenced
619 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
620 ObjSectionToIDMap &LocalSections,
621 RelocationValueRef &Rel) {
622 // Get the ELF symbol value (st_value) to compare with Relocation offset in
626 for (section_iterator si = Obj.begin_sections(),
627 se = Obj.end_sections(); si != se; si.increment(err)) {
628 section_iterator RelSecI = si->getRelocatedSection();
629 if (RelSecI == Obj.end_sections())
632 StringRef RelSectionName;
633 check(RelSecI->getName(RelSectionName));
634 if (RelSectionName != ".opd")
637 for (relocation_iterator i = si->begin_relocations(),
638 e = si->end_relocations(); i != e;) {
641 // The R_PPC64_ADDR64 relocation indicates the first field
644 check(i->getType(TypeFunc));
645 if (TypeFunc != ELF::R_PPC64_ADDR64) {
650 uint64_t TargetSymbolOffset;
651 symbol_iterator TargetSymbol = i->getSymbol();
652 check(i->getOffset(TargetSymbolOffset));
654 check(getELFRelocationAddend(*i, Addend));
656 i = i.increment(err);
661 // Just check if following relocation is a R_PPC64_TOC
663 check(i->getType(TypeTOC));
664 if (TypeTOC != ELF::R_PPC64_TOC)
667 // Finally compares the Symbol value and the target symbol offset
668 // to check if this .opd entry refers to the symbol the relocation
670 if (Rel.Addend != (int64_t)TargetSymbolOffset)
673 section_iterator tsi(Obj.end_sections());
674 check(TargetSymbol->getSection(tsi));
675 Rel.SectionID = findOrEmitSection(Obj, (*tsi), true, LocalSections);
676 Rel.Addend = (intptr_t)Addend;
680 llvm_unreachable("Attempting to get address of ODP entry!");
683 // Relocation masks following the #lo(value), #hi(value), #higher(value),
684 // and #highest(value) macros defined in section 4.5.1. Relocation Types
685 // in PPC-elf64abi document.
688 uint16_t applyPPClo (uint64_t value)
690 return value & 0xffff;
694 uint16_t applyPPChi (uint64_t value)
696 return (value >> 16) & 0xffff;
700 uint16_t applyPPChigher (uint64_t value)
702 return (value >> 32) & 0xffff;
706 uint16_t applyPPChighest (uint64_t value)
708 return (value >> 48) & 0xffff;
711 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
716 uint8_t* LocalAddress = Section.Address + Offset;
719 llvm_unreachable("Relocation type not implemented yet!");
721 case ELF::R_PPC64_ADDR16_LO :
722 writeInt16BE(LocalAddress, applyPPClo (Value + Addend));
724 case ELF::R_PPC64_ADDR16_HI :
725 writeInt16BE(LocalAddress, applyPPChi (Value + Addend));
727 case ELF::R_PPC64_ADDR16_HIGHER :
728 writeInt16BE(LocalAddress, applyPPChigher (Value + Addend));
730 case ELF::R_PPC64_ADDR16_HIGHEST :
731 writeInt16BE(LocalAddress, applyPPChighest (Value + Addend));
733 case ELF::R_PPC64_ADDR14 : {
734 assert(((Value + Addend) & 3) == 0);
735 // Preserve the AA/LK bits in the branch instruction
736 uint8_t aalk = *(LocalAddress+3);
737 writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
739 case ELF::R_PPC64_ADDR32 : {
740 int32_t Result = static_cast<int32_t>(Value + Addend);
741 if (SignExtend32<32>(Result) != Result)
742 llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
743 writeInt32BE(LocalAddress, Result);
745 case ELF::R_PPC64_REL24 : {
746 uint64_t FinalAddress = (Section.LoadAddress + Offset);
747 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
748 if (SignExtend32<24>(delta) != delta)
749 llvm_unreachable("Relocation R_PPC64_REL24 overflow");
750 // Generates a 'bl <address>' instruction
751 writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
753 case ELF::R_PPC64_REL32 : {
754 uint64_t FinalAddress = (Section.LoadAddress + Offset);
755 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
756 if (SignExtend32<32>(delta) != delta)
757 llvm_unreachable("Relocation R_PPC64_REL32 overflow");
758 writeInt32BE(LocalAddress, delta);
760 case ELF::R_PPC64_REL64: {
761 uint64_t FinalAddress = (Section.LoadAddress + Offset);
762 uint64_t Delta = Value - FinalAddress + Addend;
763 writeInt64BE(LocalAddress, Delta);
765 case ELF::R_PPC64_ADDR64 :
766 writeInt64BE(LocalAddress, Value + Addend);
768 case ELF::R_PPC64_TOC :
769 writeInt64BE(LocalAddress, findPPC64TOC());
771 case ELF::R_PPC64_TOC16 : {
772 uint64_t TOCStart = findPPC64TOC();
773 Value = applyPPClo((Value + Addend) - TOCStart);
774 writeInt16BE(LocalAddress, applyPPClo(Value));
776 case ELF::R_PPC64_TOC16_DS : {
777 uint64_t TOCStart = findPPC64TOC();
778 Value = ((Value + Addend) - TOCStart);
779 writeInt16BE(LocalAddress, applyPPClo(Value));
784 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
789 uint8_t *LocalAddress = Section.Address + Offset;
792 llvm_unreachable("Relocation type not implemented yet!");
794 case ELF::R_390_PC16DBL:
795 case ELF::R_390_PLT16DBL: {
796 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
797 assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
798 writeInt16BE(LocalAddress, Delta / 2);
801 case ELF::R_390_PC32DBL:
802 case ELF::R_390_PLT32DBL: {
803 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
804 assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
805 writeInt32BE(LocalAddress, Delta / 2);
808 case ELF::R_390_PC32: {
809 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
810 assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
811 writeInt32BE(LocalAddress, Delta);
815 writeInt64BE(LocalAddress, Value + Addend);
820 // The target location for the relocation is described by RE.SectionID and
821 // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
822 // SectionEntry has three members describing its location.
823 // SectionEntry::Address is the address at which the section has been loaded
824 // into memory in the current (host) process. SectionEntry::LoadAddress is the
825 // address that the section will have in the target process.
826 // SectionEntry::ObjAddress is the address of the bits for this section in the
827 // original emitted object image (also in the current address space).
829 // Relocations will be applied as if the section were loaded at
830 // SectionEntry::LoadAddress, but they will be applied at an address based
831 // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
832 // Target memory contents if they are required for value calculations.
834 // The Value parameter here is the load address of the symbol for the
835 // relocation to be applied. For relocations which refer to symbols in the
836 // current object Value will be the LoadAddress of the section in which
837 // the symbol resides (RE.Addend provides additional information about the
838 // symbol location). For external symbols, Value will be the address of the
839 // symbol in the target address space.
840 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
842 const SectionEntry &Section = Sections[RE.SectionID];
843 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
847 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
852 uint64_t SymOffset) {
855 resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
858 resolveX86Relocation(Section, Offset,
859 (uint32_t)(Value & 0xffffffffL), Type,
860 (uint32_t)(Addend & 0xffffffffL));
862 case Triple::aarch64:
863 resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
865 case Triple::arm: // Fall through.
867 resolveARMRelocation(Section, Offset,
868 (uint32_t)(Value & 0xffffffffL), Type,
869 (uint32_t)(Addend & 0xffffffffL));
871 case Triple::mips: // Fall through.
873 resolveMIPSRelocation(Section, Offset,
874 (uint32_t)(Value & 0xffffffffL), Type,
875 (uint32_t)(Addend & 0xffffffffL));
877 case Triple::ppc64: // Fall through.
878 case Triple::ppc64le:
879 resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
881 case Triple::systemz:
882 resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
884 default: llvm_unreachable("Unsupported CPU type!");
888 void RuntimeDyldELF::processRelocationRef(unsigned SectionID,
891 ObjSectionToIDMap &ObjSectionToID,
892 const SymbolTableMap &Symbols,
895 Check(RelI.getType(RelType));
897 Check(getELFRelocationAddend(RelI, Addend));
898 symbol_iterator Symbol = RelI.getSymbol();
900 // Obtain the symbol name which is referenced in the relocation
901 StringRef TargetName;
902 if (Symbol != Obj.end_symbols())
903 Symbol->getName(TargetName);
904 DEBUG(dbgs() << "\t\tRelType: " << RelType
905 << " Addend: " << Addend
906 << " TargetName: " << TargetName
908 RelocationValueRef Value;
909 // First search for the symbol in the local symbol table
910 SymbolTableMap::const_iterator lsi = Symbols.end();
911 SymbolRef::Type SymType = SymbolRef::ST_Unknown;
912 if (Symbol != Obj.end_symbols()) {
913 lsi = Symbols.find(TargetName.data());
914 Symbol->getType(SymType);
916 if (lsi != Symbols.end()) {
917 Value.SectionID = lsi->second.first;
918 Value.Offset = lsi->second.second;
919 Value.Addend = lsi->second.second + Addend;
921 // Search for the symbol in the global symbol table
922 SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end();
923 if (Symbol != Obj.end_symbols())
924 gsi = GlobalSymbolTable.find(TargetName.data());
925 if (gsi != GlobalSymbolTable.end()) {
926 Value.SectionID = gsi->second.first;
927 Value.Offset = gsi->second.second;
928 Value.Addend = gsi->second.second + Addend;
931 case SymbolRef::ST_Debug: {
932 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
933 // and can be changed by another developers. Maybe best way is add
934 // a new symbol type ST_Section to SymbolRef and use it.
935 section_iterator si(Obj.end_sections());
936 Symbol->getSection(si);
937 if (si == Obj.end_sections())
938 llvm_unreachable("Symbol section not found, bad object file format!");
939 DEBUG(dbgs() << "\t\tThis is section symbol\n");
940 // Default to 'true' in case isText fails (though it never does).
943 Value.SectionID = findOrEmitSection(Obj,
947 Value.Addend = Addend;
950 case SymbolRef::ST_Data:
951 case SymbolRef::ST_Unknown: {
952 Value.SymbolName = TargetName.data();
953 Value.Addend = Addend;
955 // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
956 // will manifest here as a NULL symbol name.
957 // We can set this as a valid (but empty) symbol name, and rely
958 // on addRelocationForSymbol to handle this.
959 if (!Value.SymbolName)
960 Value.SymbolName = "";
964 llvm_unreachable("Unresolved symbol type!");
970 Check(RelI.getOffset(Offset));
972 DEBUG(dbgs() << "\t\tSectionID: " << SectionID
973 << " Offset: " << Offset
975 if (Arch == Triple::aarch64 &&
976 (RelType == ELF::R_AARCH64_CALL26 ||
977 RelType == ELF::R_AARCH64_JUMP26)) {
978 // This is an AArch64 branch relocation, need to use a stub function.
979 DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
980 SectionEntry &Section = Sections[SectionID];
982 // Look for an existing stub.
983 StubMap::const_iterator i = Stubs.find(Value);
984 if (i != Stubs.end()) {
985 resolveRelocation(Section, Offset,
986 (uint64_t)Section.Address + i->second, RelType, 0);
987 DEBUG(dbgs() << " Stub function found\n");
989 // Create a new stub function.
990 DEBUG(dbgs() << " Create a new stub function\n");
991 Stubs[Value] = Section.StubOffset;
992 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
995 RelocationEntry REmovz_g3(SectionID,
996 StubTargetAddr - Section.Address,
997 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
998 RelocationEntry REmovk_g2(SectionID,
999 StubTargetAddr - Section.Address + 4,
1000 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
1001 RelocationEntry REmovk_g1(SectionID,
1002 StubTargetAddr - Section.Address + 8,
1003 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
1004 RelocationEntry REmovk_g0(SectionID,
1005 StubTargetAddr - Section.Address + 12,
1006 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
1008 if (Value.SymbolName) {
1009 addRelocationForSymbol(REmovz_g3, Value.SymbolName);
1010 addRelocationForSymbol(REmovk_g2, Value.SymbolName);
1011 addRelocationForSymbol(REmovk_g1, Value.SymbolName);
1012 addRelocationForSymbol(REmovk_g0, Value.SymbolName);
1014 addRelocationForSection(REmovz_g3, Value.SectionID);
1015 addRelocationForSection(REmovk_g2, Value.SectionID);
1016 addRelocationForSection(REmovk_g1, Value.SectionID);
1017 addRelocationForSection(REmovk_g0, Value.SectionID);
1019 resolveRelocation(Section, Offset,
1020 (uint64_t)Section.Address + Section.StubOffset,
1022 Section.StubOffset += getMaxStubSize();
1024 } else if (Arch == Triple::arm &&
1025 (RelType == ELF::R_ARM_PC24 ||
1026 RelType == ELF::R_ARM_CALL ||
1027 RelType == ELF::R_ARM_JUMP24)) {
1028 // This is an ARM branch relocation, need to use a stub function.
1029 DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
1030 SectionEntry &Section = Sections[SectionID];
1032 // Look for an existing stub.
1033 StubMap::const_iterator i = Stubs.find(Value);
1034 if (i != Stubs.end()) {
1035 resolveRelocation(Section, Offset,
1036 (uint64_t)Section.Address + i->second, RelType, 0);
1037 DEBUG(dbgs() << " Stub function found\n");
1039 // Create a new stub function.
1040 DEBUG(dbgs() << " Create a new stub function\n");
1041 Stubs[Value] = Section.StubOffset;
1042 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
1043 Section.StubOffset);
1044 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1045 ELF::R_ARM_PRIVATE_0, Value.Addend);
1046 if (Value.SymbolName)
1047 addRelocationForSymbol(RE, Value.SymbolName);
1049 addRelocationForSection(RE, Value.SectionID);
1051 resolveRelocation(Section, Offset,
1052 (uint64_t)Section.Address + Section.StubOffset,
1054 Section.StubOffset += getMaxStubSize();
1056 } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
1057 RelType == ELF::R_MIPS_26) {
1058 // This is an Mips branch relocation, need to use a stub function.
1059 DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1060 SectionEntry &Section = Sections[SectionID];
1061 uint8_t *Target = Section.Address + Offset;
1062 uint32_t *TargetAddress = (uint32_t *)Target;
1064 // Extract the addend from the instruction.
1065 uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
1067 Value.Addend += Addend;
1069 // Look up for existing stub.
1070 StubMap::const_iterator i = Stubs.find(Value);
1071 if (i != Stubs.end()) {
1072 RelocationEntry RE(SectionID, Offset, RelType, i->second);
1073 addRelocationForSection(RE, SectionID);
1074 DEBUG(dbgs() << " Stub function found\n");
1076 // Create a new stub function.
1077 DEBUG(dbgs() << " Create a new stub function\n");
1078 Stubs[Value] = Section.StubOffset;
1079 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
1080 Section.StubOffset);
1082 // Creating Hi and Lo relocations for the filled stub instructions.
1083 RelocationEntry REHi(SectionID,
1084 StubTargetAddr - Section.Address,
1085 ELF::R_MIPS_UNUSED1, Value.Addend);
1086 RelocationEntry RELo(SectionID,
1087 StubTargetAddr - Section.Address + 4,
1088 ELF::R_MIPS_UNUSED2, Value.Addend);
1090 if (Value.SymbolName) {
1091 addRelocationForSymbol(REHi, Value.SymbolName);
1092 addRelocationForSymbol(RELo, Value.SymbolName);
1094 addRelocationForSection(REHi, Value.SectionID);
1095 addRelocationForSection(RELo, Value.SectionID);
1098 RelocationEntry RE(SectionID, Offset, RelType, Section.StubOffset);
1099 addRelocationForSection(RE, SectionID);
1100 Section.StubOffset += getMaxStubSize();
1102 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1103 if (RelType == ELF::R_PPC64_REL24) {
1104 // A PPC branch relocation will need a stub function if the target is
1105 // an external symbol (Symbol::ST_Unknown) or if the target address
1106 // is not within the signed 24-bits branch address.
1107 SectionEntry &Section = Sections[SectionID];
1108 uint8_t *Target = Section.Address + Offset;
1109 bool RangeOverflow = false;
1110 if (SymType != SymbolRef::ST_Unknown) {
1111 // A function call may points to the .opd entry, so the final symbol value
1112 // in calculated based in the relocation values in .opd section.
1113 findOPDEntrySection(Obj, ObjSectionToID, Value);
1114 uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
1115 int32_t delta = static_cast<int32_t>(Target - RelocTarget);
1116 // If it is within 24-bits branch range, just set the branch target
1117 if (SignExtend32<24>(delta) == delta) {
1118 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1119 if (Value.SymbolName)
1120 addRelocationForSymbol(RE, Value.SymbolName);
1122 addRelocationForSection(RE, Value.SectionID);
1124 RangeOverflow = true;
1127 if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
1128 // It is an external symbol (SymbolRef::ST_Unknown) or within a range
1129 // larger than 24-bits.
1130 StubMap::const_iterator i = Stubs.find(Value);
1131 if (i != Stubs.end()) {
1132 // Symbol function stub already created, just relocate to it
1133 resolveRelocation(Section, Offset,
1134 (uint64_t)Section.Address + i->second, RelType, 0);
1135 DEBUG(dbgs() << " Stub function found\n");
1137 // Create a new stub function.
1138 DEBUG(dbgs() << " Create a new stub function\n");
1139 Stubs[Value] = Section.StubOffset;
1140 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
1141 Section.StubOffset);
1142 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1143 ELF::R_PPC64_ADDR64, Value.Addend);
1145 // Generates the 64-bits address loads as exemplified in section
1146 // 4.5.1 in PPC64 ELF ABI.
1147 RelocationEntry REhst(SectionID,
1148 StubTargetAddr - Section.Address + 2,
1149 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1150 RelocationEntry REhr(SectionID,
1151 StubTargetAddr - Section.Address + 6,
1152 ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1153 RelocationEntry REh(SectionID,
1154 StubTargetAddr - Section.Address + 14,
1155 ELF::R_PPC64_ADDR16_HI, Value.Addend);
1156 RelocationEntry REl(SectionID,
1157 StubTargetAddr - Section.Address + 18,
1158 ELF::R_PPC64_ADDR16_LO, Value.Addend);
1160 if (Value.SymbolName) {
1161 addRelocationForSymbol(REhst, Value.SymbolName);
1162 addRelocationForSymbol(REhr, Value.SymbolName);
1163 addRelocationForSymbol(REh, Value.SymbolName);
1164 addRelocationForSymbol(REl, Value.SymbolName);
1166 addRelocationForSection(REhst, Value.SectionID);
1167 addRelocationForSection(REhr, Value.SectionID);
1168 addRelocationForSection(REh, Value.SectionID);
1169 addRelocationForSection(REl, Value.SectionID);
1172 resolveRelocation(Section, Offset,
1173 (uint64_t)Section.Address + Section.StubOffset,
1175 if (SymType == SymbolRef::ST_Unknown)
1176 // Restore the TOC for external calls
1177 writeInt32BE(Target+4, 0xE8410028); // ld r2,40(r1)
1178 Section.StubOffset += getMaxStubSize();
1182 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1183 // Extra check to avoid relocation againt empty symbols (usually
1184 // the R_PPC64_TOC).
1185 if (SymType != SymbolRef::ST_Unknown && TargetName.empty())
1186 Value.SymbolName = NULL;
1188 if (Value.SymbolName)
1189 addRelocationForSymbol(RE, Value.SymbolName);
1191 addRelocationForSection(RE, Value.SectionID);
1193 } else if (Arch == Triple::systemz &&
1194 (RelType == ELF::R_390_PLT32DBL ||
1195 RelType == ELF::R_390_GOTENT)) {
1196 // Create function stubs for both PLT and GOT references, regardless of
1197 // whether the GOT reference is to data or code. The stub contains the
1198 // full address of the symbol, as needed by GOT references, and the
1199 // executable part only adds an overhead of 8 bytes.
1201 // We could try to conserve space by allocating the code and data
1202 // parts of the stub separately. However, as things stand, we allocate
1203 // a stub for every relocation, so using a GOT in JIT code should be
1204 // no less space efficient than using an explicit constant pool.
1205 DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1206 SectionEntry &Section = Sections[SectionID];
1208 // Look for an existing stub.
1209 StubMap::const_iterator i = Stubs.find(Value);
1210 uintptr_t StubAddress;
1211 if (i != Stubs.end()) {
1212 StubAddress = uintptr_t(Section.Address) + i->second;
1213 DEBUG(dbgs() << " Stub function found\n");
1215 // Create a new stub function.
1216 DEBUG(dbgs() << " Create a new stub function\n");
1218 uintptr_t BaseAddress = uintptr_t(Section.Address);
1219 uintptr_t StubAlignment = getStubAlignment();
1220 StubAddress = (BaseAddress + Section.StubOffset +
1221 StubAlignment - 1) & -StubAlignment;
1222 unsigned StubOffset = StubAddress - BaseAddress;
1224 Stubs[Value] = StubOffset;
1225 createStubFunction((uint8_t *)StubAddress);
1226 RelocationEntry RE(SectionID, StubOffset + 8,
1227 ELF::R_390_64, Value.Addend - Addend);
1228 if (Value.SymbolName)
1229 addRelocationForSymbol(RE, Value.SymbolName);
1231 addRelocationForSection(RE, Value.SectionID);
1232 Section.StubOffset = StubOffset + getMaxStubSize();
1235 if (RelType == ELF::R_390_GOTENT)
1236 resolveRelocation(Section, Offset, StubAddress + 8,
1237 ELF::R_390_PC32DBL, Addend);
1239 resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1240 } else if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_PLT32) {
1241 // The way the PLT relocations normally work is that the linker allocates the
1242 // PLT and this relocation makes a PC-relative call into the PLT. The PLT
1243 // entry will then jump to an address provided by the GOT. On first call, the
1244 // GOT address will point back into PLT code that resolves the symbol. After
1245 // the first call, the GOT entry points to the actual function.
1247 // For local functions we're ignoring all of that here and just replacing
1248 // the PLT32 relocation type with PC32, which will translate the relocation
1249 // into a PC-relative call directly to the function. For external symbols we
1250 // can't be sure the function will be within 2^32 bytes of the call site, so
1251 // we need to create a stub, which calls into the GOT. This case is
1252 // equivalent to the usual PLT implementation except that we use the stub
1253 // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1254 // rather than allocating a PLT section.
1255 if (Value.SymbolName) {
1256 // This is a call to an external function.
1257 // Look for an existing stub.
1258 SectionEntry &Section = Sections[SectionID];
1259 StubMap::const_iterator i = Stubs.find(Value);
1260 uintptr_t StubAddress;
1261 if (i != Stubs.end()) {
1262 StubAddress = uintptr_t(Section.Address) + i->second;
1263 DEBUG(dbgs() << " Stub function found\n");
1265 // Create a new stub function (equivalent to a PLT entry).
1266 DEBUG(dbgs() << " Create a new stub function\n");
1268 uintptr_t BaseAddress = uintptr_t(Section.Address);
1269 uintptr_t StubAlignment = getStubAlignment();
1270 StubAddress = (BaseAddress + Section.StubOffset +
1271 StubAlignment - 1) & -StubAlignment;
1272 unsigned StubOffset = StubAddress - BaseAddress;
1273 Stubs[Value] = StubOffset;
1274 createStubFunction((uint8_t *)StubAddress);
1276 // Create a GOT entry for the external function.
1277 GOTEntries.push_back(Value);
1279 // Make our stub function a relative call to the GOT entry.
1280 RelocationEntry RE(SectionID, StubOffset + 2,
1281 ELF::R_X86_64_GOTPCREL, -4);
1282 addRelocationForSymbol(RE, Value.SymbolName);
1284 // Bump our stub offset counter
1285 Section.StubOffset = StubOffset + getMaxStubSize();
1288 // Make the target call a call into the stub table.
1289 resolveRelocation(Section, Offset, StubAddress,
1290 ELF::R_X86_64_PC32, Addend);
1292 RelocationEntry RE(SectionID, Offset, ELF::R_X86_64_PC32, Value.Addend,
1294 addRelocationForSection(RE, Value.SectionID);
1297 if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_GOTPCREL) {
1298 GOTEntries.push_back(Value);
1300 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1301 if (Value.SymbolName)
1302 addRelocationForSymbol(RE, Value.SymbolName);
1304 addRelocationForSection(RE, Value.SectionID);
1308 void RuntimeDyldELF::updateGOTEntries(StringRef Name, uint64_t Addr) {
1310 SmallVectorImpl<std::pair<SID, GOTRelocations> >::iterator it;
1311 SmallVectorImpl<std::pair<SID, GOTRelocations> >::iterator end = GOTs.end();
1313 for (it = GOTs.begin(); it != end; ++it) {
1314 GOTRelocations &GOTEntries = it->second;
1315 for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1316 if (GOTEntries[i].SymbolName != 0 && GOTEntries[i].SymbolName == Name) {
1317 GOTEntries[i].Offset = Addr;
1323 size_t RuntimeDyldELF::getGOTEntrySize() {
1324 // We don't use the GOT in all of these cases, but it's essentially free
1325 // to put them all here.
1328 case Triple::x86_64:
1329 case Triple::aarch64:
1331 case Triple::ppc64le:
1332 case Triple::systemz:
1333 Result = sizeof(uint64_t);
1339 case Triple::mipsel:
1340 Result = sizeof(uint32_t);
1342 default: llvm_unreachable("Unsupported CPU type!");
1347 uint64_t RuntimeDyldELF::findGOTEntry(uint64_t LoadAddress,
1350 const size_t GOTEntrySize = getGOTEntrySize();
1352 SmallVectorImpl<std::pair<SID, GOTRelocations> >::const_iterator it;
1353 SmallVectorImpl<std::pair<SID, GOTRelocations> >::const_iterator end = GOTs.end();
1356 for (it = GOTs.begin(); it != end; ++it) {
1357 SID GOTSectionID = it->first;
1358 const GOTRelocations &GOTEntries = it->second;
1360 // Find the matching entry in our vector.
1361 uint64_t SymbolOffset = 0;
1362 for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1363 if (GOTEntries[i].SymbolName == 0) {
1364 if (getSectionLoadAddress(GOTEntries[i].SectionID) == LoadAddress &&
1365 GOTEntries[i].Offset == Offset) {
1367 SymbolOffset = GOTEntries[i].Offset;
1371 // GOT entries for external symbols use the addend as the address when
1372 // the external symbol has been resolved.
1373 if (GOTEntries[i].Offset == LoadAddress) {
1375 // Don't use the Addend here. The relocation handler will use it.
1381 if (GOTIndex != -1) {
1382 if (GOTEntrySize == sizeof(uint64_t)) {
1383 uint64_t *LocalGOTAddr = (uint64_t*)getSectionAddress(GOTSectionID);
1384 // Fill in this entry with the address of the symbol being referenced.
1385 LocalGOTAddr[GOTIndex] = LoadAddress + SymbolOffset;
1387 uint32_t *LocalGOTAddr = (uint32_t*)getSectionAddress(GOTSectionID);
1388 // Fill in this entry with the address of the symbol being referenced.
1389 LocalGOTAddr[GOTIndex] = (uint32_t)(LoadAddress + SymbolOffset);
1392 // Calculate the load address of this entry
1393 return getSectionLoadAddress(GOTSectionID) + (GOTIndex * GOTEntrySize);
1397 assert(GOTIndex != -1 && "Unable to find requested GOT entry.");
1401 void RuntimeDyldELF::finalizeLoad(ObjSectionToIDMap &SectionMap) {
1402 // If necessary, allocate the global offset table
1404 // Allocate the GOT if necessary
1405 size_t numGOTEntries = GOTEntries.size();
1406 if (numGOTEntries != 0) {
1407 // Allocate memory for the section
1408 unsigned SectionID = Sections.size();
1409 size_t TotalSize = numGOTEntries * getGOTEntrySize();
1410 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, getGOTEntrySize(),
1411 SectionID, ".got", false);
1413 report_fatal_error("Unable to allocate memory for GOT!");
1415 GOTs.push_back(std::make_pair(SectionID, GOTEntries));
1416 Sections.push_back(SectionEntry(".got", Addr, TotalSize, 0));
1417 // For now, initialize all GOT entries to zero. We'll fill them in as
1418 // needed when GOT-based relocations are applied.
1419 memset(Addr, 0, TotalSize);
1423 report_fatal_error("Unable to allocate memory for GOT!");
1426 // Look for and record the EH frame section.
1427 ObjSectionToIDMap::iterator i, e;
1428 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
1429 const SectionRef &Section = i->first;
1431 Section.getName(Name);
1432 if (Name == ".eh_frame") {
1433 UnregisteredEHFrameSections.push_back(i->second);
1439 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1440 if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1442 return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
1445 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile *Obj) const {
1446 return Obj->isELF();