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/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ExecutionEngine/ObjectBuffer.h"
23 #include "llvm/ExecutionEngine/ObjectImage.h"
24 #include "llvm/Object/ELFObjectFile.h"
25 #include "llvm/Object/ObjectFile.h"
26 #include "llvm/Support/ELF.h"
27 #include "llvm/Support/MemoryBuffer.h"
30 using namespace llvm::object;
34 static inline error_code check(error_code Err) {
36 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(MemoryBuffer *Wrapper, error_code &ec);
56 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
57 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr);
59 // Methods for type inquiry through isa, cast and dyn_cast
60 static inline bool classof(const Binary *v) {
61 return (isa<ELFObjectFile<ELFT>>(v) &&
62 classof(cast<ELFObjectFile<ELFT>>(v)));
64 static inline bool classof(const ELFObjectFile<ELFT> *v) {
65 return v->isDyldType();
69 template <class ELFT> class ELFObjectImage : public ObjectImageCommon {
71 DyldELFObject<ELFT> *DyldObj;
75 ELFObjectImage(ObjectBuffer *Input, DyldELFObject<ELFT> *Obj)
76 : ObjectImageCommon(Input, Obj), DyldObj(Obj), Registered(false) {}
78 virtual ~ELFObjectImage() {
80 deregisterWithDebugger();
83 // Subclasses can override these methods to update the image with loaded
84 // addresses for sections and common symbols
85 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr) override {
86 DyldObj->updateSectionAddress(Sec, Addr);
89 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr) override {
90 DyldObj->updateSymbolAddress(Sym, Addr);
93 void registerWithDebugger() override {
94 JITRegistrar::getGDBRegistrar().registerObject(*Buffer);
97 void deregisterWithDebugger() override {
98 JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer);
102 // The MemoryBuffer passed into this constructor is just a wrapper around the
103 // actual memory. Ultimately, the Binary parent class will take ownership of
104 // this MemoryBuffer object but not the underlying memory.
105 template <class ELFT>
106 DyldELFObject<ELFT>::DyldELFObject(MemoryBuffer *Wrapper, error_code &ec)
107 : ELFObjectFile<ELFT>(Wrapper, ec) {
108 this->isDyldELFObject = true;
111 template <class ELFT>
112 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
114 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
116 const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
118 // This assumes the address passed in matches the target address bitness
119 // The template-based type cast handles everything else.
120 shdr->sh_addr = static_cast<addr_type>(Addr);
123 template <class ELFT>
124 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
127 Elf_Sym *sym = const_cast<Elf_Sym *>(
128 ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
130 // This assumes the address passed in matches the target address bitness
131 // The template-based type cast handles everything else.
132 sym->st_value = static_cast<addr_type>(Addr);
139 void RuntimeDyldELF::registerEHFrames() {
142 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
143 SID EHFrameSID = UnregisteredEHFrameSections[i];
144 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
145 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
146 size_t EHFrameSize = Sections[EHFrameSID].Size;
147 MemMgr->registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
148 RegisteredEHFrameSections.push_back(EHFrameSID);
150 UnregisteredEHFrameSections.clear();
153 void RuntimeDyldELF::deregisterEHFrames() {
156 for (int i = 0, e = RegisteredEHFrameSections.size(); i != e; ++i) {
157 SID EHFrameSID = RegisteredEHFrameSections[i];
158 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
159 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
160 size_t EHFrameSize = Sections[EHFrameSID].Size;
161 MemMgr->deregisterEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
163 RegisteredEHFrameSections.clear();
167 RuntimeDyldELF::createObjectImageFromFile(object::ObjectFile *ObjFile) {
172 MemoryBuffer *Buffer =
173 MemoryBuffer::getMemBuffer(ObjFile->getData(), "", false);
175 if (ObjFile->getBytesInAddress() == 4 && ObjFile->isLittleEndian()) {
176 DyldELFObject<ELFType<support::little, 2, false>> *Obj =
177 new DyldELFObject<ELFType<support::little, 2, false>>(Buffer, ec);
178 return new ELFObjectImage<ELFType<support::little, 2, false>>(NULL, Obj);
179 } else if (ObjFile->getBytesInAddress() == 4 && !ObjFile->isLittleEndian()) {
180 DyldELFObject<ELFType<support::big, 2, false>> *Obj =
181 new DyldELFObject<ELFType<support::big, 2, false>>(Buffer, ec);
182 return new ELFObjectImage<ELFType<support::big, 2, false>>(NULL, Obj);
183 } else if (ObjFile->getBytesInAddress() == 8 && !ObjFile->isLittleEndian()) {
184 DyldELFObject<ELFType<support::big, 2, true>> *Obj =
185 new DyldELFObject<ELFType<support::big, 2, true>>(Buffer, ec);
186 return new ELFObjectImage<ELFType<support::big, 2, true>>(NULL, Obj);
187 } else if (ObjFile->getBytesInAddress() == 8 && ObjFile->isLittleEndian()) {
188 DyldELFObject<ELFType<support::little, 2, true>> *Obj =
189 new DyldELFObject<ELFType<support::little, 2, true>>(Buffer, ec);
190 return new ELFObjectImage<ELFType<support::little, 2, true>>(NULL, Obj);
192 llvm_unreachable("Unexpected ELF format");
195 ObjectImage *RuntimeDyldELF::createObjectImage(ObjectBuffer *Buffer) {
196 if (Buffer->getBufferSize() < ELF::EI_NIDENT)
197 llvm_unreachable("Unexpected ELF object size");
198 std::pair<unsigned char, unsigned char> Ident =
199 std::make_pair((uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS],
200 (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
203 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) {
204 DyldELFObject<ELFType<support::little, 4, false>> *Obj =
205 new DyldELFObject<ELFType<support::little, 4, false>>(
206 Buffer->getMemBuffer(), ec);
207 return new ELFObjectImage<ELFType<support::little, 4, false>>(Buffer, Obj);
208 } else if (Ident.first == ELF::ELFCLASS32 &&
209 Ident.second == ELF::ELFDATA2MSB) {
210 DyldELFObject<ELFType<support::big, 4, false>> *Obj =
211 new DyldELFObject<ELFType<support::big, 4, false>>(
212 Buffer->getMemBuffer(), ec);
213 return new ELFObjectImage<ELFType<support::big, 4, false>>(Buffer, Obj);
214 } else if (Ident.first == ELF::ELFCLASS64 &&
215 Ident.second == ELF::ELFDATA2MSB) {
216 DyldELFObject<ELFType<support::big, 8, true>> *Obj =
217 new DyldELFObject<ELFType<support::big, 8, true>>(
218 Buffer->getMemBuffer(), ec);
219 return new ELFObjectImage<ELFType<support::big, 8, true>>(Buffer, Obj);
220 } else if (Ident.first == ELF::ELFCLASS64 &&
221 Ident.second == ELF::ELFDATA2LSB) {
222 DyldELFObject<ELFType<support::little, 8, true>> *Obj =
223 new DyldELFObject<ELFType<support::little, 8, true>>(
224 Buffer->getMemBuffer(), ec);
225 return new ELFObjectImage<ELFType<support::little, 8, true>>(Buffer, Obj);
227 llvm_unreachable("Unexpected ELF format");
230 RuntimeDyldELF::~RuntimeDyldELF() {}
232 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
233 uint64_t Offset, uint64_t Value,
234 uint32_t Type, int64_t Addend,
235 uint64_t SymOffset) {
238 llvm_unreachable("Relocation type not implemented yet!");
240 case ELF::R_X86_64_64: {
241 uint64_t *Target = reinterpret_cast<uint64_t *>(Section.Address + Offset);
242 *Target = Value + Addend;
243 DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
244 << format("%p\n", Target));
247 case ELF::R_X86_64_32:
248 case ELF::R_X86_64_32S: {
250 assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
251 (Type == ELF::R_X86_64_32S &&
252 ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
253 uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
254 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
255 *Target = TruncatedAddr;
256 DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
257 << format("%p\n", Target));
260 case ELF::R_X86_64_GOTPCREL: {
261 // findGOTEntry returns the 'G + GOT' part of the relocation calculation
262 // based on the load/target address of the GOT (not the current/local addr).
263 uint64_t GOTAddr = findGOTEntry(Value, SymOffset);
264 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
265 uint64_t FinalAddress = Section.LoadAddress + Offset;
266 // The processRelocationRef method combines the symbol offset and the addend
267 // and in most cases that's what we want. For this relocation type, we need
268 // the raw addend, so we subtract the symbol offset to get it.
269 int64_t RealOffset = GOTAddr + Addend - SymOffset - FinalAddress;
270 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
271 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
272 *Target = TruncOffset;
275 case ELF::R_X86_64_PC32: {
276 // Get the placeholder value from the generated object since
277 // a previous relocation attempt may have overwritten the loaded version
278 uint32_t *Placeholder =
279 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
280 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
281 uint64_t FinalAddress = Section.LoadAddress + Offset;
282 int64_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
283 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
284 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
285 *Target = TruncOffset;
288 case ELF::R_X86_64_PC64: {
289 // Get the placeholder value from the generated object since
290 // a previous relocation attempt may have overwritten the loaded version
291 uint64_t *Placeholder =
292 reinterpret_cast<uint64_t *>(Section.ObjAddress + Offset);
293 uint64_t *Target = reinterpret_cast<uint64_t *>(Section.Address + Offset);
294 uint64_t FinalAddress = Section.LoadAddress + Offset;
295 *Target = *Placeholder + Value + Addend - FinalAddress;
301 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
302 uint64_t Offset, uint32_t Value,
303 uint32_t Type, int32_t Addend) {
305 case ELF::R_386_32: {
306 // Get the placeholder value from the generated object since
307 // a previous relocation attempt may have overwritten the loaded version
308 uint32_t *Placeholder =
309 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
310 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
311 *Target = *Placeholder + Value + Addend;
314 case ELF::R_386_PC32: {
315 // Get the placeholder value from the generated object since
316 // a previous relocation attempt may have overwritten the loaded version
317 uint32_t *Placeholder =
318 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
319 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
320 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
321 uint32_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
322 *Target = RealOffset;
326 // There are other relocation types, but it appears these are the
327 // only ones currently used by the LLVM ELF object writer
328 llvm_unreachable("Relocation type not implemented yet!");
333 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
334 uint64_t Offset, uint64_t Value,
335 uint32_t Type, int64_t Addend) {
336 uint32_t *TargetPtr = reinterpret_cast<uint32_t *>(Section.Address + Offset);
337 uint64_t FinalAddress = Section.LoadAddress + Offset;
339 DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
340 << format("%llx", Section.Address + Offset)
341 << " FinalAddress: 0x" << format("%llx", FinalAddress)
342 << " Value: 0x" << format("%llx", Value) << " Type: 0x"
343 << format("%x", Type) << " Addend: 0x" << format("%llx", Addend)
348 llvm_unreachable("Relocation type not implemented yet!");
350 case ELF::R_AARCH64_ABS64: {
351 uint64_t *TargetPtr =
352 reinterpret_cast<uint64_t *>(Section.Address + Offset);
353 *TargetPtr = Value + Addend;
356 case ELF::R_AARCH64_PREL32: {
357 uint64_t Result = Value + Addend - FinalAddress;
358 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
359 static_cast<int64_t>(Result) <= UINT32_MAX);
360 *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU);
363 case ELF::R_AARCH64_CALL26: // fallthrough
364 case ELF::R_AARCH64_JUMP26: {
365 // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
367 uint64_t BranchImm = Value + Addend - FinalAddress;
369 // "Check that -2^27 <= result < 2^27".
370 assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) &&
371 static_cast<int64_t>(BranchImm) < (1LL << 27));
373 // AArch64 code is emitted with .rela relocations. The data already in any
374 // bits affected by the relocation on entry is garbage.
375 *TargetPtr &= 0xfc000000U;
376 // Immediate goes in bits 25:0 of B and BL.
377 *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2;
380 case ELF::R_AARCH64_MOVW_UABS_G3: {
381 uint64_t Result = Value + Addend;
383 // AArch64 code is emitted with .rela relocations. The data already in any
384 // bits affected by the relocation on entry is garbage.
385 *TargetPtr &= 0xffe0001fU;
386 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
387 *TargetPtr |= Result >> (48 - 5);
388 // Shift must be "lsl #48", in bits 22:21
389 assert((*TargetPtr >> 21 & 0x3) == 3 && "invalid shift for relocation");
392 case ELF::R_AARCH64_MOVW_UABS_G2_NC: {
393 uint64_t Result = Value + Addend;
395 // AArch64 code is emitted with .rela relocations. The data already in any
396 // bits affected by the relocation on entry is garbage.
397 *TargetPtr &= 0xffe0001fU;
398 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
399 *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5));
400 // Shift must be "lsl #32", in bits 22:21
401 assert((*TargetPtr >> 21 & 0x3) == 2 && "invalid shift for relocation");
404 case ELF::R_AARCH64_MOVW_UABS_G1_NC: {
405 uint64_t Result = Value + Addend;
407 // AArch64 code is emitted with .rela relocations. The data already in any
408 // bits affected by the relocation on entry is garbage.
409 *TargetPtr &= 0xffe0001fU;
410 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
411 *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5));
412 // Shift must be "lsl #16", in bits 22:2
413 assert((*TargetPtr >> 21 & 0x3) == 1 && "invalid shift for relocation");
416 case ELF::R_AARCH64_MOVW_UABS_G0_NC: {
417 uint64_t Result = Value + Addend;
419 // AArch64 code is emitted with .rela relocations. The data already in any
420 // bits affected by the relocation on entry is garbage.
421 *TargetPtr &= 0xffe0001fU;
422 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
423 *TargetPtr |= ((Result & 0xffffU) << 5);
424 // Shift must be "lsl #0", in bits 22:21.
425 assert((*TargetPtr >> 21 & 0x3) == 0 && "invalid shift for relocation");
428 case ELF::R_AARCH64_ADR_PREL_PG_HI21: {
429 // Operation: Page(S+A) - Page(P)
431 ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL);
433 // Check that -2^32 <= X < 2^32
434 assert(static_cast<int64_t>(Result) >= (-1LL << 32) &&
435 static_cast<int64_t>(Result) < (1LL << 32) &&
436 "overflow check failed for relocation");
438 // AArch64 code is emitted with .rela relocations. The data already in any
439 // bits affected by the relocation on entry is garbage.
440 *TargetPtr &= 0x9f00001fU;
441 // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken
442 // from bits 32:12 of X.
443 *TargetPtr |= ((Result & 0x3000U) << (29 - 12));
444 *TargetPtr |= ((Result & 0x1ffffc000ULL) >> (14 - 5));
447 case ELF::R_AARCH64_LDST32_ABS_LO12_NC: {
449 uint64_t Result = Value + Addend;
451 // AArch64 code is emitted with .rela relocations. The data already in any
452 // bits affected by the relocation on entry is garbage.
453 *TargetPtr &= 0xffc003ffU;
454 // Immediate goes in bits 21:10 of LD/ST instruction, taken
455 // from bits 11:2 of X
456 *TargetPtr |= ((Result & 0xffc) << (10 - 2));
459 case ELF::R_AARCH64_LDST64_ABS_LO12_NC: {
461 uint64_t Result = Value + Addend;
463 // AArch64 code is emitted with .rela relocations. The data already in any
464 // bits affected by the relocation on entry is garbage.
465 *TargetPtr &= 0xffc003ffU;
466 // Immediate goes in bits 21:10 of LD/ST instruction, taken
467 // from bits 11:3 of X
468 *TargetPtr |= ((Result & 0xff8) << (10 - 3));
474 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
475 uint64_t Offset, uint32_t Value,
476 uint32_t Type, int32_t Addend) {
477 // TODO: Add Thumb relocations.
478 uint32_t *Placeholder =
479 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
480 uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset);
481 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
484 DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
485 << Section.Address + Offset
486 << " FinalAddress: " << format("%p", FinalAddress) << " Value: "
487 << format("%x", Value) << " Type: " << format("%x", Type)
488 << " Addend: " << format("%x", Addend) << "\n");
492 llvm_unreachable("Not implemented relocation type!");
494 case ELF::R_ARM_NONE:
496 // Write a 32bit value to relocation address, taking into account the
497 // implicit addend encoded in the target.
498 case ELF::R_ARM_PREL31:
499 case ELF::R_ARM_TARGET1:
500 case ELF::R_ARM_ABS32:
501 *TargetPtr = *Placeholder + Value;
503 // Write first 16 bit of 32 bit value to the mov instruction.
504 // Last 4 bit should be shifted.
505 case ELF::R_ARM_MOVW_ABS_NC:
506 // We are not expecting any other addend in the relocation address.
507 // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
508 // non-contiguous fields.
509 assert((*Placeholder & 0x000F0FFF) == 0);
510 Value = Value & 0xFFFF;
511 *TargetPtr = *Placeholder | (Value & 0xFFF);
512 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
514 // Write last 16 bit of 32 bit value to the mov instruction.
515 // Last 4 bit should be shifted.
516 case ELF::R_ARM_MOVT_ABS:
517 // We are not expecting any other addend in the relocation address.
518 // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
519 assert((*Placeholder & 0x000F0FFF) == 0);
521 Value = (Value >> 16) & 0xFFFF;
522 *TargetPtr = *Placeholder | (Value & 0xFFF);
523 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
525 // Write 24 bit relative value to the branch instruction.
526 case ELF::R_ARM_PC24: // Fall through.
527 case ELF::R_ARM_CALL: // Fall through.
528 case ELF::R_ARM_JUMP24: {
529 int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
530 RelValue = (RelValue & 0x03FFFFFC) >> 2;
531 assert((*TargetPtr & 0xFFFFFF) == 0xFFFFFE);
532 *TargetPtr &= 0xFF000000;
533 *TargetPtr |= RelValue;
536 case ELF::R_ARM_PRIVATE_0:
537 // This relocation is reserved by the ARM ELF ABI for internal use. We
538 // appropriate it here to act as an R_ARM_ABS32 without any addend for use
539 // in the stubs created during JIT (which can't put an addend into the
540 // original object file).
546 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
547 uint64_t Offset, uint32_t Value,
548 uint32_t Type, int32_t Addend) {
549 uint32_t *Placeholder =
550 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
551 uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset);
554 DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
555 << Section.Address + Offset << " FinalAddress: "
556 << format("%p", Section.LoadAddress + Offset) << " Value: "
557 << format("%x", Value) << " Type: " << format("%x", Type)
558 << " Addend: " << format("%x", Addend) << "\n");
562 llvm_unreachable("Not implemented relocation type!");
565 *TargetPtr = Value + (*Placeholder);
568 *TargetPtr = ((*Placeholder) & 0xfc000000) | ((Value & 0x0fffffff) >> 2);
570 case ELF::R_MIPS_HI16:
571 // Get the higher 16-bits. Also add 1 if bit 15 is 1.
572 Value += ((*Placeholder) & 0x0000ffff) << 16;
574 ((*Placeholder) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff);
576 case ELF::R_MIPS_LO16:
577 Value += ((*Placeholder) & 0x0000ffff);
578 *TargetPtr = ((*Placeholder) & 0xffff0000) | (Value & 0xffff);
580 case ELF::R_MIPS_UNUSED1:
581 // Similar to ELF::R_ARM_PRIVATE_0, R_MIPS_UNUSED1 and R_MIPS_UNUSED2
582 // are used for internal JIT purpose. These relocations are similar to
583 // R_MIPS_HI16 and R_MIPS_LO16, but they do not take any addend into
586 ((*TargetPtr) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff);
588 case ELF::R_MIPS_UNUSED2:
589 *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
594 // Return the .TOC. section address to R_PPC64_TOC relocations.
595 uint64_t RuntimeDyldELF::findPPC64TOC() const {
596 // The TOC consists of sections .got, .toc, .tocbss, .plt in that
597 // order. The TOC starts where the first of these sections starts.
598 SectionList::const_iterator it = Sections.begin();
599 SectionList::const_iterator ite = Sections.end();
600 for (; it != ite; ++it) {
601 if (it->Name == ".got" || it->Name == ".toc" || it->Name == ".tocbss" ||
606 // This may happen for
607 // * references to TOC base base (sym@toc, .odp relocation) without
609 // In this case just use the first section (which is usually
610 // the .odp) since the code won't reference the .toc base
612 it = Sections.begin();
615 // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
616 // thus permitting a full 64 Kbytes segment.
617 return it->LoadAddress + 0x8000;
620 // Returns the sections and offset associated with the ODP entry referenced
622 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
623 ObjSectionToIDMap &LocalSections,
624 RelocationValueRef &Rel) {
625 // Get the ELF symbol value (st_value) to compare with Relocation offset in
627 for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections();
629 section_iterator RelSecI = si->getRelocatedSection();
630 if (RelSecI == Obj.end_sections())
633 StringRef RelSectionName;
634 check(RelSecI->getName(RelSectionName));
635 if (RelSectionName != ".opd")
638 for (relocation_iterator i = si->relocation_begin(),
639 e = si->relocation_end();
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));
660 // Just check if following relocation is a R_PPC64_TOC
662 check(i->getType(TypeTOC));
663 if (TypeTOC != ELF::R_PPC64_TOC)
666 // Finally compares the Symbol value and the target symbol offset
667 // to check if this .opd entry refers to the symbol the relocation
669 if (Rel.Addend != (int64_t)TargetSymbolOffset)
672 section_iterator tsi(Obj.end_sections());
673 check(TargetSymbol->getSection(tsi));
676 Rel.SectionID = findOrEmitSection(Obj, (*tsi), IsCode, LocalSections);
677 Rel.Addend = (intptr_t)Addend;
681 llvm_unreachable("Attempting to get address of ODP entry!");
684 // Relocation masks following the #lo(value), #hi(value), #higher(value),
685 // and #highest(value) macros defined in section 4.5.1. Relocation Types
686 // in PPC-elf64abi document.
688 static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
690 static inline uint16_t applyPPChi(uint64_t value) {
691 return (value >> 16) & 0xffff;
694 static inline uint16_t applyPPChigher(uint64_t value) {
695 return (value >> 32) & 0xffff;
698 static inline uint16_t applyPPChighest(uint64_t value) {
699 return (value >> 48) & 0xffff;
702 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
703 uint64_t Offset, uint64_t Value,
704 uint32_t Type, int64_t Addend) {
705 uint8_t *LocalAddress = Section.Address + Offset;
708 llvm_unreachable("Relocation type not implemented yet!");
710 case ELF::R_PPC64_ADDR16_LO:
711 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
713 case ELF::R_PPC64_ADDR16_HI:
714 writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
716 case ELF::R_PPC64_ADDR16_HIGHER:
717 writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
719 case ELF::R_PPC64_ADDR16_HIGHEST:
720 writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
722 case ELF::R_PPC64_ADDR14: {
723 assert(((Value + Addend) & 3) == 0);
724 // Preserve the AA/LK bits in the branch instruction
725 uint8_t aalk = *(LocalAddress + 3);
726 writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
728 case ELF::R_PPC64_ADDR32: {
729 int32_t Result = static_cast<int32_t>(Value + Addend);
730 if (SignExtend32<32>(Result) != Result)
731 llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
732 writeInt32BE(LocalAddress, Result);
734 case ELF::R_PPC64_REL24: {
735 uint64_t FinalAddress = (Section.LoadAddress + Offset);
736 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
737 if (SignExtend32<24>(delta) != delta)
738 llvm_unreachable("Relocation R_PPC64_REL24 overflow");
739 // Generates a 'bl <address>' instruction
740 writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
742 case ELF::R_PPC64_REL32: {
743 uint64_t FinalAddress = (Section.LoadAddress + Offset);
744 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
745 if (SignExtend32<32>(delta) != delta)
746 llvm_unreachable("Relocation R_PPC64_REL32 overflow");
747 writeInt32BE(LocalAddress, delta);
749 case ELF::R_PPC64_REL64: {
750 uint64_t FinalAddress = (Section.LoadAddress + Offset);
751 uint64_t Delta = Value - FinalAddress + Addend;
752 writeInt64BE(LocalAddress, Delta);
754 case ELF::R_PPC64_ADDR64:
755 writeInt64BE(LocalAddress, Value + Addend);
757 case ELF::R_PPC64_TOC:
758 writeInt64BE(LocalAddress, findPPC64TOC());
760 case ELF::R_PPC64_TOC16: {
761 uint64_t TOCStart = findPPC64TOC();
762 Value = applyPPClo((Value + Addend) - TOCStart);
763 writeInt16BE(LocalAddress, applyPPClo(Value));
765 case ELF::R_PPC64_TOC16_DS: {
766 uint64_t TOCStart = findPPC64TOC();
767 Value = ((Value + Addend) - TOCStart);
768 writeInt16BE(LocalAddress, applyPPClo(Value));
773 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
774 uint64_t Offset, uint64_t Value,
775 uint32_t Type, int64_t Addend) {
776 uint8_t *LocalAddress = Section.Address + Offset;
779 llvm_unreachable("Relocation type not implemented yet!");
781 case ELF::R_390_PC16DBL:
782 case ELF::R_390_PLT16DBL: {
783 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
784 assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
785 writeInt16BE(LocalAddress, Delta / 2);
788 case ELF::R_390_PC32DBL:
789 case ELF::R_390_PLT32DBL: {
790 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
791 assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
792 writeInt32BE(LocalAddress, Delta / 2);
795 case ELF::R_390_PC32: {
796 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
797 assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
798 writeInt32BE(LocalAddress, Delta);
802 writeInt64BE(LocalAddress, Value + Addend);
807 // The target location for the relocation is described by RE.SectionID and
808 // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
809 // SectionEntry has three members describing its location.
810 // SectionEntry::Address is the address at which the section has been loaded
811 // into memory in the current (host) process. SectionEntry::LoadAddress is the
812 // address that the section will have in the target process.
813 // SectionEntry::ObjAddress is the address of the bits for this section in the
814 // original emitted object image (also in the current address space).
816 // Relocations will be applied as if the section were loaded at
817 // SectionEntry::LoadAddress, but they will be applied at an address based
818 // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
819 // Target memory contents if they are required for value calculations.
821 // The Value parameter here is the load address of the symbol for the
822 // relocation to be applied. For relocations which refer to symbols in the
823 // current object Value will be the LoadAddress of the section in which
824 // the symbol resides (RE.Addend provides additional information about the
825 // symbol location). For external symbols, Value will be the address of the
826 // symbol in the target address space.
827 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
829 const SectionEntry &Section = Sections[RE.SectionID];
830 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
834 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
835 uint64_t Offset, uint64_t Value,
836 uint32_t Type, int64_t Addend,
837 uint64_t SymOffset) {
840 resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
843 resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
844 (uint32_t)(Addend & 0xffffffffL));
846 case Triple::aarch64:
847 resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
849 case Triple::arm: // Fall through.
851 resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
852 (uint32_t)(Addend & 0xffffffffL));
854 case Triple::mips: // Fall through.
856 resolveMIPSRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL),
857 Type, (uint32_t)(Addend & 0xffffffffL));
859 case Triple::ppc64: // Fall through.
860 case Triple::ppc64le:
861 resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
863 case Triple::systemz:
864 resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
867 llvm_unreachable("Unsupported CPU type!");
871 relocation_iterator RuntimeDyldELF::processRelocationRef(
872 unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
873 ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
876 Check(RelI->getType(RelType));
878 Check(getELFRelocationAddend(*RelI, Addend));
879 symbol_iterator Symbol = RelI->getSymbol();
881 // Obtain the symbol name which is referenced in the relocation
882 StringRef TargetName;
883 if (Symbol != Obj.end_symbols())
884 Symbol->getName(TargetName);
885 DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
886 << " TargetName: " << TargetName << "\n");
887 RelocationValueRef Value;
888 // First search for the symbol in the local symbol table
889 SymbolTableMap::const_iterator lsi = Symbols.end();
890 SymbolRef::Type SymType = SymbolRef::ST_Unknown;
891 if (Symbol != Obj.end_symbols()) {
892 lsi = Symbols.find(TargetName.data());
893 Symbol->getType(SymType);
895 if (lsi != Symbols.end()) {
896 Value.SectionID = lsi->second.first;
897 Value.Offset = lsi->second.second;
898 Value.Addend = lsi->second.second + Addend;
900 // Search for the symbol in the global symbol table
901 SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end();
902 if (Symbol != Obj.end_symbols())
903 gsi = GlobalSymbolTable.find(TargetName.data());
904 if (gsi != GlobalSymbolTable.end()) {
905 Value.SectionID = gsi->second.first;
906 Value.Offset = gsi->second.second;
907 Value.Addend = gsi->second.second + Addend;
910 case SymbolRef::ST_Debug: {
911 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
912 // and can be changed by another developers. Maybe best way is add
913 // a new symbol type ST_Section to SymbolRef and use it.
914 section_iterator si(Obj.end_sections());
915 Symbol->getSection(si);
916 if (si == Obj.end_sections())
917 llvm_unreachable("Symbol section not found, bad object file format!");
918 DEBUG(dbgs() << "\t\tThis is section symbol\n");
919 // Default to 'true' in case isText fails (though it never does).
922 Value.SectionID = findOrEmitSection(Obj, (*si), isCode, ObjSectionToID);
923 Value.Addend = Addend;
926 case SymbolRef::ST_Data:
927 case SymbolRef::ST_Unknown: {
928 Value.SymbolName = TargetName.data();
929 Value.Addend = Addend;
931 // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
932 // will manifest here as a NULL symbol name.
933 // We can set this as a valid (but empty) symbol name, and rely
934 // on addRelocationForSymbol to handle this.
935 if (!Value.SymbolName)
936 Value.SymbolName = "";
940 llvm_unreachable("Unresolved symbol type!");
946 Check(RelI->getOffset(Offset));
948 DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
950 if (Arch == Triple::aarch64 &&
951 (RelType == ELF::R_AARCH64_CALL26 || RelType == ELF::R_AARCH64_JUMP26)) {
952 // This is an AArch64 branch relocation, need to use a stub function.
953 DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
954 SectionEntry &Section = Sections[SectionID];
956 // Look for an existing stub.
957 StubMap::const_iterator i = Stubs.find(Value);
958 if (i != Stubs.end()) {
959 resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
961 DEBUG(dbgs() << " Stub function found\n");
963 // Create a new stub function.
964 DEBUG(dbgs() << " Create a new stub function\n");
965 Stubs[Value] = Section.StubOffset;
966 uint8_t *StubTargetAddr =
967 createStubFunction(Section.Address + Section.StubOffset);
969 RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.Address,
970 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
971 RelocationEntry REmovk_g2(SectionID, StubTargetAddr - Section.Address + 4,
972 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
973 RelocationEntry REmovk_g1(SectionID, StubTargetAddr - Section.Address + 8,
974 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
975 RelocationEntry REmovk_g0(SectionID,
976 StubTargetAddr - Section.Address + 12,
977 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
979 if (Value.SymbolName) {
980 addRelocationForSymbol(REmovz_g3, Value.SymbolName);
981 addRelocationForSymbol(REmovk_g2, Value.SymbolName);
982 addRelocationForSymbol(REmovk_g1, Value.SymbolName);
983 addRelocationForSymbol(REmovk_g0, Value.SymbolName);
985 addRelocationForSection(REmovz_g3, Value.SectionID);
986 addRelocationForSection(REmovk_g2, Value.SectionID);
987 addRelocationForSection(REmovk_g1, Value.SectionID);
988 addRelocationForSection(REmovk_g0, Value.SectionID);
990 resolveRelocation(Section, Offset,
991 (uint64_t)Section.Address + Section.StubOffset, RelType,
993 Section.StubOffset += getMaxStubSize();
995 } else if (Arch == Triple::arm &&
996 (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
997 RelType == ELF::R_ARM_JUMP24)) {
998 // This is an ARM branch relocation, need to use a stub function.
999 DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
1000 SectionEntry &Section = Sections[SectionID];
1002 // Look for an existing stub.
1003 StubMap::const_iterator i = Stubs.find(Value);
1004 if (i != Stubs.end()) {
1005 resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
1007 DEBUG(dbgs() << " Stub function found\n");
1009 // Create a new stub function.
1010 DEBUG(dbgs() << " Create a new stub function\n");
1011 Stubs[Value] = Section.StubOffset;
1012 uint8_t *StubTargetAddr =
1013 createStubFunction(Section.Address + Section.StubOffset);
1014 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1015 ELF::R_ARM_PRIVATE_0, Value.Addend);
1016 if (Value.SymbolName)
1017 addRelocationForSymbol(RE, Value.SymbolName);
1019 addRelocationForSection(RE, Value.SectionID);
1021 resolveRelocation(Section, Offset,
1022 (uint64_t)Section.Address + Section.StubOffset, RelType,
1024 Section.StubOffset += getMaxStubSize();
1026 } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
1027 RelType == ELF::R_MIPS_26) {
1028 // This is an Mips branch relocation, need to use a stub function.
1029 DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1030 SectionEntry &Section = Sections[SectionID];
1031 uint8_t *Target = Section.Address + Offset;
1032 uint32_t *TargetAddress = (uint32_t *)Target;
1034 // Extract the addend from the instruction.
1035 uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
1037 Value.Addend += Addend;
1039 // Look up for existing stub.
1040 StubMap::const_iterator i = Stubs.find(Value);
1041 if (i != Stubs.end()) {
1042 RelocationEntry RE(SectionID, Offset, RelType, i->second);
1043 addRelocationForSection(RE, SectionID);
1044 DEBUG(dbgs() << " Stub function found\n");
1046 // Create a new stub function.
1047 DEBUG(dbgs() << " Create a new stub function\n");
1048 Stubs[Value] = Section.StubOffset;
1049 uint8_t *StubTargetAddr =
1050 createStubFunction(Section.Address + Section.StubOffset);
1052 // Creating Hi and Lo relocations for the filled stub instructions.
1053 RelocationEntry REHi(SectionID, StubTargetAddr - Section.Address,
1054 ELF::R_MIPS_UNUSED1, Value.Addend);
1055 RelocationEntry RELo(SectionID, StubTargetAddr - Section.Address + 4,
1056 ELF::R_MIPS_UNUSED2, Value.Addend);
1058 if (Value.SymbolName) {
1059 addRelocationForSymbol(REHi, Value.SymbolName);
1060 addRelocationForSymbol(RELo, Value.SymbolName);
1062 addRelocationForSection(REHi, Value.SectionID);
1063 addRelocationForSection(RELo, Value.SectionID);
1066 RelocationEntry RE(SectionID, Offset, RelType, Section.StubOffset);
1067 addRelocationForSection(RE, SectionID);
1068 Section.StubOffset += getMaxStubSize();
1070 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1071 if (RelType == ELF::R_PPC64_REL24) {
1072 // A PPC branch relocation will need a stub function if the target is
1073 // an external symbol (Symbol::ST_Unknown) or if the target address
1074 // is not within the signed 24-bits branch address.
1075 SectionEntry &Section = Sections[SectionID];
1076 uint8_t *Target = Section.Address + Offset;
1077 bool RangeOverflow = false;
1078 if (SymType != SymbolRef::ST_Unknown) {
1079 // A function call may points to the .opd entry, so the final symbol
1081 // in calculated based in the relocation values in .opd section.
1082 findOPDEntrySection(Obj, ObjSectionToID, Value);
1083 uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
1084 int32_t delta = static_cast<int32_t>(Target - RelocTarget);
1085 // If it is within 24-bits branch range, just set the branch target
1086 if (SignExtend32<24>(delta) == delta) {
1087 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1088 if (Value.SymbolName)
1089 addRelocationForSymbol(RE, Value.SymbolName);
1091 addRelocationForSection(RE, Value.SectionID);
1093 RangeOverflow = true;
1096 if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
1097 // It is an external symbol (SymbolRef::ST_Unknown) or within a range
1098 // larger than 24-bits.
1099 StubMap::const_iterator i = Stubs.find(Value);
1100 if (i != Stubs.end()) {
1101 // Symbol function stub already created, just relocate to it
1102 resolveRelocation(Section, Offset,
1103 (uint64_t)Section.Address + i->second, RelType, 0);
1104 DEBUG(dbgs() << " Stub function found\n");
1106 // Create a new stub function.
1107 DEBUG(dbgs() << " Create a new stub function\n");
1108 Stubs[Value] = Section.StubOffset;
1109 uint8_t *StubTargetAddr =
1110 createStubFunction(Section.Address + Section.StubOffset);
1111 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1112 ELF::R_PPC64_ADDR64, Value.Addend);
1114 // Generates the 64-bits address loads as exemplified in section
1115 // 4.5.1 in PPC64 ELF ABI.
1116 RelocationEntry REhst(SectionID, StubTargetAddr - Section.Address + 2,
1117 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1118 RelocationEntry REhr(SectionID, StubTargetAddr - Section.Address + 6,
1119 ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1120 RelocationEntry REh(SectionID, StubTargetAddr - Section.Address + 14,
1121 ELF::R_PPC64_ADDR16_HI, Value.Addend);
1122 RelocationEntry REl(SectionID, StubTargetAddr - Section.Address + 18,
1123 ELF::R_PPC64_ADDR16_LO, Value.Addend);
1125 if (Value.SymbolName) {
1126 addRelocationForSymbol(REhst, Value.SymbolName);
1127 addRelocationForSymbol(REhr, Value.SymbolName);
1128 addRelocationForSymbol(REh, Value.SymbolName);
1129 addRelocationForSymbol(REl, Value.SymbolName);
1131 addRelocationForSection(REhst, Value.SectionID);
1132 addRelocationForSection(REhr, Value.SectionID);
1133 addRelocationForSection(REh, Value.SectionID);
1134 addRelocationForSection(REl, Value.SectionID);
1137 resolveRelocation(Section, Offset,
1138 (uint64_t)Section.Address + Section.StubOffset,
1140 Section.StubOffset += getMaxStubSize();
1142 if (SymType == SymbolRef::ST_Unknown)
1143 // Restore the TOC for external calls
1144 writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
1147 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1148 // Extra check to avoid relocation againt empty symbols (usually
1149 // the R_PPC64_TOC).
1150 if (SymType != SymbolRef::ST_Unknown && TargetName.empty())
1151 Value.SymbolName = NULL;
1153 if (Value.SymbolName)
1154 addRelocationForSymbol(RE, Value.SymbolName);
1156 addRelocationForSection(RE, Value.SectionID);
1158 } else if (Arch == Triple::systemz &&
1159 (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
1160 // Create function stubs for both PLT and GOT references, regardless of
1161 // whether the GOT reference is to data or code. The stub contains the
1162 // full address of the symbol, as needed by GOT references, and the
1163 // executable part only adds an overhead of 8 bytes.
1165 // We could try to conserve space by allocating the code and data
1166 // parts of the stub separately. However, as things stand, we allocate
1167 // a stub for every relocation, so using a GOT in JIT code should be
1168 // no less space efficient than using an explicit constant pool.
1169 DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1170 SectionEntry &Section = Sections[SectionID];
1172 // Look for an existing stub.
1173 StubMap::const_iterator i = Stubs.find(Value);
1174 uintptr_t StubAddress;
1175 if (i != Stubs.end()) {
1176 StubAddress = uintptr_t(Section.Address) + i->second;
1177 DEBUG(dbgs() << " Stub function found\n");
1179 // Create a new stub function.
1180 DEBUG(dbgs() << " Create a new stub function\n");
1182 uintptr_t BaseAddress = uintptr_t(Section.Address);
1183 uintptr_t StubAlignment = getStubAlignment();
1184 StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1186 unsigned StubOffset = StubAddress - BaseAddress;
1188 Stubs[Value] = StubOffset;
1189 createStubFunction((uint8_t *)StubAddress);
1190 RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
1191 Value.Addend - Addend);
1192 if (Value.SymbolName)
1193 addRelocationForSymbol(RE, Value.SymbolName);
1195 addRelocationForSection(RE, Value.SectionID);
1196 Section.StubOffset = StubOffset + getMaxStubSize();
1199 if (RelType == ELF::R_390_GOTENT)
1200 resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
1203 resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1204 } else if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_PLT32) {
1205 // The way the PLT relocations normally work is that the linker allocates
1207 // PLT and this relocation makes a PC-relative call into the PLT. The PLT
1208 // entry will then jump to an address provided by the GOT. On first call,
1210 // GOT address will point back into PLT code that resolves the symbol. After
1211 // the first call, the GOT entry points to the actual function.
1213 // For local functions we're ignoring all of that here and just replacing
1214 // the PLT32 relocation type with PC32, which will translate the relocation
1215 // into a PC-relative call directly to the function. For external symbols we
1216 // can't be sure the function will be within 2^32 bytes of the call site, so
1217 // we need to create a stub, which calls into the GOT. This case is
1218 // equivalent to the usual PLT implementation except that we use the stub
1219 // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1220 // rather than allocating a PLT section.
1221 if (Value.SymbolName) {
1222 // This is a call to an external function.
1223 // Look for an existing stub.
1224 SectionEntry &Section = Sections[SectionID];
1225 StubMap::const_iterator i = Stubs.find(Value);
1226 uintptr_t StubAddress;
1227 if (i != Stubs.end()) {
1228 StubAddress = uintptr_t(Section.Address) + i->second;
1229 DEBUG(dbgs() << " Stub function found\n");
1231 // Create a new stub function (equivalent to a PLT entry).
1232 DEBUG(dbgs() << " Create a new stub function\n");
1234 uintptr_t BaseAddress = uintptr_t(Section.Address);
1235 uintptr_t StubAlignment = getStubAlignment();
1236 StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1238 unsigned StubOffset = StubAddress - BaseAddress;
1239 Stubs[Value] = StubOffset;
1240 createStubFunction((uint8_t *)StubAddress);
1242 // Create a GOT entry for the external function.
1243 GOTEntries.push_back(Value);
1245 // Make our stub function a relative call to the GOT entry.
1246 RelocationEntry RE(SectionID, StubOffset + 2, ELF::R_X86_64_GOTPCREL,
1248 addRelocationForSymbol(RE, Value.SymbolName);
1250 // Bump our stub offset counter
1251 Section.StubOffset = StubOffset + getMaxStubSize();
1254 // Make the target call a call into the stub table.
1255 resolveRelocation(Section, Offset, StubAddress, ELF::R_X86_64_PC32,
1258 RelocationEntry RE(SectionID, Offset, ELF::R_X86_64_PC32, Value.Addend,
1260 addRelocationForSection(RE, Value.SectionID);
1263 if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_GOTPCREL) {
1264 GOTEntries.push_back(Value);
1266 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1267 if (Value.SymbolName)
1268 addRelocationForSymbol(RE, Value.SymbolName);
1270 addRelocationForSection(RE, Value.SectionID);
1275 void RuntimeDyldELF::updateGOTEntries(StringRef Name, uint64_t Addr) {
1277 SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator it;
1278 SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator end = GOTs.end();
1280 for (it = GOTs.begin(); it != end; ++it) {
1281 GOTRelocations &GOTEntries = it->second;
1282 for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1283 if (GOTEntries[i].SymbolName != 0 && GOTEntries[i].SymbolName == Name) {
1284 GOTEntries[i].Offset = Addr;
1290 size_t RuntimeDyldELF::getGOTEntrySize() {
1291 // We don't use the GOT in all of these cases, but it's essentially free
1292 // to put them all here.
1295 case Triple::x86_64:
1296 case Triple::aarch64:
1298 case Triple::ppc64le:
1299 case Triple::systemz:
1300 Result = sizeof(uint64_t);
1306 case Triple::mipsel:
1307 Result = sizeof(uint32_t);
1310 llvm_unreachable("Unsupported CPU type!");
1315 uint64_t RuntimeDyldELF::findGOTEntry(uint64_t LoadAddress, uint64_t Offset) {
1317 const size_t GOTEntrySize = getGOTEntrySize();
1319 SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator it;
1320 SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator end =
1324 for (it = GOTs.begin(); it != end; ++it) {
1325 SID GOTSectionID = it->first;
1326 const GOTRelocations &GOTEntries = it->second;
1328 // Find the matching entry in our vector.
1329 uint64_t SymbolOffset = 0;
1330 for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1331 if (GOTEntries[i].SymbolName == 0) {
1332 if (getSectionLoadAddress(GOTEntries[i].SectionID) == LoadAddress &&
1333 GOTEntries[i].Offset == Offset) {
1335 SymbolOffset = GOTEntries[i].Offset;
1339 // GOT entries for external symbols use the addend as the address when
1340 // the external symbol has been resolved.
1341 if (GOTEntries[i].Offset == LoadAddress) {
1343 // Don't use the Addend here. The relocation handler will use it.
1349 if (GOTIndex != -1) {
1350 if (GOTEntrySize == sizeof(uint64_t)) {
1351 uint64_t *LocalGOTAddr = (uint64_t *)getSectionAddress(GOTSectionID);
1352 // Fill in this entry with the address of the symbol being referenced.
1353 LocalGOTAddr[GOTIndex] = LoadAddress + SymbolOffset;
1355 uint32_t *LocalGOTAddr = (uint32_t *)getSectionAddress(GOTSectionID);
1356 // Fill in this entry with the address of the symbol being referenced.
1357 LocalGOTAddr[GOTIndex] = (uint32_t)(LoadAddress + SymbolOffset);
1360 // Calculate the load address of this entry
1361 return getSectionLoadAddress(GOTSectionID) + (GOTIndex * GOTEntrySize);
1365 assert(GOTIndex != -1 && "Unable to find requested GOT entry.");
1369 void RuntimeDyldELF::finalizeLoad(ObjSectionToIDMap &SectionMap) {
1370 // If necessary, allocate the global offset table
1372 // Allocate the GOT if necessary
1373 size_t numGOTEntries = GOTEntries.size();
1374 if (numGOTEntries != 0) {
1375 // Allocate memory for the section
1376 unsigned SectionID = Sections.size();
1377 size_t TotalSize = numGOTEntries * getGOTEntrySize();
1378 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, getGOTEntrySize(),
1379 SectionID, ".got", false);
1381 report_fatal_error("Unable to allocate memory for GOT!");
1383 GOTs.push_back(std::make_pair(SectionID, GOTEntries));
1384 Sections.push_back(SectionEntry(".got", Addr, TotalSize, 0));
1385 // For now, initialize all GOT entries to zero. We'll fill them in as
1386 // needed when GOT-based relocations are applied.
1387 memset(Addr, 0, TotalSize);
1390 report_fatal_error("Unable to allocate memory for GOT!");
1393 // Look for and record the EH frame section.
1394 ObjSectionToIDMap::iterator i, e;
1395 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
1396 const SectionRef &Section = i->first;
1398 Section.getName(Name);
1399 if (Name == ".eh_frame") {
1400 UnregisteredEHFrameSections.push_back(i->second);
1406 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1407 if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1409 return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic,
1410 strlen(ELF::ElfMagic))) == 0;
1413 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile *Obj) const {
1414 return Obj->isELF();