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 #include "RuntimeDyldELF.h"
15 #include "llvm/ADT/IntervalMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/Object/ELFObjectFile.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/ELF.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/TargetRegistry.h"
28 using namespace llvm::object;
30 #define DEBUG_TYPE "dyld"
32 static inline std::error_code check(std::error_code Err) {
34 report_fatal_error(Err.message());
41 template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> {
42 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
44 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
45 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
46 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
47 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
49 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
51 typedef typename ELFDataTypeTypedefHelper<ELFT>::value_type addr_type;
54 DyldELFObject(MemoryBufferRef Wrapper, std::error_code &ec);
56 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
58 void updateSymbolAddress(const SymbolRef &SymRef, uint64_t Addr);
60 // Methods for type inquiry through isa, cast and dyn_cast
61 static inline bool classof(const Binary *v) {
62 return (isa<ELFObjectFile<ELFT>>(v) &&
63 classof(cast<ELFObjectFile<ELFT>>(v)));
65 static inline bool classof(const ELFObjectFile<ELFT> *v) {
66 return v->isDyldType();
73 // The MemoryBuffer passed into this constructor is just a wrapper around the
74 // actual memory. Ultimately, the Binary parent class will take ownership of
75 // this MemoryBuffer object but not the underlying memory.
77 DyldELFObject<ELFT>::DyldELFObject(MemoryBufferRef Wrapper, std::error_code &EC)
78 : ELFObjectFile<ELFT>(Wrapper, EC) {
79 this->isDyldELFObject = true;
83 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
85 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
87 const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
89 // This assumes the address passed in matches the target address bitness
90 // The template-based type cast handles everything else.
91 shdr->sh_addr = static_cast<addr_type>(Addr);
95 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
98 Elf_Sym *sym = const_cast<Elf_Sym *>(
99 ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
101 // This assumes the address passed in matches the target address bitness
102 // The template-based type cast handles everything else.
103 sym->st_value = static_cast<addr_type>(Addr);
106 class LoadedELFObjectInfo : public RuntimeDyld::LoadedObjectInfo {
108 LoadedELFObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
110 : RuntimeDyld::LoadedObjectInfo(RTDyld, BeginIdx, EndIdx) {}
112 OwningBinary<ObjectFile>
113 getObjectForDebug(const ObjectFile &Obj) const override;
116 template <typename ELFT>
117 std::unique_ptr<DyldELFObject<ELFT>>
118 createRTDyldELFObject(MemoryBufferRef Buffer,
119 const LoadedELFObjectInfo &L,
120 std::error_code &ec) {
121 typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
122 typedef typename ELFDataTypeTypedefHelper<ELFT>::value_type addr_type;
124 std::unique_ptr<DyldELFObject<ELFT>> Obj =
125 llvm::make_unique<DyldELFObject<ELFT>>(Buffer, ec);
127 // Iterate over all sections in the object.
128 for (const auto &Sec : Obj->sections()) {
129 StringRef SectionName;
130 Sec.getName(SectionName);
131 if (SectionName != "") {
132 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
133 Elf_Shdr *shdr = const_cast<Elf_Shdr *>(
134 reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
136 if (uint64_t SecLoadAddr = L.getSectionLoadAddress(SectionName)) {
137 // This assumes that the address passed in matches the target address
138 // bitness. The template-based type cast handles everything else.
139 shdr->sh_addr = static_cast<addr_type>(SecLoadAddr);
147 OwningBinary<ObjectFile> createELFDebugObject(const ObjectFile &Obj,
148 const LoadedELFObjectInfo &L) {
149 assert(Obj.isELF() && "Not an ELF object file.");
151 std::unique_ptr<MemoryBuffer> Buffer =
152 MemoryBuffer::getMemBufferCopy(Obj.getData(), Obj.getFileName());
156 std::unique_ptr<ObjectFile> DebugObj;
157 if (Obj.getBytesInAddress() == 4 && Obj.isLittleEndian()) {
158 typedef ELFType<support::little, 2, false> ELF32LE;
159 DebugObj = createRTDyldELFObject<ELF32LE>(Buffer->getMemBufferRef(), L, ec);
160 } else if (Obj.getBytesInAddress() == 4 && !Obj.isLittleEndian()) {
161 typedef ELFType<support::big, 2, false> ELF32BE;
162 DebugObj = createRTDyldELFObject<ELF32BE>(Buffer->getMemBufferRef(), L, ec);
163 } else if (Obj.getBytesInAddress() == 8 && !Obj.isLittleEndian()) {
164 typedef ELFType<support::big, 2, true> ELF64BE;
165 DebugObj = createRTDyldELFObject<ELF64BE>(Buffer->getMemBufferRef(), L, ec);
166 } else if (Obj.getBytesInAddress() == 8 && Obj.isLittleEndian()) {
167 typedef ELFType<support::little, 2, true> ELF64LE;
168 DebugObj = createRTDyldELFObject<ELF64LE>(Buffer->getMemBufferRef(), L, ec);
170 llvm_unreachable("Unexpected ELF format");
172 assert(!ec && "Could not construct copy ELF object file");
174 return OwningBinary<ObjectFile>(std::move(DebugObj), std::move(Buffer));
177 OwningBinary<ObjectFile>
178 LoadedELFObjectInfo::getObjectForDebug(const ObjectFile &Obj) const {
179 return createELFDebugObject(Obj, *this);
186 RuntimeDyldELF::RuntimeDyldELF(RuntimeDyld::MemoryManager &MemMgr,
187 RuntimeDyld::SymbolResolver &Resolver)
188 : RuntimeDyldImpl(MemMgr, Resolver) {}
189 RuntimeDyldELF::~RuntimeDyldELF() {}
191 void RuntimeDyldELF::registerEHFrames() {
192 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
193 SID EHFrameSID = UnregisteredEHFrameSections[i];
194 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
195 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
196 size_t EHFrameSize = Sections[EHFrameSID].Size;
197 MemMgr.registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
198 RegisteredEHFrameSections.push_back(EHFrameSID);
200 UnregisteredEHFrameSections.clear();
203 void RuntimeDyldELF::deregisterEHFrames() {
204 for (int i = 0, e = RegisteredEHFrameSections.size(); i != e; ++i) {
205 SID EHFrameSID = RegisteredEHFrameSections[i];
206 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
207 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
208 size_t EHFrameSize = Sections[EHFrameSID].Size;
209 MemMgr.deregisterEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
211 RegisteredEHFrameSections.clear();
214 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
215 RuntimeDyldELF::loadObject(const object::ObjectFile &O) {
216 unsigned SectionStartIdx, SectionEndIdx;
217 std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
218 return llvm::make_unique<LoadedELFObjectInfo>(*this, SectionStartIdx,
222 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
223 uint64_t Offset, uint64_t Value,
224 uint32_t Type, int64_t Addend,
225 uint64_t SymOffset) {
228 llvm_unreachable("Relocation type not implemented yet!");
230 case ELF::R_X86_64_64: {
231 support::ulittle64_t::ref(Section.Address + Offset) = Value + Addend;
232 DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
233 << format("%p\n", Section.Address + Offset));
236 case ELF::R_X86_64_32:
237 case ELF::R_X86_64_32S: {
239 assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
240 (Type == ELF::R_X86_64_32S &&
241 ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
242 uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
243 support::ulittle32_t::ref(Section.Address + Offset) = TruncatedAddr;
244 DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
245 << format("%p\n", Section.Address + Offset));
248 case ELF::R_X86_64_GOTPCREL: {
249 // findGOTEntry returns the 'G + GOT' part of the relocation calculation
250 // based on the load/target address of the GOT (not the current/local addr).
251 uint64_t GOTAddr = findGOTEntry(Value, SymOffset);
252 uint64_t FinalAddress = Section.LoadAddress + Offset;
253 // The processRelocationRef method combines the symbol offset and the addend
254 // and in most cases that's what we want. For this relocation type, we need
255 // the raw addend, so we subtract the symbol offset to get it.
256 int64_t RealOffset = GOTAddr + Addend - SymOffset - FinalAddress;
257 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
258 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
259 support::ulittle32_t::ref(Section.Address + Offset) = TruncOffset;
262 case ELF::R_X86_64_PC32: {
263 // Get the placeholder value from the generated object since
264 // a previous relocation attempt may have overwritten the loaded version
265 support::ulittle32_t::ref Placeholder(
266 (void *)(Section.ObjAddress + Offset));
267 uint64_t FinalAddress = Section.LoadAddress + Offset;
268 int64_t RealOffset = Placeholder + Value + Addend - FinalAddress;
269 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
270 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
271 support::ulittle32_t::ref(Section.Address + Offset) = TruncOffset;
274 case ELF::R_X86_64_PC64: {
275 // Get the placeholder value from the generated object since
276 // a previous relocation attempt may have overwritten the loaded version
277 support::ulittle64_t::ref Placeholder(
278 (void *)(Section.ObjAddress + Offset));
279 uint64_t FinalAddress = Section.LoadAddress + Offset;
280 support::ulittle64_t::ref(Section.Address + Offset) =
281 Placeholder + Value + Addend - FinalAddress;
287 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
288 uint64_t Offset, uint32_t Value,
289 uint32_t Type, int32_t Addend) {
291 case ELF::R_386_32: {
292 // Get the placeholder value from the generated object since
293 // a previous relocation attempt may have overwritten the loaded version
294 support::ulittle32_t::ref Placeholder(
295 (void *)(Section.ObjAddress + Offset));
296 support::ulittle32_t::ref(Section.Address + Offset) =
297 Placeholder + Value + Addend;
300 case ELF::R_386_PC32: {
301 // Get the placeholder value from the generated object since
302 // a previous relocation attempt may have overwritten the loaded version
303 support::ulittle32_t::ref Placeholder(
304 (void *)(Section.ObjAddress + Offset));
305 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
306 uint32_t RealOffset = Placeholder + Value + Addend - FinalAddress;
307 support::ulittle32_t::ref(Section.Address + Offset) = RealOffset;
311 // There are other relocation types, but it appears these are the
312 // only ones currently used by the LLVM ELF object writer
313 llvm_unreachable("Relocation type not implemented yet!");
318 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
319 uint64_t Offset, uint64_t Value,
320 uint32_t Type, int64_t Addend) {
321 uint32_t *TargetPtr = reinterpret_cast<uint32_t *>(Section.Address + Offset);
322 uint64_t FinalAddress = Section.LoadAddress + Offset;
324 DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
325 << format("%llx", Section.Address + Offset)
326 << " FinalAddress: 0x" << format("%llx", FinalAddress)
327 << " Value: 0x" << format("%llx", Value) << " Type: 0x"
328 << format("%x", Type) << " Addend: 0x" << format("%llx", Addend)
333 llvm_unreachable("Relocation type not implemented yet!");
335 case ELF::R_AARCH64_ABS64: {
336 uint64_t *TargetPtr =
337 reinterpret_cast<uint64_t *>(Section.Address + Offset);
338 *TargetPtr = Value + Addend;
341 case ELF::R_AARCH64_PREL32: {
342 uint64_t Result = Value + Addend - FinalAddress;
343 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
344 static_cast<int64_t>(Result) <= UINT32_MAX);
345 *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU);
348 case ELF::R_AARCH64_CALL26: // fallthrough
349 case ELF::R_AARCH64_JUMP26: {
350 // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
352 uint64_t BranchImm = Value + Addend - FinalAddress;
354 // "Check that -2^27 <= result < 2^27".
355 assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) &&
356 static_cast<int64_t>(BranchImm) < (1LL << 27));
358 // AArch64 code is emitted with .rela relocations. The data already in any
359 // bits affected by the relocation on entry is garbage.
360 *TargetPtr &= 0xfc000000U;
361 // Immediate goes in bits 25:0 of B and BL.
362 *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2;
365 case ELF::R_AARCH64_MOVW_UABS_G3: {
366 uint64_t Result = Value + Addend;
368 // AArch64 code is emitted with .rela relocations. The data already in any
369 // bits affected by the relocation on entry is garbage.
370 *TargetPtr &= 0xffe0001fU;
371 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
372 *TargetPtr |= Result >> (48 - 5);
373 // Shift must be "lsl #48", in bits 22:21
374 assert((*TargetPtr >> 21 & 0x3) == 3 && "invalid shift for relocation");
377 case ELF::R_AARCH64_MOVW_UABS_G2_NC: {
378 uint64_t Result = Value + Addend;
380 // AArch64 code is emitted with .rela relocations. The data already in any
381 // bits affected by the relocation on entry is garbage.
382 *TargetPtr &= 0xffe0001fU;
383 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
384 *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5));
385 // Shift must be "lsl #32", in bits 22:21
386 assert((*TargetPtr >> 21 & 0x3) == 2 && "invalid shift for relocation");
389 case ELF::R_AARCH64_MOVW_UABS_G1_NC: {
390 uint64_t Result = Value + Addend;
392 // AArch64 code is emitted with .rela relocations. The data already in any
393 // bits affected by the relocation on entry is garbage.
394 *TargetPtr &= 0xffe0001fU;
395 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
396 *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5));
397 // Shift must be "lsl #16", in bits 22:2
398 assert((*TargetPtr >> 21 & 0x3) == 1 && "invalid shift for relocation");
401 case ELF::R_AARCH64_MOVW_UABS_G0_NC: {
402 uint64_t Result = Value + Addend;
404 // AArch64 code is emitted with .rela relocations. The data already in any
405 // bits affected by the relocation on entry is garbage.
406 *TargetPtr &= 0xffe0001fU;
407 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
408 *TargetPtr |= ((Result & 0xffffU) << 5);
409 // Shift must be "lsl #0", in bits 22:21.
410 assert((*TargetPtr >> 21 & 0x3) == 0 && "invalid shift for relocation");
413 case ELF::R_AARCH64_ADR_PREL_PG_HI21: {
414 // Operation: Page(S+A) - Page(P)
416 ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL);
418 // Check that -2^32 <= X < 2^32
419 assert(static_cast<int64_t>(Result) >= (-1LL << 32) &&
420 static_cast<int64_t>(Result) < (1LL << 32) &&
421 "overflow check failed for relocation");
423 // AArch64 code is emitted with .rela relocations. The data already in any
424 // bits affected by the relocation on entry is garbage.
425 *TargetPtr &= 0x9f00001fU;
426 // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken
427 // from bits 32:12 of X.
428 *TargetPtr |= ((Result & 0x3000U) << (29 - 12));
429 *TargetPtr |= ((Result & 0x1ffffc000ULL) >> (14 - 5));
432 case ELF::R_AARCH64_LDST32_ABS_LO12_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 &= 0xffc003ffU;
439 // Immediate goes in bits 21:10 of LD/ST instruction, taken
440 // from bits 11:2 of X
441 *TargetPtr |= ((Result & 0xffc) << (10 - 2));
444 case ELF::R_AARCH64_LDST64_ABS_LO12_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 &= 0xffc003ffU;
451 // Immediate goes in bits 21:10 of LD/ST instruction, taken
452 // from bits 11:3 of X
453 *TargetPtr |= ((Result & 0xff8) << (10 - 3));
459 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
460 uint64_t Offset, uint32_t Value,
461 uint32_t Type, int32_t Addend) {
462 // TODO: Add Thumb relocations.
463 uint32_t *Placeholder =
464 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
465 uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset);
466 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
469 DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
470 << Section.Address + Offset
471 << " FinalAddress: " << format("%p", FinalAddress) << " Value: "
472 << format("%x", Value) << " Type: " << format("%x", Type)
473 << " Addend: " << format("%x", Addend) << "\n");
477 llvm_unreachable("Not implemented relocation type!");
479 case ELF::R_ARM_NONE:
481 // Write a 32bit value to relocation address, taking into account the
482 // implicit addend encoded in the target.
483 case ELF::R_ARM_PREL31:
484 case ELF::R_ARM_TARGET1:
485 case ELF::R_ARM_ABS32:
486 *TargetPtr = *Placeholder + Value;
488 // Write first 16 bit of 32 bit value to the mov instruction.
489 // Last 4 bit should be shifted.
490 case ELF::R_ARM_MOVW_ABS_NC:
491 // We are not expecting any other addend in the relocation address.
492 // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
493 // non-contiguous fields.
494 assert((*Placeholder & 0x000F0FFF) == 0);
495 Value = Value & 0xFFFF;
496 *TargetPtr = *Placeholder | (Value & 0xFFF);
497 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
499 // Write last 16 bit of 32 bit value to the mov instruction.
500 // Last 4 bit should be shifted.
501 case ELF::R_ARM_MOVT_ABS:
502 // We are not expecting any other addend in the relocation address.
503 // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
504 assert((*Placeholder & 0x000F0FFF) == 0);
506 Value = (Value >> 16) & 0xFFFF;
507 *TargetPtr = *Placeholder | (Value & 0xFFF);
508 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
510 // Write 24 bit relative value to the branch instruction.
511 case ELF::R_ARM_PC24: // Fall through.
512 case ELF::R_ARM_CALL: // Fall through.
513 case ELF::R_ARM_JUMP24: {
514 int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
515 RelValue = (RelValue & 0x03FFFFFC) >> 2;
516 assert((*TargetPtr & 0xFFFFFF) == 0xFFFFFE);
517 *TargetPtr &= 0xFF000000;
518 *TargetPtr |= RelValue;
521 case ELF::R_ARM_PRIVATE_0:
522 // This relocation is reserved by the ARM ELF ABI for internal use. We
523 // appropriate it here to act as an R_ARM_ABS32 without any addend for use
524 // in the stubs created during JIT (which can't put an addend into the
525 // original object file).
531 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
532 uint64_t Offset, uint32_t Value,
533 uint32_t Type, int32_t Addend) {
534 uint32_t *Placeholder =
535 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
536 uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset);
539 DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
540 << Section.Address + Offset << " FinalAddress: "
541 << format("%p", Section.LoadAddress + Offset) << " Value: "
542 << format("%x", Value) << " Type: " << format("%x", Type)
543 << " Addend: " << format("%x", Addend) << "\n");
547 llvm_unreachable("Not implemented relocation type!");
550 *TargetPtr = Value + (*Placeholder);
553 *TargetPtr = ((*Placeholder) & 0xfc000000) | ((Value & 0x0fffffff) >> 2);
555 case ELF::R_MIPS_HI16:
556 // Get the higher 16-bits. Also add 1 if bit 15 is 1.
557 Value += ((*Placeholder) & 0x0000ffff) << 16;
559 ((*Placeholder) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff);
561 case ELF::R_MIPS_LO16:
562 Value += ((*Placeholder) & 0x0000ffff);
563 *TargetPtr = ((*Placeholder) & 0xffff0000) | (Value & 0xffff);
565 case ELF::R_MIPS_UNUSED1:
566 // Similar to ELF::R_ARM_PRIVATE_0, R_MIPS_UNUSED1 and R_MIPS_UNUSED2
567 // are used for internal JIT purpose. These relocations are similar to
568 // R_MIPS_HI16 and R_MIPS_LO16, but they do not take any addend into
571 ((*TargetPtr) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff);
573 case ELF::R_MIPS_UNUSED2:
574 *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
579 // Return the .TOC. section and offset.
580 void RuntimeDyldELF::findPPC64TOCSection(const ObjectFile &Obj,
581 ObjSectionToIDMap &LocalSections,
582 RelocationValueRef &Rel) {
583 // Set a default SectionID in case we do not find a TOC section below.
584 // This may happen for references to TOC base base (sym@toc, .odp
585 // relocation) without a .toc directive. In this case just use the
586 // first section (which is usually the .odp) since the code won't
587 // reference the .toc base directly.
588 Rel.SymbolName = NULL;
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 for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
596 StringRef SectionName;
597 check(si->getName(SectionName));
599 if (SectionName == ".got"
600 || SectionName == ".toc"
601 || SectionName == ".tocbss"
602 || SectionName == ".plt") {
603 Rel.SectionID = findOrEmitSection(Obj, *si, false, LocalSections);
608 // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
609 // thus permitting a full 64 Kbytes segment.
613 // Returns the sections and offset associated with the ODP entry referenced
615 void RuntimeDyldELF::findOPDEntrySection(const ObjectFile &Obj,
616 ObjSectionToIDMap &LocalSections,
617 RelocationValueRef &Rel) {
618 // Get the ELF symbol value (st_value) to compare with Relocation offset in
620 for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
622 section_iterator RelSecI = si->getRelocatedSection();
623 if (RelSecI == Obj.section_end())
626 StringRef RelSectionName;
627 check(RelSecI->getName(RelSectionName));
628 if (RelSectionName != ".opd")
631 for (relocation_iterator i = si->relocation_begin(),
632 e = si->relocation_end();
634 // The R_PPC64_ADDR64 relocation indicates the first field
637 check(i->getType(TypeFunc));
638 if (TypeFunc != ELF::R_PPC64_ADDR64) {
643 uint64_t TargetSymbolOffset;
644 symbol_iterator TargetSymbol = i->getSymbol();
645 check(i->getOffset(TargetSymbolOffset));
647 check(getELFRelocationAddend(*i, Addend));
653 // Just check if following relocation is a R_PPC64_TOC
655 check(i->getType(TypeTOC));
656 if (TypeTOC != ELF::R_PPC64_TOC)
659 // Finally compares the Symbol value and the target symbol offset
660 // to check if this .opd entry refers to the symbol the relocation
662 if (Rel.Addend != (int64_t)TargetSymbolOffset)
665 section_iterator tsi(Obj.section_end());
666 check(TargetSymbol->getSection(tsi));
667 bool IsCode = tsi->isText();
668 Rel.SectionID = findOrEmitSection(Obj, (*tsi), IsCode, LocalSections);
669 Rel.Addend = (intptr_t)Addend;
673 llvm_unreachable("Attempting to get address of ODP entry!");
676 // Relocation masks following the #lo(value), #hi(value), #ha(value),
677 // #higher(value), #highera(value), #highest(value), and #highesta(value)
678 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
681 static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
683 static inline uint16_t applyPPChi(uint64_t value) {
684 return (value >> 16) & 0xffff;
687 static inline uint16_t applyPPCha (uint64_t value) {
688 return ((value + 0x8000) >> 16) & 0xffff;
691 static inline uint16_t applyPPChigher(uint64_t value) {
692 return (value >> 32) & 0xffff;
695 static inline uint16_t applyPPChighera (uint64_t value) {
696 return ((value + 0x8000) >> 32) & 0xffff;
699 static inline uint16_t applyPPChighest(uint64_t value) {
700 return (value >> 48) & 0xffff;
703 static inline uint16_t applyPPChighesta (uint64_t value) {
704 return ((value + 0x8000) >> 48) & 0xffff;
707 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
708 uint64_t Offset, uint64_t Value,
709 uint32_t Type, int64_t Addend) {
710 uint8_t *LocalAddress = Section.Address + Offset;
713 llvm_unreachable("Relocation type not implemented yet!");
715 case ELF::R_PPC64_ADDR16:
716 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
718 case ELF::R_PPC64_ADDR16_DS:
719 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
721 case ELF::R_PPC64_ADDR16_LO:
722 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
724 case ELF::R_PPC64_ADDR16_LO_DS:
725 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
727 case ELF::R_PPC64_ADDR16_HI:
728 writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
730 case ELF::R_PPC64_ADDR16_HA:
731 writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
733 case ELF::R_PPC64_ADDR16_HIGHER:
734 writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
736 case ELF::R_PPC64_ADDR16_HIGHERA:
737 writeInt16BE(LocalAddress, applyPPChighera(Value + Addend));
739 case ELF::R_PPC64_ADDR16_HIGHEST:
740 writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
742 case ELF::R_PPC64_ADDR16_HIGHESTA:
743 writeInt16BE(LocalAddress, applyPPChighesta(Value + Addend));
745 case ELF::R_PPC64_ADDR14: {
746 assert(((Value + Addend) & 3) == 0);
747 // Preserve the AA/LK bits in the branch instruction
748 uint8_t aalk = *(LocalAddress + 3);
749 writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
751 case ELF::R_PPC64_REL16_LO: {
752 uint64_t FinalAddress = (Section.LoadAddress + Offset);
753 uint64_t Delta = Value - FinalAddress + Addend;
754 writeInt16BE(LocalAddress, applyPPClo(Delta));
756 case ELF::R_PPC64_REL16_HI: {
757 uint64_t FinalAddress = (Section.LoadAddress + Offset);
758 uint64_t Delta = Value - FinalAddress + Addend;
759 writeInt16BE(LocalAddress, applyPPChi(Delta));
761 case ELF::R_PPC64_REL16_HA: {
762 uint64_t FinalAddress = (Section.LoadAddress + Offset);
763 uint64_t Delta = Value - FinalAddress + Addend;
764 writeInt16BE(LocalAddress, applyPPCha(Delta));
766 case ELF::R_PPC64_ADDR32: {
767 int32_t Result = static_cast<int32_t>(Value + Addend);
768 if (SignExtend32<32>(Result) != Result)
769 llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
770 writeInt32BE(LocalAddress, Result);
772 case ELF::R_PPC64_REL24: {
773 uint64_t FinalAddress = (Section.LoadAddress + Offset);
774 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
775 if (SignExtend32<24>(delta) != delta)
776 llvm_unreachable("Relocation R_PPC64_REL24 overflow");
777 // Generates a 'bl <address>' instruction
778 writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
780 case ELF::R_PPC64_REL32: {
781 uint64_t FinalAddress = (Section.LoadAddress + Offset);
782 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
783 if (SignExtend32<32>(delta) != delta)
784 llvm_unreachable("Relocation R_PPC64_REL32 overflow");
785 writeInt32BE(LocalAddress, delta);
787 case ELF::R_PPC64_REL64: {
788 uint64_t FinalAddress = (Section.LoadAddress + Offset);
789 uint64_t Delta = Value - FinalAddress + Addend;
790 writeInt64BE(LocalAddress, Delta);
792 case ELF::R_PPC64_ADDR64:
793 writeInt64BE(LocalAddress, Value + Addend);
798 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
799 uint64_t Offset, uint64_t Value,
800 uint32_t Type, int64_t Addend) {
801 uint8_t *LocalAddress = Section.Address + Offset;
804 llvm_unreachable("Relocation type not implemented yet!");
806 case ELF::R_390_PC16DBL:
807 case ELF::R_390_PLT16DBL: {
808 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
809 assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
810 writeInt16BE(LocalAddress, Delta / 2);
813 case ELF::R_390_PC32DBL:
814 case ELF::R_390_PLT32DBL: {
815 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
816 assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
817 writeInt32BE(LocalAddress, Delta / 2);
820 case ELF::R_390_PC32: {
821 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
822 assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
823 writeInt32BE(LocalAddress, Delta);
827 writeInt64BE(LocalAddress, Value + Addend);
832 // The target location for the relocation is described by RE.SectionID and
833 // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
834 // SectionEntry has three members describing its location.
835 // SectionEntry::Address is the address at which the section has been loaded
836 // into memory in the current (host) process. SectionEntry::LoadAddress is the
837 // address that the section will have in the target process.
838 // SectionEntry::ObjAddress is the address of the bits for this section in the
839 // original emitted object image (also in the current address space).
841 // Relocations will be applied as if the section were loaded at
842 // SectionEntry::LoadAddress, but they will be applied at an address based
843 // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
844 // Target memory contents if they are required for value calculations.
846 // The Value parameter here is the load address of the symbol for the
847 // relocation to be applied. For relocations which refer to symbols in the
848 // current object Value will be the LoadAddress of the section in which
849 // the symbol resides (RE.Addend provides additional information about the
850 // symbol location). For external symbols, Value will be the address of the
851 // symbol in the target address space.
852 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
854 const SectionEntry &Section = Sections[RE.SectionID];
855 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
859 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
860 uint64_t Offset, uint64_t Value,
861 uint32_t Type, int64_t Addend,
862 uint64_t SymOffset) {
865 resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
868 resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
869 (uint32_t)(Addend & 0xffffffffL));
871 case Triple::aarch64:
872 case Triple::aarch64_be:
873 resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
875 case Triple::arm: // Fall through.
878 case Triple::thumbeb:
879 resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
880 (uint32_t)(Addend & 0xffffffffL));
882 case Triple::mips: // Fall through.
884 resolveMIPSRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL),
885 Type, (uint32_t)(Addend & 0xffffffffL));
887 case Triple::ppc64: // Fall through.
888 case Triple::ppc64le:
889 resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
891 case Triple::systemz:
892 resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
895 llvm_unreachable("Unsupported CPU type!");
899 relocation_iterator RuntimeDyldELF::processRelocationRef(
900 unsigned SectionID, relocation_iterator RelI,
901 const ObjectFile &Obj,
902 ObjSectionToIDMap &ObjSectionToID,
905 Check(RelI->getType(RelType));
907 Check(getELFRelocationAddend(*RelI, Addend));
908 symbol_iterator Symbol = RelI->getSymbol();
910 // Obtain the symbol name which is referenced in the relocation
911 StringRef TargetName;
912 if (Symbol != Obj.symbol_end())
913 Symbol->getName(TargetName);
914 DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
915 << " TargetName: " << TargetName << "\n");
916 RelocationValueRef Value;
917 // First search for the symbol in the local symbol table
918 SymbolRef::Type SymType = SymbolRef::ST_Unknown;
920 // Search for the symbol in the global symbol table
921 RTDyldSymbolTable::const_iterator gsi = GlobalSymbolTable.end();
922 if (Symbol != Obj.symbol_end()) {
923 gsi = GlobalSymbolTable.find(TargetName.data());
924 Symbol->getType(SymType);
926 if (gsi != GlobalSymbolTable.end()) {
927 const auto &SymInfo = gsi->second;
928 Value.SectionID = SymInfo.getSectionID();
929 Value.Offset = SymInfo.getOffset();
930 Value.Addend = SymInfo.getOffset() + Addend;
933 case SymbolRef::ST_Debug: {
934 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
935 // and can be changed by another developers. Maybe best way is add
936 // a new symbol type ST_Section to SymbolRef and use it.
937 section_iterator si(Obj.section_end());
938 Symbol->getSection(si);
939 if (si == Obj.section_end())
940 llvm_unreachable("Symbol section not found, bad object file format!");
941 DEBUG(dbgs() << "\t\tThis is section symbol\n");
942 bool isCode = si->isText();
943 Value.SectionID = findOrEmitSection(Obj, (*si), isCode, ObjSectionToID);
944 Value.Addend = Addend;
947 case SymbolRef::ST_Data:
948 case SymbolRef::ST_Unknown: {
949 Value.SymbolName = TargetName.data();
950 Value.Addend = Addend;
952 // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
953 // will manifest here as a NULL symbol name.
954 // We can set this as a valid (but empty) symbol name, and rely
955 // on addRelocationForSymbol to handle this.
956 if (!Value.SymbolName)
957 Value.SymbolName = "";
961 llvm_unreachable("Unresolved symbol type!");
967 Check(RelI->getOffset(Offset));
969 DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
971 if ((Arch == Triple::aarch64 || Arch == Triple::aarch64_be) &&
972 (RelType == ELF::R_AARCH64_CALL26 || RelType == ELF::R_AARCH64_JUMP26)) {
973 // This is an AArch64 branch relocation, need to use a stub function.
974 DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
975 SectionEntry &Section = Sections[SectionID];
977 // Look for an existing stub.
978 StubMap::const_iterator i = Stubs.find(Value);
979 if (i != Stubs.end()) {
980 resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
982 DEBUG(dbgs() << " Stub function found\n");
984 // Create a new stub function.
985 DEBUG(dbgs() << " Create a new stub function\n");
986 Stubs[Value] = Section.StubOffset;
987 uint8_t *StubTargetAddr =
988 createStubFunction(Section.Address + Section.StubOffset);
990 RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.Address,
991 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
992 RelocationEntry REmovk_g2(SectionID, StubTargetAddr - Section.Address + 4,
993 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
994 RelocationEntry REmovk_g1(SectionID, StubTargetAddr - Section.Address + 8,
995 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
996 RelocationEntry REmovk_g0(SectionID,
997 StubTargetAddr - Section.Address + 12,
998 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
1000 if (Value.SymbolName) {
1001 addRelocationForSymbol(REmovz_g3, Value.SymbolName);
1002 addRelocationForSymbol(REmovk_g2, Value.SymbolName);
1003 addRelocationForSymbol(REmovk_g1, Value.SymbolName);
1004 addRelocationForSymbol(REmovk_g0, Value.SymbolName);
1006 addRelocationForSection(REmovz_g3, Value.SectionID);
1007 addRelocationForSection(REmovk_g2, Value.SectionID);
1008 addRelocationForSection(REmovk_g1, Value.SectionID);
1009 addRelocationForSection(REmovk_g0, Value.SectionID);
1011 resolveRelocation(Section, Offset,
1012 (uint64_t)Section.Address + Section.StubOffset, RelType,
1014 Section.StubOffset += getMaxStubSize();
1016 } else if (Arch == Triple::arm &&
1017 (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
1018 RelType == ELF::R_ARM_JUMP24)) {
1019 // This is an ARM branch relocation, need to use a stub function.
1020 DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
1021 SectionEntry &Section = Sections[SectionID];
1023 // Look for an existing stub.
1024 StubMap::const_iterator i = Stubs.find(Value);
1025 if (i != Stubs.end()) {
1026 resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
1028 DEBUG(dbgs() << " Stub function found\n");
1030 // Create a new stub function.
1031 DEBUG(dbgs() << " Create a new stub function\n");
1032 Stubs[Value] = Section.StubOffset;
1033 uint8_t *StubTargetAddr =
1034 createStubFunction(Section.Address + Section.StubOffset);
1035 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1036 ELF::R_ARM_PRIVATE_0, Value.Addend);
1037 if (Value.SymbolName)
1038 addRelocationForSymbol(RE, Value.SymbolName);
1040 addRelocationForSection(RE, Value.SectionID);
1042 resolveRelocation(Section, Offset,
1043 (uint64_t)Section.Address + Section.StubOffset, RelType,
1045 Section.StubOffset += getMaxStubSize();
1047 } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
1048 RelType == ELF::R_MIPS_26) {
1049 // This is an Mips branch relocation, need to use a stub function.
1050 DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1051 SectionEntry &Section = Sections[SectionID];
1052 uint8_t *Target = Section.Address + Offset;
1053 uint32_t *TargetAddress = (uint32_t *)Target;
1055 // Extract the addend from the instruction.
1056 uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
1058 Value.Addend += Addend;
1060 // Look up for existing stub.
1061 StubMap::const_iterator i = Stubs.find(Value);
1062 if (i != Stubs.end()) {
1063 RelocationEntry RE(SectionID, Offset, RelType, i->second);
1064 addRelocationForSection(RE, SectionID);
1065 DEBUG(dbgs() << " Stub function found\n");
1067 // Create a new stub function.
1068 DEBUG(dbgs() << " Create a new stub function\n");
1069 Stubs[Value] = Section.StubOffset;
1070 uint8_t *StubTargetAddr =
1071 createStubFunction(Section.Address + Section.StubOffset);
1073 // Creating Hi and Lo relocations for the filled stub instructions.
1074 RelocationEntry REHi(SectionID, StubTargetAddr - Section.Address,
1075 ELF::R_MIPS_UNUSED1, Value.Addend);
1076 RelocationEntry RELo(SectionID, StubTargetAddr - Section.Address + 4,
1077 ELF::R_MIPS_UNUSED2, Value.Addend);
1079 if (Value.SymbolName) {
1080 addRelocationForSymbol(REHi, Value.SymbolName);
1081 addRelocationForSymbol(RELo, Value.SymbolName);
1083 addRelocationForSection(REHi, Value.SectionID);
1084 addRelocationForSection(RELo, Value.SectionID);
1087 RelocationEntry RE(SectionID, Offset, RelType, Section.StubOffset);
1088 addRelocationForSection(RE, SectionID);
1089 Section.StubOffset += getMaxStubSize();
1091 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1092 if (RelType == ELF::R_PPC64_REL24) {
1093 // Determine ABI variant in use for this object.
1094 unsigned AbiVariant;
1095 Obj.getPlatformFlags(AbiVariant);
1096 AbiVariant &= ELF::EF_PPC64_ABI;
1097 // A PPC branch relocation will need a stub function if the target is
1098 // an external symbol (Symbol::ST_Unknown) or if the target address
1099 // is not within the signed 24-bits branch address.
1100 SectionEntry &Section = Sections[SectionID];
1101 uint8_t *Target = Section.Address + Offset;
1102 bool RangeOverflow = false;
1103 if (SymType != SymbolRef::ST_Unknown) {
1104 if (AbiVariant != 2) {
1105 // In the ELFv1 ABI, a function call may point to the .opd entry,
1106 // so the final symbol value is calculated based on the relocation
1107 // values in the .opd section.
1108 findOPDEntrySection(Obj, ObjSectionToID, Value);
1110 // In the ELFv2 ABI, a function symbol may provide a local entry
1111 // point, which must be used for direct calls.
1113 Symbol->getOther(SymOther);
1114 Value.Addend += ELF::decodePPC64LocalEntryOffset(SymOther);
1116 uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
1117 int32_t delta = static_cast<int32_t>(Target - RelocTarget);
1118 // If it is within 24-bits branch range, just set the branch target
1119 if (SignExtend32<24>(delta) == delta) {
1120 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1121 if (Value.SymbolName)
1122 addRelocationForSymbol(RE, Value.SymbolName);
1124 addRelocationForSection(RE, Value.SectionID);
1126 RangeOverflow = true;
1129 if (SymType == SymbolRef::ST_Unknown || RangeOverflow) {
1130 // It is an external symbol (SymbolRef::ST_Unknown) or within a range
1131 // larger than 24-bits.
1132 StubMap::const_iterator i = Stubs.find(Value);
1133 if (i != Stubs.end()) {
1134 // Symbol function stub already created, just relocate to it
1135 resolveRelocation(Section, Offset,
1136 (uint64_t)Section.Address + i->second, RelType, 0);
1137 DEBUG(dbgs() << " Stub function found\n");
1139 // Create a new stub function.
1140 DEBUG(dbgs() << " Create a new stub function\n");
1141 Stubs[Value] = Section.StubOffset;
1142 uint8_t *StubTargetAddr =
1143 createStubFunction(Section.Address + Section.StubOffset,
1145 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1146 ELF::R_PPC64_ADDR64, Value.Addend);
1148 // Generates the 64-bits address loads as exemplified in section
1149 // 4.5.1 in PPC64 ELF ABI. Note that the relocations need to
1150 // apply to the low part of the instructions, so we have to update
1151 // the offset according to the target endianness.
1152 uint64_t StubRelocOffset = StubTargetAddr - Section.Address;
1153 if (!IsTargetLittleEndian)
1154 StubRelocOffset += 2;
1156 RelocationEntry REhst(SectionID, StubRelocOffset + 0,
1157 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1158 RelocationEntry REhr(SectionID, StubRelocOffset + 4,
1159 ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1160 RelocationEntry REh(SectionID, StubRelocOffset + 12,
1161 ELF::R_PPC64_ADDR16_HI, Value.Addend);
1162 RelocationEntry REl(SectionID, StubRelocOffset + 16,
1163 ELF::R_PPC64_ADDR16_LO, Value.Addend);
1165 if (Value.SymbolName) {
1166 addRelocationForSymbol(REhst, Value.SymbolName);
1167 addRelocationForSymbol(REhr, Value.SymbolName);
1168 addRelocationForSymbol(REh, Value.SymbolName);
1169 addRelocationForSymbol(REl, Value.SymbolName);
1171 addRelocationForSection(REhst, Value.SectionID);
1172 addRelocationForSection(REhr, Value.SectionID);
1173 addRelocationForSection(REh, Value.SectionID);
1174 addRelocationForSection(REl, Value.SectionID);
1177 resolveRelocation(Section, Offset,
1178 (uint64_t)Section.Address + Section.StubOffset,
1180 Section.StubOffset += getMaxStubSize();
1182 if (SymType == SymbolRef::ST_Unknown) {
1183 // Restore the TOC for external calls
1184 if (AbiVariant == 2)
1185 writeInt32BE(Target + 4, 0xE8410018); // ld r2,28(r1)
1187 writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
1190 } else if (RelType == ELF::R_PPC64_TOC16 ||
1191 RelType == ELF::R_PPC64_TOC16_DS ||
1192 RelType == ELF::R_PPC64_TOC16_LO ||
1193 RelType == ELF::R_PPC64_TOC16_LO_DS ||
1194 RelType == ELF::R_PPC64_TOC16_HI ||
1195 RelType == ELF::R_PPC64_TOC16_HA) {
1196 // These relocations are supposed to subtract the TOC address from
1197 // the final value. This does not fit cleanly into the RuntimeDyld
1198 // scheme, since there may be *two* sections involved in determining
1199 // the relocation value (the section of the symbol refered to by the
1200 // relocation, and the TOC section associated with the current module).
1202 // Fortunately, these relocations are currently only ever generated
1203 // refering to symbols that themselves reside in the TOC, which means
1204 // that the two sections are actually the same. Thus they cancel out
1205 // and we can immediately resolve the relocation right now.
1207 case ELF::R_PPC64_TOC16: RelType = ELF::R_PPC64_ADDR16; break;
1208 case ELF::R_PPC64_TOC16_DS: RelType = ELF::R_PPC64_ADDR16_DS; break;
1209 case ELF::R_PPC64_TOC16_LO: RelType = ELF::R_PPC64_ADDR16_LO; break;
1210 case ELF::R_PPC64_TOC16_LO_DS: RelType = ELF::R_PPC64_ADDR16_LO_DS; break;
1211 case ELF::R_PPC64_TOC16_HI: RelType = ELF::R_PPC64_ADDR16_HI; break;
1212 case ELF::R_PPC64_TOC16_HA: RelType = ELF::R_PPC64_ADDR16_HA; break;
1213 default: llvm_unreachable("Wrong relocation type.");
1216 RelocationValueRef TOCValue;
1217 findPPC64TOCSection(Obj, ObjSectionToID, TOCValue);
1218 if (Value.SymbolName || Value.SectionID != TOCValue.SectionID)
1219 llvm_unreachable("Unsupported TOC relocation.");
1220 Value.Addend -= TOCValue.Addend;
1221 resolveRelocation(Sections[SectionID], Offset, Value.Addend, RelType, 0);
1223 // There are two ways to refer to the TOC address directly: either
1224 // via a ELF::R_PPC64_TOC relocation (where both symbol and addend are
1225 // ignored), or via any relocation that refers to the magic ".TOC."
1226 // symbols (in which case the addend is respected).
1227 if (RelType == ELF::R_PPC64_TOC) {
1228 RelType = ELF::R_PPC64_ADDR64;
1229 findPPC64TOCSection(Obj, ObjSectionToID, Value);
1230 } else if (TargetName == ".TOC.") {
1231 findPPC64TOCSection(Obj, ObjSectionToID, Value);
1232 Value.Addend += Addend;
1235 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1237 if (Value.SymbolName)
1238 addRelocationForSymbol(RE, Value.SymbolName);
1240 addRelocationForSection(RE, Value.SectionID);
1242 } else if (Arch == Triple::systemz &&
1243 (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
1244 // Create function stubs for both PLT and GOT references, regardless of
1245 // whether the GOT reference is to data or code. The stub contains the
1246 // full address of the symbol, as needed by GOT references, and the
1247 // executable part only adds an overhead of 8 bytes.
1249 // We could try to conserve space by allocating the code and data
1250 // parts of the stub separately. However, as things stand, we allocate
1251 // a stub for every relocation, so using a GOT in JIT code should be
1252 // no less space efficient than using an explicit constant pool.
1253 DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1254 SectionEntry &Section = Sections[SectionID];
1256 // Look for an existing stub.
1257 StubMap::const_iterator i = Stubs.find(Value);
1258 uintptr_t StubAddress;
1259 if (i != Stubs.end()) {
1260 StubAddress = uintptr_t(Section.Address) + i->second;
1261 DEBUG(dbgs() << " Stub function found\n");
1263 // Create a new stub function.
1264 DEBUG(dbgs() << " Create a new stub function\n");
1266 uintptr_t BaseAddress = uintptr_t(Section.Address);
1267 uintptr_t StubAlignment = getStubAlignment();
1268 StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1270 unsigned StubOffset = StubAddress - BaseAddress;
1272 Stubs[Value] = StubOffset;
1273 createStubFunction((uint8_t *)StubAddress);
1274 RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
1276 if (Value.SymbolName)
1277 addRelocationForSymbol(RE, Value.SymbolName);
1279 addRelocationForSection(RE, Value.SectionID);
1280 Section.StubOffset = StubOffset + getMaxStubSize();
1283 if (RelType == ELF::R_390_GOTENT)
1284 resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
1287 resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1288 } else if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_PLT32) {
1289 // The way the PLT relocations normally work is that the linker allocates
1291 // PLT and this relocation makes a PC-relative call into the PLT. The PLT
1292 // entry will then jump to an address provided by the GOT. On first call,
1294 // GOT address will point back into PLT code that resolves the symbol. After
1295 // the first call, the GOT entry points to the actual function.
1297 // For local functions we're ignoring all of that here and just replacing
1298 // the PLT32 relocation type with PC32, which will translate the relocation
1299 // into a PC-relative call directly to the function. For external symbols we
1300 // can't be sure the function will be within 2^32 bytes of the call site, so
1301 // we need to create a stub, which calls into the GOT. This case is
1302 // equivalent to the usual PLT implementation except that we use the stub
1303 // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1304 // rather than allocating a PLT section.
1305 if (Value.SymbolName) {
1306 // This is a call to an external function.
1307 // Look for an existing stub.
1308 SectionEntry &Section = Sections[SectionID];
1309 StubMap::const_iterator i = Stubs.find(Value);
1310 uintptr_t StubAddress;
1311 if (i != Stubs.end()) {
1312 StubAddress = uintptr_t(Section.Address) + i->second;
1313 DEBUG(dbgs() << " Stub function found\n");
1315 // Create a new stub function (equivalent to a PLT entry).
1316 DEBUG(dbgs() << " Create a new stub function\n");
1318 uintptr_t BaseAddress = uintptr_t(Section.Address);
1319 uintptr_t StubAlignment = getStubAlignment();
1320 StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1322 unsigned StubOffset = StubAddress - BaseAddress;
1323 Stubs[Value] = StubOffset;
1324 createStubFunction((uint8_t *)StubAddress);
1326 // Create a GOT entry for the external function.
1327 GOTEntries.push_back(Value);
1329 // Make our stub function a relative call to the GOT entry.
1330 RelocationEntry RE(SectionID, StubOffset + 2, ELF::R_X86_64_GOTPCREL,
1332 addRelocationForSymbol(RE, Value.SymbolName);
1334 // Bump our stub offset counter
1335 Section.StubOffset = StubOffset + getMaxStubSize();
1338 // Make the target call a call into the stub table.
1339 resolveRelocation(Section, Offset, StubAddress, ELF::R_X86_64_PC32,
1342 RelocationEntry RE(SectionID, Offset, ELF::R_X86_64_PC32, Value.Addend,
1344 addRelocationForSection(RE, Value.SectionID);
1347 if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_GOTPCREL) {
1348 GOTEntries.push_back(Value);
1350 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1351 if (Value.SymbolName)
1352 addRelocationForSymbol(RE, Value.SymbolName);
1354 addRelocationForSection(RE, Value.SectionID);
1359 void RuntimeDyldELF::updateGOTEntries(StringRef Name, uint64_t Addr) {
1361 SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator it;
1362 SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator end = GOTs.end();
1364 for (it = GOTs.begin(); it != end; ++it) {
1365 GOTRelocations &GOTEntries = it->second;
1366 for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1367 if (GOTEntries[i].SymbolName != nullptr &&
1368 GOTEntries[i].SymbolName == Name) {
1369 GOTEntries[i].Offset = Addr;
1375 size_t RuntimeDyldELF::getGOTEntrySize() {
1376 // We don't use the GOT in all of these cases, but it's essentially free
1377 // to put them all here.
1380 case Triple::x86_64:
1381 case Triple::aarch64:
1382 case Triple::aarch64_be:
1384 case Triple::ppc64le:
1385 case Triple::systemz:
1386 Result = sizeof(uint64_t);
1392 case Triple::mipsel:
1393 Result = sizeof(uint32_t);
1396 llvm_unreachable("Unsupported CPU type!");
1401 uint64_t RuntimeDyldELF::findGOTEntry(uint64_t LoadAddress, uint64_t Offset) {
1403 const size_t GOTEntrySize = getGOTEntrySize();
1405 SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator it;
1406 SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator end =
1410 for (it = GOTs.begin(); it != end; ++it) {
1411 SID GOTSectionID = it->first;
1412 const GOTRelocations &GOTEntries = it->second;
1414 // Find the matching entry in our vector.
1415 uint64_t SymbolOffset = 0;
1416 for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1417 if (!GOTEntries[i].SymbolName) {
1418 if (getSectionLoadAddress(GOTEntries[i].SectionID) == LoadAddress &&
1419 GOTEntries[i].Offset == Offset) {
1421 SymbolOffset = GOTEntries[i].Offset;
1425 // GOT entries for external symbols use the addend as the address when
1426 // the external symbol has been resolved.
1427 if (GOTEntries[i].Offset == LoadAddress) {
1429 // Don't use the Addend here. The relocation handler will use it.
1435 if (GOTIndex != -1) {
1436 if (GOTEntrySize == sizeof(uint64_t)) {
1437 uint64_t *LocalGOTAddr = (uint64_t *)getSectionAddress(GOTSectionID);
1438 // Fill in this entry with the address of the symbol being referenced.
1439 LocalGOTAddr[GOTIndex] = LoadAddress + SymbolOffset;
1441 uint32_t *LocalGOTAddr = (uint32_t *)getSectionAddress(GOTSectionID);
1442 // Fill in this entry with the address of the symbol being referenced.
1443 LocalGOTAddr[GOTIndex] = (uint32_t)(LoadAddress + SymbolOffset);
1446 // Calculate the load address of this entry
1447 return getSectionLoadAddress(GOTSectionID) + (GOTIndex * GOTEntrySize);
1451 assert(GOTIndex != -1 && "Unable to find requested GOT entry.");
1455 void RuntimeDyldELF::finalizeLoad(const ObjectFile &Obj,
1456 ObjSectionToIDMap &SectionMap) {
1457 // If necessary, allocate the global offset table
1458 size_t numGOTEntries = GOTEntries.size();
1459 if (numGOTEntries != 0) {
1460 // Allocate memory for the section
1461 unsigned SectionID = Sections.size();
1462 size_t TotalSize = numGOTEntries * getGOTEntrySize();
1463 uint8_t *Addr = MemMgr.allocateDataSection(TotalSize, getGOTEntrySize(),
1464 SectionID, ".got", false);
1466 report_fatal_error("Unable to allocate memory for GOT!");
1468 GOTs.push_back(std::make_pair(SectionID, GOTEntries));
1469 Sections.push_back(SectionEntry(".got", Addr, TotalSize, 0));
1470 // For now, initialize all GOT entries to zero. We'll fill them in as
1471 // needed when GOT-based relocations are applied.
1472 memset(Addr, 0, TotalSize);
1475 // Look for and record the EH frame section.
1476 ObjSectionToIDMap::iterator i, e;
1477 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
1478 const SectionRef &Section = i->first;
1480 Section.getName(Name);
1481 if (Name == ".eh_frame") {
1482 UnregisteredEHFrameSections.push_back(i->second);
1488 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile &Obj) const {