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 "JITRegistrar.h"
16 #include "ObjectImageCommon.h"
17 #include "llvm/ADT/IntervalMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ExecutionEngine/ObjectBuffer.h"
22 #include "llvm/ExecutionEngine/ObjectImage.h"
23 #include "llvm/Object/ELFObjectFile.h"
24 #include "llvm/Object/ObjectFile.h"
25 #include "llvm/Support/ELF.h"
26 #include "llvm/Support/MemoryBuffer.h"
29 using namespace llvm::object;
31 #define DEBUG_TYPE "dyld"
35 static inline error_code check(error_code Err) {
37 report_fatal_error(Err.message());
42 template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> {
43 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
45 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
46 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
47 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
48 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
50 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
52 typedef typename ELFDataTypeTypedefHelper<ELFT>::value_type addr_type;
55 DyldELFObject(MemoryBuffer *Wrapper, error_code &ec);
57 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
58 void updateSymbolAddress(const SymbolRef &Sym, 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();
70 template <class ELFT> class ELFObjectImage : public ObjectImageCommon {
72 DyldELFObject<ELFT> *DyldObj;
76 ELFObjectImage(ObjectBuffer *Input, DyldELFObject<ELFT> *Obj)
77 : ObjectImageCommon(Input, Obj), DyldObj(Obj), Registered(false) {}
79 virtual ~ELFObjectImage() {
81 deregisterWithDebugger();
84 // Subclasses can override these methods to update the image with loaded
85 // addresses for sections and common symbols
86 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr) override {
87 DyldObj->updateSectionAddress(Sec, Addr);
90 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr) override {
91 DyldObj->updateSymbolAddress(Sym, Addr);
94 void registerWithDebugger() override {
95 JITRegistrar::getGDBRegistrar().registerObject(*Buffer);
98 void deregisterWithDebugger() override {
99 JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer);
103 // The MemoryBuffer passed into this constructor is just a wrapper around the
104 // actual memory. Ultimately, the Binary parent class will take ownership of
105 // this MemoryBuffer object but not the underlying memory.
106 template <class ELFT>
107 DyldELFObject<ELFT>::DyldELFObject(MemoryBuffer *Wrapper, error_code &ec)
108 : ELFObjectFile<ELFT>(Wrapper, ec) {
109 this->isDyldELFObject = true;
112 template <class ELFT>
113 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
115 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
117 const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
119 // This assumes the address passed in matches the target address bitness
120 // The template-based type cast handles everything else.
121 shdr->sh_addr = static_cast<addr_type>(Addr);
124 template <class ELFT>
125 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
128 Elf_Sym *sym = const_cast<Elf_Sym *>(
129 ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
131 // This assumes the address passed in matches the target address bitness
132 // The template-based type cast handles everything else.
133 sym->st_value = static_cast<addr_type>(Addr);
140 void RuntimeDyldELF::registerEHFrames() {
143 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
144 SID EHFrameSID = UnregisteredEHFrameSections[i];
145 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
146 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
147 size_t EHFrameSize = Sections[EHFrameSID].Size;
148 MemMgr->registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
149 RegisteredEHFrameSections.push_back(EHFrameSID);
151 UnregisteredEHFrameSections.clear();
154 void RuntimeDyldELF::deregisterEHFrames() {
157 for (int i = 0, e = RegisteredEHFrameSections.size(); i != e; ++i) {
158 SID EHFrameSID = RegisteredEHFrameSections[i];
159 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address;
160 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress;
161 size_t EHFrameSize = Sections[EHFrameSID].Size;
162 MemMgr->deregisterEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
164 RegisteredEHFrameSections.clear();
168 RuntimeDyldELF::createObjectImageFromFile(object::ObjectFile *ObjFile) {
173 MemoryBuffer *Buffer =
174 MemoryBuffer::getMemBuffer(ObjFile->getData(), "", false);
176 if (ObjFile->getBytesInAddress() == 4 && ObjFile->isLittleEndian()) {
177 DyldELFObject<ELFType<support::little, 2, false>> *Obj =
178 new DyldELFObject<ELFType<support::little, 2, false>>(Buffer, ec);
179 return new ELFObjectImage<ELFType<support::little, 2, false>>(nullptr, Obj);
180 } else if (ObjFile->getBytesInAddress() == 4 && !ObjFile->isLittleEndian()) {
181 DyldELFObject<ELFType<support::big, 2, false>> *Obj =
182 new DyldELFObject<ELFType<support::big, 2, false>>(Buffer, ec);
183 return new ELFObjectImage<ELFType<support::big, 2, false>>(nullptr, Obj);
184 } else if (ObjFile->getBytesInAddress() == 8 && !ObjFile->isLittleEndian()) {
185 DyldELFObject<ELFType<support::big, 2, true>> *Obj =
186 new DyldELFObject<ELFType<support::big, 2, true>>(Buffer, ec);
187 return new ELFObjectImage<ELFType<support::big, 2, true>>(nullptr, Obj);
188 } else if (ObjFile->getBytesInAddress() == 8 && ObjFile->isLittleEndian()) {
189 DyldELFObject<ELFType<support::little, 2, true>> *Obj =
190 new DyldELFObject<ELFType<support::little, 2, true>>(Buffer, ec);
191 return new ELFObjectImage<ELFType<support::little, 2, true>>(nullptr, Obj);
193 llvm_unreachable("Unexpected ELF format");
196 ObjectImage *RuntimeDyldELF::createObjectImage(ObjectBuffer *Buffer) {
197 if (Buffer->getBufferSize() < ELF::EI_NIDENT)
198 llvm_unreachable("Unexpected ELF object size");
199 std::pair<unsigned char, unsigned char> Ident =
200 std::make_pair((uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS],
201 (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
204 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) {
205 DyldELFObject<ELFType<support::little, 4, false>> *Obj =
206 new DyldELFObject<ELFType<support::little, 4, false>>(
207 Buffer->getMemBuffer(), ec);
208 return new ELFObjectImage<ELFType<support::little, 4, false>>(Buffer, Obj);
209 } else if (Ident.first == ELF::ELFCLASS32 &&
210 Ident.second == ELF::ELFDATA2MSB) {
211 DyldELFObject<ELFType<support::big, 4, false>> *Obj =
212 new DyldELFObject<ELFType<support::big, 4, false>>(
213 Buffer->getMemBuffer(), ec);
214 return new ELFObjectImage<ELFType<support::big, 4, false>>(Buffer, Obj);
215 } else if (Ident.first == ELF::ELFCLASS64 &&
216 Ident.second == ELF::ELFDATA2MSB) {
217 DyldELFObject<ELFType<support::big, 8, true>> *Obj =
218 new DyldELFObject<ELFType<support::big, 8, true>>(
219 Buffer->getMemBuffer(), ec);
220 return new ELFObjectImage<ELFType<support::big, 8, true>>(Buffer, Obj);
221 } else if (Ident.first == ELF::ELFCLASS64 &&
222 Ident.second == ELF::ELFDATA2LSB) {
223 DyldELFObject<ELFType<support::little, 8, true>> *Obj =
224 new DyldELFObject<ELFType<support::little, 8, true>>(
225 Buffer->getMemBuffer(), ec);
226 return new ELFObjectImage<ELFType<support::little, 8, true>>(Buffer, Obj);
228 llvm_unreachable("Unexpected ELF format");
231 RuntimeDyldELF::~RuntimeDyldELF() {}
233 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
234 uint64_t Offset, uint64_t Value,
235 uint32_t Type, int64_t Addend,
236 uint64_t SymOffset) {
239 llvm_unreachable("Relocation type not implemented yet!");
241 case ELF::R_X86_64_64: {
242 uint64_t *Target = reinterpret_cast<uint64_t *>(Section.Address + Offset);
243 *Target = Value + Addend;
244 DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
245 << format("%p\n", Target));
248 case ELF::R_X86_64_32:
249 case ELF::R_X86_64_32S: {
251 assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
252 (Type == ELF::R_X86_64_32S &&
253 ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
254 uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
255 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
256 *Target = TruncatedAddr;
257 DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
258 << format("%p\n", Target));
261 case ELF::R_X86_64_GOTPCREL: {
262 // findGOTEntry returns the 'G + GOT' part of the relocation calculation
263 // based on the load/target address of the GOT (not the current/local addr).
264 uint64_t GOTAddr = findGOTEntry(Value, SymOffset);
265 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
266 uint64_t FinalAddress = Section.LoadAddress + Offset;
267 // The processRelocationRef method combines the symbol offset and the addend
268 // and in most cases that's what we want. For this relocation type, we need
269 // the raw addend, so we subtract the symbol offset to get it.
270 int64_t RealOffset = GOTAddr + Addend - SymOffset - FinalAddress;
271 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
272 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
273 *Target = TruncOffset;
276 case ELF::R_X86_64_PC32: {
277 // Get the placeholder value from the generated object since
278 // a previous relocation attempt may have overwritten the loaded version
279 uint32_t *Placeholder =
280 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
281 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
282 uint64_t FinalAddress = Section.LoadAddress + Offset;
283 int64_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
284 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
285 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
286 *Target = TruncOffset;
289 case ELF::R_X86_64_PC64: {
290 // Get the placeholder value from the generated object since
291 // a previous relocation attempt may have overwritten the loaded version
292 uint64_t *Placeholder =
293 reinterpret_cast<uint64_t *>(Section.ObjAddress + Offset);
294 uint64_t *Target = reinterpret_cast<uint64_t *>(Section.Address + Offset);
295 uint64_t FinalAddress = Section.LoadAddress + Offset;
296 *Target = *Placeholder + Value + Addend - FinalAddress;
302 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
303 uint64_t Offset, uint32_t Value,
304 uint32_t Type, int32_t Addend) {
306 case ELF::R_386_32: {
307 // Get the placeholder value from the generated object since
308 // a previous relocation attempt may have overwritten the loaded version
309 uint32_t *Placeholder =
310 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
311 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
312 *Target = *Placeholder + Value + Addend;
315 case ELF::R_386_PC32: {
316 // Get the placeholder value from the generated object since
317 // a previous relocation attempt may have overwritten the loaded version
318 uint32_t *Placeholder =
319 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
320 uint32_t *Target = reinterpret_cast<uint32_t *>(Section.Address + Offset);
321 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
322 uint32_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
323 *Target = RealOffset;
327 // There are other relocation types, but it appears these are the
328 // only ones currently used by the LLVM ELF object writer
329 llvm_unreachable("Relocation type not implemented yet!");
334 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
335 uint64_t Offset, uint64_t Value,
336 uint32_t Type, int64_t Addend) {
337 uint32_t *TargetPtr = reinterpret_cast<uint32_t *>(Section.Address + Offset);
338 uint64_t FinalAddress = Section.LoadAddress + Offset;
340 DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
341 << format("%llx", Section.Address + Offset)
342 << " FinalAddress: 0x" << format("%llx", FinalAddress)
343 << " Value: 0x" << format("%llx", Value) << " Type: 0x"
344 << format("%x", Type) << " Addend: 0x" << format("%llx", Addend)
349 llvm_unreachable("Relocation type not implemented yet!");
351 case ELF::R_AARCH64_ABS64: {
352 uint64_t *TargetPtr =
353 reinterpret_cast<uint64_t *>(Section.Address + Offset);
354 *TargetPtr = Value + Addend;
357 case ELF::R_AARCH64_PREL32: {
358 uint64_t Result = Value + Addend - FinalAddress;
359 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
360 static_cast<int64_t>(Result) <= UINT32_MAX);
361 *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU);
364 case ELF::R_AARCH64_CALL26: // fallthrough
365 case ELF::R_AARCH64_JUMP26: {
366 // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
368 uint64_t BranchImm = Value + Addend - FinalAddress;
370 // "Check that -2^27 <= result < 2^27".
371 assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) &&
372 static_cast<int64_t>(BranchImm) < (1LL << 27));
374 // AArch64 code is emitted with .rela relocations. The data already in any
375 // bits affected by the relocation on entry is garbage.
376 *TargetPtr &= 0xfc000000U;
377 // Immediate goes in bits 25:0 of B and BL.
378 *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2;
381 case ELF::R_AARCH64_MOVW_UABS_G3: {
382 uint64_t Result = Value + Addend;
384 // AArch64 code is emitted with .rela relocations. The data already in any
385 // bits affected by the relocation on entry is garbage.
386 *TargetPtr &= 0xffe0001fU;
387 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
388 *TargetPtr |= Result >> (48 - 5);
389 // Shift must be "lsl #48", in bits 22:21
390 assert((*TargetPtr >> 21 & 0x3) == 3 && "invalid shift for relocation");
393 case ELF::R_AARCH64_MOVW_UABS_G2_NC: {
394 uint64_t Result = Value + Addend;
396 // AArch64 code is emitted with .rela relocations. The data already in any
397 // bits affected by the relocation on entry is garbage.
398 *TargetPtr &= 0xffe0001fU;
399 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
400 *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5));
401 // Shift must be "lsl #32", in bits 22:21
402 assert((*TargetPtr >> 21 & 0x3) == 2 && "invalid shift for relocation");
405 case ELF::R_AARCH64_MOVW_UABS_G1_NC: {
406 uint64_t Result = Value + Addend;
408 // AArch64 code is emitted with .rela relocations. The data already in any
409 // bits affected by the relocation on entry is garbage.
410 *TargetPtr &= 0xffe0001fU;
411 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
412 *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5));
413 // Shift must be "lsl #16", in bits 22:2
414 assert((*TargetPtr >> 21 & 0x3) == 1 && "invalid shift for relocation");
417 case ELF::R_AARCH64_MOVW_UABS_G0_NC: {
418 uint64_t Result = Value + Addend;
420 // AArch64 code is emitted with .rela relocations. The data already in any
421 // bits affected by the relocation on entry is garbage.
422 *TargetPtr &= 0xffe0001fU;
423 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
424 *TargetPtr |= ((Result & 0xffffU) << 5);
425 // Shift must be "lsl #0", in bits 22:21.
426 assert((*TargetPtr >> 21 & 0x3) == 0 && "invalid shift for relocation");
429 case ELF::R_AARCH64_ADR_PREL_PG_HI21: {
430 // Operation: Page(S+A) - Page(P)
432 ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL);
434 // Check that -2^32 <= X < 2^32
435 assert(static_cast<int64_t>(Result) >= (-1LL << 32) &&
436 static_cast<int64_t>(Result) < (1LL << 32) &&
437 "overflow check failed for relocation");
439 // AArch64 code is emitted with .rela relocations. The data already in any
440 // bits affected by the relocation on entry is garbage.
441 *TargetPtr &= 0x9f00001fU;
442 // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken
443 // from bits 32:12 of X.
444 *TargetPtr |= ((Result & 0x3000U) << (29 - 12));
445 *TargetPtr |= ((Result & 0x1ffffc000ULL) >> (14 - 5));
448 case ELF::R_AARCH64_LDST32_ABS_LO12_NC: {
450 uint64_t Result = Value + Addend;
452 // AArch64 code is emitted with .rela relocations. The data already in any
453 // bits affected by the relocation on entry is garbage.
454 *TargetPtr &= 0xffc003ffU;
455 // Immediate goes in bits 21:10 of LD/ST instruction, taken
456 // from bits 11:2 of X
457 *TargetPtr |= ((Result & 0xffc) << (10 - 2));
460 case ELF::R_AARCH64_LDST64_ABS_LO12_NC: {
462 uint64_t Result = Value + Addend;
464 // AArch64 code is emitted with .rela relocations. The data already in any
465 // bits affected by the relocation on entry is garbage.
466 *TargetPtr &= 0xffc003ffU;
467 // Immediate goes in bits 21:10 of LD/ST instruction, taken
468 // from bits 11:3 of X
469 *TargetPtr |= ((Result & 0xff8) << (10 - 3));
475 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
476 uint64_t Offset, uint32_t Value,
477 uint32_t Type, int32_t Addend) {
478 // TODO: Add Thumb relocations.
479 uint32_t *Placeholder =
480 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
481 uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset);
482 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
485 DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
486 << Section.Address + Offset
487 << " FinalAddress: " << format("%p", FinalAddress) << " Value: "
488 << format("%x", Value) << " Type: " << format("%x", Type)
489 << " Addend: " << format("%x", Addend) << "\n");
493 llvm_unreachable("Not implemented relocation type!");
495 case ELF::R_ARM_NONE:
497 // Write a 32bit value to relocation address, taking into account the
498 // implicit addend encoded in the target.
499 case ELF::R_ARM_PREL31:
500 case ELF::R_ARM_TARGET1:
501 case ELF::R_ARM_ABS32:
502 *TargetPtr = *Placeholder + Value;
504 // Write first 16 bit of 32 bit value to the mov instruction.
505 // Last 4 bit should be shifted.
506 case ELF::R_ARM_MOVW_ABS_NC:
507 // We are not expecting any other addend in the relocation address.
508 // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
509 // non-contiguous fields.
510 assert((*Placeholder & 0x000F0FFF) == 0);
511 Value = Value & 0xFFFF;
512 *TargetPtr = *Placeholder | (Value & 0xFFF);
513 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
515 // Write last 16 bit of 32 bit value to the mov instruction.
516 // Last 4 bit should be shifted.
517 case ELF::R_ARM_MOVT_ABS:
518 // We are not expecting any other addend in the relocation address.
519 // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
520 assert((*Placeholder & 0x000F0FFF) == 0);
522 Value = (Value >> 16) & 0xFFFF;
523 *TargetPtr = *Placeholder | (Value & 0xFFF);
524 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
526 // Write 24 bit relative value to the branch instruction.
527 case ELF::R_ARM_PC24: // Fall through.
528 case ELF::R_ARM_CALL: // Fall through.
529 case ELF::R_ARM_JUMP24: {
530 int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
531 RelValue = (RelValue & 0x03FFFFFC) >> 2;
532 assert((*TargetPtr & 0xFFFFFF) == 0xFFFFFE);
533 *TargetPtr &= 0xFF000000;
534 *TargetPtr |= RelValue;
537 case ELF::R_ARM_PRIVATE_0:
538 // This relocation is reserved by the ARM ELF ABI for internal use. We
539 // appropriate it here to act as an R_ARM_ABS32 without any addend for use
540 // in the stubs created during JIT (which can't put an addend into the
541 // original object file).
547 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
548 uint64_t Offset, uint32_t Value,
549 uint32_t Type, int32_t Addend) {
550 uint32_t *Placeholder =
551 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset);
552 uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset);
555 DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
556 << Section.Address + Offset << " FinalAddress: "
557 << format("%p", Section.LoadAddress + Offset) << " Value: "
558 << format("%x", Value) << " Type: " << format("%x", Type)
559 << " Addend: " << format("%x", Addend) << "\n");
563 llvm_unreachable("Not implemented relocation type!");
566 *TargetPtr = Value + (*Placeholder);
569 *TargetPtr = ((*Placeholder) & 0xfc000000) | ((Value & 0x0fffffff) >> 2);
571 case ELF::R_MIPS_HI16:
572 // Get the higher 16-bits. Also add 1 if bit 15 is 1.
573 Value += ((*Placeholder) & 0x0000ffff) << 16;
575 ((*Placeholder) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff);
577 case ELF::R_MIPS_LO16:
578 Value += ((*Placeholder) & 0x0000ffff);
579 *TargetPtr = ((*Placeholder) & 0xffff0000) | (Value & 0xffff);
581 case ELF::R_MIPS_UNUSED1:
582 // Similar to ELF::R_ARM_PRIVATE_0, R_MIPS_UNUSED1 and R_MIPS_UNUSED2
583 // are used for internal JIT purpose. These relocations are similar to
584 // R_MIPS_HI16 and R_MIPS_LO16, but they do not take any addend into
587 ((*TargetPtr) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff);
589 case ELF::R_MIPS_UNUSED2:
590 *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
595 // Return the .TOC. section address to R_PPC64_TOC relocations.
596 uint64_t RuntimeDyldELF::findPPC64TOC() const {
597 // The TOC consists of sections .got, .toc, .tocbss, .plt in that
598 // order. The TOC starts where the first of these sections starts.
599 SectionList::const_iterator it = Sections.begin();
600 SectionList::const_iterator ite = Sections.end();
601 for (; it != ite; ++it) {
602 if (it->Name == ".got" || it->Name == ".toc" || it->Name == ".tocbss" ||
607 // This may happen for
608 // * references to TOC base base (sym@toc, .odp relocation) without
610 // In this case just use the first section (which is usually
611 // the .odp) since the code won't reference the .toc base
613 it = Sections.begin();
616 // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
617 // thus permitting a full 64 Kbytes segment.
618 return it->LoadAddress + 0x8000;
621 // Returns the sections and offset associated with the ODP entry referenced
623 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
624 ObjSectionToIDMap &LocalSections,
625 RelocationValueRef &Rel) {
626 // Get the ELF symbol value (st_value) to compare with Relocation offset in
628 for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections();
630 section_iterator RelSecI = si->getRelocatedSection();
631 if (RelSecI == Obj.end_sections())
634 StringRef RelSectionName;
635 check(RelSecI->getName(RelSectionName));
636 if (RelSectionName != ".opd")
639 for (relocation_iterator i = si->relocation_begin(),
640 e = si->relocation_end();
642 // The R_PPC64_ADDR64 relocation indicates the first field
645 check(i->getType(TypeFunc));
646 if (TypeFunc != ELF::R_PPC64_ADDR64) {
651 uint64_t TargetSymbolOffset;
652 symbol_iterator TargetSymbol = i->getSymbol();
653 check(i->getOffset(TargetSymbolOffset));
655 check(getELFRelocationAddend(*i, Addend));
661 // Just check if following relocation is a R_PPC64_TOC
663 check(i->getType(TypeTOC));
664 if (TypeTOC != ELF::R_PPC64_TOC)
667 // Finally compares the Symbol value and the target symbol offset
668 // to check if this .opd entry refers to the symbol the relocation
670 if (Rel.Addend != (int64_t)TargetSymbolOffset)
673 section_iterator tsi(Obj.end_sections());
674 check(TargetSymbol->getSection(tsi));
677 Rel.SectionID = findOrEmitSection(Obj, (*tsi), IsCode, LocalSections);
678 Rel.Addend = (intptr_t)Addend;
682 llvm_unreachable("Attempting to get address of ODP entry!");
685 // Relocation masks following the #lo(value), #hi(value), #higher(value),
686 // and #highest(value) macros defined in section 4.5.1. Relocation Types
687 // in PPC-elf64abi document.
689 static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
691 static inline uint16_t applyPPChi(uint64_t value) {
692 return (value >> 16) & 0xffff;
695 static inline uint16_t applyPPChigher(uint64_t value) {
696 return (value >> 32) & 0xffff;
699 static inline uint16_t applyPPChighest(uint64_t value) {
700 return (value >> 48) & 0xffff;
703 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
704 uint64_t Offset, uint64_t Value,
705 uint32_t Type, int64_t Addend) {
706 uint8_t *LocalAddress = Section.Address + Offset;
709 llvm_unreachable("Relocation type not implemented yet!");
711 case ELF::R_PPC64_ADDR16_LO:
712 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
714 case ELF::R_PPC64_ADDR16_HI:
715 writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
717 case ELF::R_PPC64_ADDR16_HIGHER:
718 writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
720 case ELF::R_PPC64_ADDR16_HIGHEST:
721 writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
723 case ELF::R_PPC64_ADDR14: {
724 assert(((Value + Addend) & 3) == 0);
725 // Preserve the AA/LK bits in the branch instruction
726 uint8_t aalk = *(LocalAddress + 3);
727 writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
729 case ELF::R_PPC64_ADDR32: {
730 int32_t Result = static_cast<int32_t>(Value + Addend);
731 if (SignExtend32<32>(Result) != Result)
732 llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
733 writeInt32BE(LocalAddress, Result);
735 case ELF::R_PPC64_REL24: {
736 uint64_t FinalAddress = (Section.LoadAddress + Offset);
737 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
738 if (SignExtend32<24>(delta) != delta)
739 llvm_unreachable("Relocation R_PPC64_REL24 overflow");
740 // Generates a 'bl <address>' instruction
741 writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
743 case ELF::R_PPC64_REL32: {
744 uint64_t FinalAddress = (Section.LoadAddress + Offset);
745 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
746 if (SignExtend32<32>(delta) != delta)
747 llvm_unreachable("Relocation R_PPC64_REL32 overflow");
748 writeInt32BE(LocalAddress, delta);
750 case ELF::R_PPC64_REL64: {
751 uint64_t FinalAddress = (Section.LoadAddress + Offset);
752 uint64_t Delta = Value - FinalAddress + Addend;
753 writeInt64BE(LocalAddress, Delta);
755 case ELF::R_PPC64_ADDR64:
756 writeInt64BE(LocalAddress, Value + Addend);
758 case ELF::R_PPC64_TOC:
759 writeInt64BE(LocalAddress, findPPC64TOC());
761 case ELF::R_PPC64_TOC16: {
762 uint64_t TOCStart = findPPC64TOC();
763 Value = applyPPClo((Value + Addend) - TOCStart);
764 writeInt16BE(LocalAddress, applyPPClo(Value));
766 case ELF::R_PPC64_TOC16_DS: {
767 uint64_t TOCStart = findPPC64TOC();
768 Value = ((Value + Addend) - TOCStart);
769 writeInt16BE(LocalAddress, applyPPClo(Value));
774 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
775 uint64_t Offset, uint64_t Value,
776 uint32_t Type, int64_t Addend) {
777 uint8_t *LocalAddress = Section.Address + Offset;
780 llvm_unreachable("Relocation type not implemented yet!");
782 case ELF::R_390_PC16DBL:
783 case ELF::R_390_PLT16DBL: {
784 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
785 assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
786 writeInt16BE(LocalAddress, Delta / 2);
789 case ELF::R_390_PC32DBL:
790 case ELF::R_390_PLT32DBL: {
791 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
792 assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
793 writeInt32BE(LocalAddress, Delta / 2);
796 case ELF::R_390_PC32: {
797 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
798 assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
799 writeInt32BE(LocalAddress, Delta);
803 writeInt64BE(LocalAddress, Value + Addend);
808 // The target location for the relocation is described by RE.SectionID and
809 // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
810 // SectionEntry has three members describing its location.
811 // SectionEntry::Address is the address at which the section has been loaded
812 // into memory in the current (host) process. SectionEntry::LoadAddress is the
813 // address that the section will have in the target process.
814 // SectionEntry::ObjAddress is the address of the bits for this section in the
815 // original emitted object image (also in the current address space).
817 // Relocations will be applied as if the section were loaded at
818 // SectionEntry::LoadAddress, but they will be applied at an address based
819 // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
820 // Target memory contents if they are required for value calculations.
822 // The Value parameter here is the load address of the symbol for the
823 // relocation to be applied. For relocations which refer to symbols in the
824 // current object Value will be the LoadAddress of the section in which
825 // the symbol resides (RE.Addend provides additional information about the
826 // symbol location). For external symbols, Value will be the address of the
827 // symbol in the target address space.
828 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
830 const SectionEntry &Section = Sections[RE.SectionID];
831 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
835 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
836 uint64_t Offset, uint64_t Value,
837 uint32_t Type, int64_t Addend,
838 uint64_t SymOffset) {
841 resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
844 resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
845 (uint32_t)(Addend & 0xffffffffL));
847 case Triple::aarch64:
848 case Triple::aarch64_be:
849 resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
851 case Triple::arm: // Fall through.
854 case Triple::thumbeb:
855 resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
856 (uint32_t)(Addend & 0xffffffffL));
858 case Triple::mips: // Fall through.
860 resolveMIPSRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL),
861 Type, (uint32_t)(Addend & 0xffffffffL));
863 case Triple::ppc64: // Fall through.
864 case Triple::ppc64le:
865 resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
867 case Triple::systemz:
868 resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
871 llvm_unreachable("Unsupported CPU type!");
875 relocation_iterator RuntimeDyldELF::processRelocationRef(
876 unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
877 ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
880 Check(RelI->getType(RelType));
882 Check(getELFRelocationAddend(*RelI, Addend));
883 symbol_iterator Symbol = RelI->getSymbol();
885 // Obtain the symbol name which is referenced in the relocation
886 StringRef TargetName;
887 if (Symbol != Obj.end_symbols())
888 Symbol->getName(TargetName);
889 DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
890 << " TargetName: " << TargetName << "\n");
891 RelocationValueRef Value;
892 // First search for the symbol in the local symbol table
893 SymbolTableMap::const_iterator lsi = Symbols.end();
894 SymbolRef::Type SymType = SymbolRef::ST_Unknown;
895 if (Symbol != Obj.end_symbols()) {
896 lsi = Symbols.find(TargetName.data());
897 Symbol->getType(SymType);
899 if (lsi != Symbols.end()) {
900 Value.SectionID = lsi->second.first;
901 Value.Offset = lsi->second.second;
902 Value.Addend = lsi->second.second + Addend;
904 // Search for the symbol in the global symbol table
905 SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end();
906 if (Symbol != Obj.end_symbols())
907 gsi = GlobalSymbolTable.find(TargetName.data());
908 if (gsi != GlobalSymbolTable.end()) {
909 Value.SectionID = gsi->second.first;
910 Value.Offset = gsi->second.second;
911 Value.Addend = gsi->second.second + Addend;
914 case SymbolRef::ST_Debug: {
915 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
916 // and can be changed by another developers. Maybe best way is add
917 // a new symbol type ST_Section to SymbolRef and use it.
918 section_iterator si(Obj.end_sections());
919 Symbol->getSection(si);
920 if (si == Obj.end_sections())
921 llvm_unreachable("Symbol section not found, bad object file format!");
922 DEBUG(dbgs() << "\t\tThis is section symbol\n");
923 // Default to 'true' in case isText fails (though it never does).
926 Value.SectionID = findOrEmitSection(Obj, (*si), isCode, ObjSectionToID);
927 Value.Addend = Addend;
930 case SymbolRef::ST_Data:
931 case SymbolRef::ST_Unknown: {
932 Value.SymbolName = TargetName.data();
933 Value.Addend = Addend;
935 // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
936 // will manifest here as a NULL symbol name.
937 // We can set this as a valid (but empty) symbol name, and rely
938 // on addRelocationForSymbol to handle this.
939 if (!Value.SymbolName)
940 Value.SymbolName = "";
944 llvm_unreachable("Unresolved symbol type!");
950 Check(RelI->getOffset(Offset));
952 DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
954 if (Arch == Triple::aarch64 &&
955 (RelType == ELF::R_AARCH64_CALL26 || RelType == ELF::R_AARCH64_JUMP26)) {
956 // This is an AArch64 branch relocation, need to use a stub function.
957 DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
958 SectionEntry &Section = Sections[SectionID];
960 // Look for an existing stub.
961 StubMap::const_iterator i = Stubs.find(Value);
962 if (i != Stubs.end()) {
963 resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
965 DEBUG(dbgs() << " Stub function found\n");
967 // Create a new stub function.
968 DEBUG(dbgs() << " Create a new stub function\n");
969 Stubs[Value] = Section.StubOffset;
970 uint8_t *StubTargetAddr =
971 createStubFunction(Section.Address + Section.StubOffset);
973 RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.Address,
974 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
975 RelocationEntry REmovk_g2(SectionID, StubTargetAddr - Section.Address + 4,
976 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
977 RelocationEntry REmovk_g1(SectionID, StubTargetAddr - Section.Address + 8,
978 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
979 RelocationEntry REmovk_g0(SectionID,
980 StubTargetAddr - Section.Address + 12,
981 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
983 if (Value.SymbolName) {
984 addRelocationForSymbol(REmovz_g3, Value.SymbolName);
985 addRelocationForSymbol(REmovk_g2, Value.SymbolName);
986 addRelocationForSymbol(REmovk_g1, Value.SymbolName);
987 addRelocationForSymbol(REmovk_g0, Value.SymbolName);
989 addRelocationForSection(REmovz_g3, Value.SectionID);
990 addRelocationForSection(REmovk_g2, Value.SectionID);
991 addRelocationForSection(REmovk_g1, Value.SectionID);
992 addRelocationForSection(REmovk_g0, Value.SectionID);
994 resolveRelocation(Section, Offset,
995 (uint64_t)Section.Address + Section.StubOffset, RelType,
997 Section.StubOffset += getMaxStubSize();
999 } else if (Arch == Triple::arm &&
1000 (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
1001 RelType == ELF::R_ARM_JUMP24)) {
1002 // This is an ARM branch relocation, need to use a stub function.
1003 DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
1004 SectionEntry &Section = Sections[SectionID];
1006 // Look for an existing stub.
1007 StubMap::const_iterator i = Stubs.find(Value);
1008 if (i != Stubs.end()) {
1009 resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
1011 DEBUG(dbgs() << " Stub function found\n");
1013 // Create a new stub function.
1014 DEBUG(dbgs() << " Create a new stub function\n");
1015 Stubs[Value] = Section.StubOffset;
1016 uint8_t *StubTargetAddr =
1017 createStubFunction(Section.Address + Section.StubOffset);
1018 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1019 ELF::R_ARM_PRIVATE_0, Value.Addend);
1020 if (Value.SymbolName)
1021 addRelocationForSymbol(RE, Value.SymbolName);
1023 addRelocationForSection(RE, Value.SectionID);
1025 resolveRelocation(Section, Offset,
1026 (uint64_t)Section.Address + Section.StubOffset, RelType,
1028 Section.StubOffset += getMaxStubSize();
1030 } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
1031 RelType == ELF::R_MIPS_26) {
1032 // This is an Mips branch relocation, need to use a stub function.
1033 DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1034 SectionEntry &Section = Sections[SectionID];
1035 uint8_t *Target = Section.Address + Offset;
1036 uint32_t *TargetAddress = (uint32_t *)Target;
1038 // Extract the addend from the instruction.
1039 uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
1041 Value.Addend += Addend;
1043 // Look up for existing stub.
1044 StubMap::const_iterator i = Stubs.find(Value);
1045 if (i != Stubs.end()) {
1046 RelocationEntry RE(SectionID, Offset, RelType, i->second);
1047 addRelocationForSection(RE, SectionID);
1048 DEBUG(dbgs() << " Stub function found\n");
1050 // Create a new stub function.
1051 DEBUG(dbgs() << " Create a new stub function\n");
1052 Stubs[Value] = Section.StubOffset;
1053 uint8_t *StubTargetAddr =
1054 createStubFunction(Section.Address + Section.StubOffset);
1056 // Creating Hi and Lo relocations for the filled stub instructions.
1057 RelocationEntry REHi(SectionID, StubTargetAddr - Section.Address,
1058 ELF::R_MIPS_UNUSED1, Value.Addend);
1059 RelocationEntry RELo(SectionID, StubTargetAddr - Section.Address + 4,
1060 ELF::R_MIPS_UNUSED2, Value.Addend);
1062 if (Value.SymbolName) {
1063 addRelocationForSymbol(REHi, Value.SymbolName);
1064 addRelocationForSymbol(RELo, Value.SymbolName);
1066 addRelocationForSection(REHi, Value.SectionID);
1067 addRelocationForSection(RELo, Value.SectionID);
1070 RelocationEntry RE(SectionID, Offset, RelType, Section.StubOffset);
1071 addRelocationForSection(RE, SectionID);
1072 Section.StubOffset += getMaxStubSize();
1074 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1075 if (RelType == ELF::R_PPC64_REL24) {
1076 // A PPC branch relocation will need a stub function if the target is
1077 // an external symbol (Symbol::ST_Unknown) or if the target address
1078 // is not within the signed 24-bits branch address.
1079 SectionEntry &Section = Sections[SectionID];
1080 uint8_t *Target = Section.Address + Offset;
1081 bool RangeOverflow = false;
1082 if (SymType != SymbolRef::ST_Unknown) {
1083 // A function call may points to the .opd entry, so the final symbol
1085 // in calculated based in the relocation values in .opd section.
1086 findOPDEntrySection(Obj, ObjSectionToID, Value);
1087 uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
1088 int32_t delta = static_cast<int32_t>(Target - RelocTarget);
1089 // If it is within 24-bits branch range, just set the branch target
1090 if (SignExtend32<24>(delta) == delta) {
1091 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1092 if (Value.SymbolName)
1093 addRelocationForSymbol(RE, Value.SymbolName);
1095 addRelocationForSection(RE, Value.SectionID);
1097 RangeOverflow = true;
1100 if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
1101 // It is an external symbol (SymbolRef::ST_Unknown) or within a range
1102 // larger than 24-bits.
1103 StubMap::const_iterator i = Stubs.find(Value);
1104 if (i != Stubs.end()) {
1105 // Symbol function stub already created, just relocate to it
1106 resolveRelocation(Section, Offset,
1107 (uint64_t)Section.Address + i->second, RelType, 0);
1108 DEBUG(dbgs() << " Stub function found\n");
1110 // Create a new stub function.
1111 DEBUG(dbgs() << " Create a new stub function\n");
1112 Stubs[Value] = Section.StubOffset;
1113 uint8_t *StubTargetAddr =
1114 createStubFunction(Section.Address + Section.StubOffset);
1115 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1116 ELF::R_PPC64_ADDR64, Value.Addend);
1118 // Generates the 64-bits address loads as exemplified in section
1119 // 4.5.1 in PPC64 ELF ABI.
1120 RelocationEntry REhst(SectionID, StubTargetAddr - Section.Address + 2,
1121 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1122 RelocationEntry REhr(SectionID, StubTargetAddr - Section.Address + 6,
1123 ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1124 RelocationEntry REh(SectionID, StubTargetAddr - Section.Address + 14,
1125 ELF::R_PPC64_ADDR16_HI, Value.Addend);
1126 RelocationEntry REl(SectionID, StubTargetAddr - Section.Address + 18,
1127 ELF::R_PPC64_ADDR16_LO, Value.Addend);
1129 if (Value.SymbolName) {
1130 addRelocationForSymbol(REhst, Value.SymbolName);
1131 addRelocationForSymbol(REhr, Value.SymbolName);
1132 addRelocationForSymbol(REh, Value.SymbolName);
1133 addRelocationForSymbol(REl, Value.SymbolName);
1135 addRelocationForSection(REhst, Value.SectionID);
1136 addRelocationForSection(REhr, Value.SectionID);
1137 addRelocationForSection(REh, Value.SectionID);
1138 addRelocationForSection(REl, Value.SectionID);
1141 resolveRelocation(Section, Offset,
1142 (uint64_t)Section.Address + Section.StubOffset,
1144 Section.StubOffset += getMaxStubSize();
1146 if (SymType == SymbolRef::ST_Unknown)
1147 // Restore the TOC for external calls
1148 writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
1151 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1152 // Extra check to avoid relocation againt empty symbols (usually
1153 // the R_PPC64_TOC).
1154 if (SymType != SymbolRef::ST_Unknown && TargetName.empty())
1155 Value.SymbolName = nullptr;
1157 if (Value.SymbolName)
1158 addRelocationForSymbol(RE, Value.SymbolName);
1160 addRelocationForSection(RE, Value.SectionID);
1162 } else if (Arch == Triple::systemz &&
1163 (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
1164 // Create function stubs for both PLT and GOT references, regardless of
1165 // whether the GOT reference is to data or code. The stub contains the
1166 // full address of the symbol, as needed by GOT references, and the
1167 // executable part only adds an overhead of 8 bytes.
1169 // We could try to conserve space by allocating the code and data
1170 // parts of the stub separately. However, as things stand, we allocate
1171 // a stub for every relocation, so using a GOT in JIT code should be
1172 // no less space efficient than using an explicit constant pool.
1173 DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1174 SectionEntry &Section = Sections[SectionID];
1176 // Look for an existing stub.
1177 StubMap::const_iterator i = Stubs.find(Value);
1178 uintptr_t StubAddress;
1179 if (i != Stubs.end()) {
1180 StubAddress = uintptr_t(Section.Address) + i->second;
1181 DEBUG(dbgs() << " Stub function found\n");
1183 // Create a new stub function.
1184 DEBUG(dbgs() << " Create a new stub function\n");
1186 uintptr_t BaseAddress = uintptr_t(Section.Address);
1187 uintptr_t StubAlignment = getStubAlignment();
1188 StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1190 unsigned StubOffset = StubAddress - BaseAddress;
1192 Stubs[Value] = StubOffset;
1193 createStubFunction((uint8_t *)StubAddress);
1194 RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
1195 Value.Addend - Addend);
1196 if (Value.SymbolName)
1197 addRelocationForSymbol(RE, Value.SymbolName);
1199 addRelocationForSection(RE, Value.SectionID);
1200 Section.StubOffset = StubOffset + getMaxStubSize();
1203 if (RelType == ELF::R_390_GOTENT)
1204 resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
1207 resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1208 } else if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_PLT32) {
1209 // The way the PLT relocations normally work is that the linker allocates
1211 // PLT and this relocation makes a PC-relative call into the PLT. The PLT
1212 // entry will then jump to an address provided by the GOT. On first call,
1214 // GOT address will point back into PLT code that resolves the symbol. After
1215 // the first call, the GOT entry points to the actual function.
1217 // For local functions we're ignoring all of that here and just replacing
1218 // the PLT32 relocation type with PC32, which will translate the relocation
1219 // into a PC-relative call directly to the function. For external symbols we
1220 // can't be sure the function will be within 2^32 bytes of the call site, so
1221 // we need to create a stub, which calls into the GOT. This case is
1222 // equivalent to the usual PLT implementation except that we use the stub
1223 // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1224 // rather than allocating a PLT section.
1225 if (Value.SymbolName) {
1226 // This is a call to an external function.
1227 // Look for an existing stub.
1228 SectionEntry &Section = Sections[SectionID];
1229 StubMap::const_iterator i = Stubs.find(Value);
1230 uintptr_t StubAddress;
1231 if (i != Stubs.end()) {
1232 StubAddress = uintptr_t(Section.Address) + i->second;
1233 DEBUG(dbgs() << " Stub function found\n");
1235 // Create a new stub function (equivalent to a PLT entry).
1236 DEBUG(dbgs() << " Create a new stub function\n");
1238 uintptr_t BaseAddress = uintptr_t(Section.Address);
1239 uintptr_t StubAlignment = getStubAlignment();
1240 StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
1242 unsigned StubOffset = StubAddress - BaseAddress;
1243 Stubs[Value] = StubOffset;
1244 createStubFunction((uint8_t *)StubAddress);
1246 // Create a GOT entry for the external function.
1247 GOTEntries.push_back(Value);
1249 // Make our stub function a relative call to the GOT entry.
1250 RelocationEntry RE(SectionID, StubOffset + 2, ELF::R_X86_64_GOTPCREL,
1252 addRelocationForSymbol(RE, Value.SymbolName);
1254 // Bump our stub offset counter
1255 Section.StubOffset = StubOffset + getMaxStubSize();
1258 // Make the target call a call into the stub table.
1259 resolveRelocation(Section, Offset, StubAddress, ELF::R_X86_64_PC32,
1262 RelocationEntry RE(SectionID, Offset, ELF::R_X86_64_PC32, Value.Addend,
1264 addRelocationForSection(RE, Value.SectionID);
1267 if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_GOTPCREL) {
1268 GOTEntries.push_back(Value);
1270 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1271 if (Value.SymbolName)
1272 addRelocationForSymbol(RE, Value.SymbolName);
1274 addRelocationForSection(RE, Value.SectionID);
1279 void RuntimeDyldELF::updateGOTEntries(StringRef Name, uint64_t Addr) {
1281 SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator it;
1282 SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator end = GOTs.end();
1284 for (it = GOTs.begin(); it != end; ++it) {
1285 GOTRelocations &GOTEntries = it->second;
1286 for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1287 if (GOTEntries[i].SymbolName != nullptr &&
1288 GOTEntries[i].SymbolName == Name) {
1289 GOTEntries[i].Offset = Addr;
1295 size_t RuntimeDyldELF::getGOTEntrySize() {
1296 // We don't use the GOT in all of these cases, but it's essentially free
1297 // to put them all here.
1300 case Triple::x86_64:
1301 case Triple::aarch64:
1303 case Triple::ppc64le:
1304 case Triple::systemz:
1305 Result = sizeof(uint64_t);
1311 case Triple::mipsel:
1312 Result = sizeof(uint32_t);
1315 llvm_unreachable("Unsupported CPU type!");
1320 uint64_t RuntimeDyldELF::findGOTEntry(uint64_t LoadAddress, uint64_t Offset) {
1322 const size_t GOTEntrySize = getGOTEntrySize();
1324 SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator it;
1325 SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator end =
1329 for (it = GOTs.begin(); it != end; ++it) {
1330 SID GOTSectionID = it->first;
1331 const GOTRelocations &GOTEntries = it->second;
1333 // Find the matching entry in our vector.
1334 uint64_t SymbolOffset = 0;
1335 for (int i = 0, e = GOTEntries.size(); i != e; ++i) {
1336 if (!GOTEntries[i].SymbolName) {
1337 if (getSectionLoadAddress(GOTEntries[i].SectionID) == LoadAddress &&
1338 GOTEntries[i].Offset == Offset) {
1340 SymbolOffset = GOTEntries[i].Offset;
1344 // GOT entries for external symbols use the addend as the address when
1345 // the external symbol has been resolved.
1346 if (GOTEntries[i].Offset == LoadAddress) {
1348 // Don't use the Addend here. The relocation handler will use it.
1354 if (GOTIndex != -1) {
1355 if (GOTEntrySize == sizeof(uint64_t)) {
1356 uint64_t *LocalGOTAddr = (uint64_t *)getSectionAddress(GOTSectionID);
1357 // Fill in this entry with the address of the symbol being referenced.
1358 LocalGOTAddr[GOTIndex] = LoadAddress + SymbolOffset;
1360 uint32_t *LocalGOTAddr = (uint32_t *)getSectionAddress(GOTSectionID);
1361 // Fill in this entry with the address of the symbol being referenced.
1362 LocalGOTAddr[GOTIndex] = (uint32_t)(LoadAddress + SymbolOffset);
1365 // Calculate the load address of this entry
1366 return getSectionLoadAddress(GOTSectionID) + (GOTIndex * GOTEntrySize);
1370 assert(GOTIndex != -1 && "Unable to find requested GOT entry.");
1374 void RuntimeDyldELF::finalizeLoad(ObjSectionToIDMap &SectionMap) {
1375 // If necessary, allocate the global offset table
1377 // Allocate the GOT if necessary
1378 size_t numGOTEntries = GOTEntries.size();
1379 if (numGOTEntries != 0) {
1380 // Allocate memory for the section
1381 unsigned SectionID = Sections.size();
1382 size_t TotalSize = numGOTEntries * getGOTEntrySize();
1383 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, getGOTEntrySize(),
1384 SectionID, ".got", false);
1386 report_fatal_error("Unable to allocate memory for GOT!");
1388 GOTs.push_back(std::make_pair(SectionID, GOTEntries));
1389 Sections.push_back(SectionEntry(".got", Addr, TotalSize, 0));
1390 // For now, initialize all GOT entries to zero. We'll fill them in as
1391 // needed when GOT-based relocations are applied.
1392 memset(Addr, 0, TotalSize);
1395 report_fatal_error("Unable to allocate memory for GOT!");
1398 // Look for and record the EH frame section.
1399 ObjSectionToIDMap::iterator i, e;
1400 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
1401 const SectionRef &Section = i->first;
1403 Section.getName(Name);
1404 if (Name == ".eh_frame") {
1405 UnregisteredEHFrameSections.push_back(i->second);
1411 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1412 if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1414 return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic,
1415 strlen(ELF::ElfMagic))) == 0;
1418 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile *Obj) const {
1419 return Obj->isELF();