1 //===-- RuntimeDyldELF.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation of ELF support for the MC-JIT runtime dynamic linker.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dyld"
15 #include "RuntimeDyldELF.h"
16 #include "JITRegistrar.h"
17 #include "ObjectImageCommon.h"
18 #include "llvm/ADT/IntervalMap.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ExecutionEngine/ObjectBuffer.h"
24 #include "llvm/ExecutionEngine/ObjectImage.h"
25 #include "llvm/Object/ELF.h"
26 #include "llvm/Object/ObjectFile.h"
27 #include "llvm/Support/ELF.h"
29 using namespace llvm::object;
34 error_code check(error_code Err) {
36 report_fatal_error(Err.message());
43 : public ELFObjectFile<ELFT> {
44 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
46 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
47 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
49 Elf_Rel_Impl<ELFT, false> Elf_Rel;
51 Elf_Rel_Impl<ELFT, true> Elf_Rela;
53 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
55 typedef typename ELFDataTypeTypedefHelper<
56 ELFT>::value_type addr_type;
59 DyldELFObject(MemoryBuffer *Wrapper, error_code &ec);
61 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
62 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr);
64 // Methods for type inquiry through isa, cast and dyn_cast
65 static inline bool classof(const Binary *v) {
66 return (isa<ELFObjectFile<ELFT> >(v)
67 && classof(cast<ELFObjectFile
70 static inline bool classof(
71 const ELFObjectFile<ELFT> *v) {
72 return v->isDyldType();
77 class ELFObjectImage : public ObjectImageCommon {
79 DyldELFObject<ELFT> *DyldObj;
83 ELFObjectImage(ObjectBuffer *Input,
84 DyldELFObject<ELFT> *Obj)
85 : ObjectImageCommon(Input, Obj),
89 virtual ~ELFObjectImage() {
91 deregisterWithDebugger();
94 // Subclasses can override these methods to update the image with loaded
95 // addresses for sections and common symbols
96 virtual void updateSectionAddress(const SectionRef &Sec, uint64_t Addr)
98 DyldObj->updateSectionAddress(Sec, Addr);
101 virtual void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr)
103 DyldObj->updateSymbolAddress(Sym, Addr);
106 virtual void registerWithDebugger()
108 JITRegistrar::getGDBRegistrar().registerObject(*Buffer);
111 virtual void deregisterWithDebugger()
113 JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer);
117 // The MemoryBuffer passed into this constructor is just a wrapper around the
118 // actual memory. Ultimately, the Binary parent class will take ownership of
119 // this MemoryBuffer object but not the underlying memory.
121 DyldELFObject<ELFT>::DyldELFObject(MemoryBuffer *Wrapper, error_code &ec)
122 : ELFObjectFile<ELFT>(Wrapper, ec) {
123 this->isDyldELFObject = true;
127 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
129 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
130 Elf_Shdr *shdr = const_cast<Elf_Shdr*>(
131 reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
133 // This assumes the address passed in matches the target address bitness
134 // The template-based type cast handles everything else.
135 shdr->sh_addr = static_cast<addr_type>(Addr);
139 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
142 Elf_Sym *sym = const_cast<Elf_Sym*>(
143 ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
145 // This assumes the address passed in matches the target address bitness
146 // The template-based type cast handles everything else.
147 sym->st_value = static_cast<addr_type>(Addr);
154 StringRef RuntimeDyldELF::getEHFrameSection() {
155 for (int i = 0, e = Sections.size(); i != e; ++i) {
156 if (Sections[i].Name == ".eh_frame")
157 return StringRef((const char*)Sections[i].Address, Sections[i].Size);
162 ObjectImage *RuntimeDyldELF::createObjectImage(ObjectBuffer *Buffer) {
163 if (Buffer->getBufferSize() < ELF::EI_NIDENT)
164 llvm_unreachable("Unexpected ELF object size");
165 std::pair<unsigned char, unsigned char> Ident = std::make_pair(
166 (uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS],
167 (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
170 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) {
171 DyldELFObject<ELFType<support::little, 4, false> > *Obj =
172 new DyldELFObject<ELFType<support::little, 4, false> >(
173 Buffer->getMemBuffer(), ec);
174 return new ELFObjectImage<ELFType<support::little, 4, false> >(Buffer, Obj);
176 else if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB) {
177 DyldELFObject<ELFType<support::big, 4, false> > *Obj =
178 new DyldELFObject<ELFType<support::big, 4, false> >(
179 Buffer->getMemBuffer(), ec);
180 return new ELFObjectImage<ELFType<support::big, 4, false> >(Buffer, Obj);
182 else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB) {
183 DyldELFObject<ELFType<support::big, 8, true> > *Obj =
184 new DyldELFObject<ELFType<support::big, 8, true> >(
185 Buffer->getMemBuffer(), ec);
186 return new ELFObjectImage<ELFType<support::big, 8, true> >(Buffer, Obj);
188 else if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB) {
189 DyldELFObject<ELFType<support::little, 8, true> > *Obj =
190 new DyldELFObject<ELFType<support::little, 8, true> >(
191 Buffer->getMemBuffer(), ec);
192 return new ELFObjectImage<ELFType<support::little, 8, true> >(Buffer, Obj);
195 llvm_unreachable("Unexpected ELF format");
198 RuntimeDyldELF::~RuntimeDyldELF() {
201 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
208 llvm_unreachable("Relocation type not implemented yet!");
210 case ELF::R_X86_64_64: {
211 uint64_t *Target = reinterpret_cast<uint64_t*>(Section.Address + Offset);
212 *Target = Value + Addend;
213 DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend))
214 << " at " << format("%p\n",Target));
217 case ELF::R_X86_64_32:
218 case ELF::R_X86_64_32S: {
220 assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
221 (Type == ELF::R_X86_64_32S &&
222 ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
223 uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
224 uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
225 *Target = TruncatedAddr;
226 DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr)
227 << " at " << format("%p\n",Target));
230 case ELF::R_X86_64_PC32: {
231 // Get the placeholder value from the generated object since
232 // a previous relocation attempt may have overwritten the loaded version
233 uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
235 uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
236 uint64_t FinalAddress = Section.LoadAddress + Offset;
237 int64_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
238 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN);
239 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
240 *Target = TruncOffset;
246 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
252 case ELF::R_386_32: {
253 // Get the placeholder value from the generated object since
254 // a previous relocation attempt may have overwritten the loaded version
255 uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
257 uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
258 *Target = *Placeholder + Value + Addend;
261 case ELF::R_386_PC32: {
262 // Get the placeholder value from the generated object since
263 // a previous relocation attempt may have overwritten the loaded version
264 uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress
266 uint32_t *Target = reinterpret_cast<uint32_t*>(Section.Address + Offset);
267 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
268 uint32_t RealOffset = *Placeholder + Value + Addend - FinalAddress;
269 *Target = RealOffset;
273 // There are other relocation types, but it appears these are the
274 // only ones currently used by the LLVM ELF object writer
275 llvm_unreachable("Relocation type not implemented yet!");
280 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
285 uint32_t *TargetPtr = reinterpret_cast<uint32_t*>(Section.Address + Offset);
286 uint64_t FinalAddress = Section.LoadAddress + Offset;
288 DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
289 << format("%llx", Section.Address + Offset)
290 << " FinalAddress: 0x" << format("%llx",FinalAddress)
291 << " Value: 0x" << format("%llx",Value)
292 << " Type: 0x" << format("%x",Type)
293 << " Addend: 0x" << format("%llx",Addend)
298 llvm_unreachable("Relocation type not implemented yet!");
300 case ELF::R_AARCH64_ABS64: {
301 uint64_t *TargetPtr = reinterpret_cast<uint64_t*>(Section.Address + Offset);
302 *TargetPtr = Value + Addend;
305 case ELF::R_AARCH64_PREL32: {
306 uint64_t Result = Value + Addend - FinalAddress;
307 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
308 static_cast<int64_t>(Result) <= UINT32_MAX);
309 *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU);
312 case ELF::R_AARCH64_CALL26: // fallthrough
313 case ELF::R_AARCH64_JUMP26: {
314 // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
316 uint64_t BranchImm = Value + Addend - FinalAddress;
318 // "Check that -2^27 <= result < 2^27".
319 assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) &&
320 static_cast<int64_t>(BranchImm) < (1LL << 27));
322 // AArch64 code is emitted with .rela relocations. The data already in any
323 // bits affected by the relocation on entry is garbage.
324 *TargetPtr &= 0xfc000000U;
325 // Immediate goes in bits 25:0 of B and BL.
326 *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2;
329 case ELF::R_AARCH64_MOVW_UABS_G3: {
330 uint64_t Result = Value + Addend;
332 // AArch64 code is emitted with .rela relocations. The data already in any
333 // bits affected by the relocation on entry is garbage.
334 *TargetPtr &= 0xff80001fU;
335 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
336 *TargetPtr |= Result >> (48 - 5);
337 // Shift is "lsl #48", in bits 22:21
338 *TargetPtr |= 3 << 21;
341 case ELF::R_AARCH64_MOVW_UABS_G2_NC: {
342 uint64_t Result = Value + Addend;
345 // AArch64 code is emitted with .rela relocations. The data already in any
346 // bits affected by the relocation on entry is garbage.
347 *TargetPtr &= 0xff80001fU;
348 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
349 *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5));
350 // Shift is "lsl #32", in bits 22:21
351 *TargetPtr |= 2 << 21;
354 case ELF::R_AARCH64_MOVW_UABS_G1_NC: {
355 uint64_t Result = Value + Addend;
357 // AArch64 code is emitted with .rela relocations. The data already in any
358 // bits affected by the relocation on entry is garbage.
359 *TargetPtr &= 0xff80001fU;
360 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
361 *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5));
362 // Shift is "lsl #16", in bits 22:21
363 *TargetPtr |= 1 << 21;
366 case ELF::R_AARCH64_MOVW_UABS_G0_NC: {
367 uint64_t Result = Value + Addend;
369 // AArch64 code is emitted with .rela relocations. The data already in any
370 // bits affected by the relocation on entry is garbage.
371 *TargetPtr &= 0xff80001fU;
372 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction
373 *TargetPtr |= ((Result & 0xffffU) << 5);
374 // Shift is "lsl #0", in bits 22:21. No action needed.
380 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
385 // TODO: Add Thumb relocations.
386 uint32_t *Placeholder = reinterpret_cast<uint32_t*>(Section.ObjAddress +
388 uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
389 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF);
392 DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
393 << Section.Address + Offset
394 << " FinalAddress: " << format("%p",FinalAddress)
395 << " Value: " << format("%x",Value)
396 << " Type: " << format("%x",Type)
397 << " Addend: " << format("%x",Addend)
402 llvm_unreachable("Not implemented relocation type!");
404 // Write a 32bit value to relocation address, taking into account the
405 // implicit addend encoded in the target.
406 case ELF::R_ARM_TARGET1:
407 case ELF::R_ARM_ABS32:
408 *TargetPtr = *Placeholder + Value;
410 // Write first 16 bit of 32 bit value to the mov instruction.
411 // Last 4 bit should be shifted.
412 case ELF::R_ARM_MOVW_ABS_NC:
413 // We are not expecting any other addend in the relocation address.
414 // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2
415 // non-contiguous fields.
416 assert((*Placeholder & 0x000F0FFF) == 0);
417 Value = Value & 0xFFFF;
418 *TargetPtr = *Placeholder | (Value & 0xFFF);
419 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
421 // Write last 16 bit of 32 bit value to the mov instruction.
422 // Last 4 bit should be shifted.
423 case ELF::R_ARM_MOVT_ABS:
424 // We are not expecting any other addend in the relocation address.
425 // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC.
426 assert((*Placeholder & 0x000F0FFF) == 0);
428 Value = (Value >> 16) & 0xFFFF;
429 *TargetPtr = *Placeholder | (Value & 0xFFF);
430 *TargetPtr |= ((Value >> 12) & 0xF) << 16;
432 // Write 24 bit relative value to the branch instruction.
433 case ELF::R_ARM_PC24 : // Fall through.
434 case ELF::R_ARM_CALL : // Fall through.
435 case ELF::R_ARM_JUMP24: {
436 int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
437 RelValue = (RelValue & 0x03FFFFFC) >> 2;
438 assert((*TargetPtr & 0xFFFFFF) == 0xFFFFFE);
439 *TargetPtr &= 0xFF000000;
440 *TargetPtr |= RelValue;
443 case ELF::R_ARM_PRIVATE_0:
444 // This relocation is reserved by the ARM ELF ABI for internal use. We
445 // appropriate it here to act as an R_ARM_ABS32 without any addend for use
446 // in the stubs created during JIT (which can't put an addend into the
447 // original object file).
453 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section,
458 uint32_t* TargetPtr = (uint32_t*)(Section.Address + Offset);
461 DEBUG(dbgs() << "resolveMipselocation, LocalAddress: "
462 << Section.Address + Offset
464 << format("%p",Section.LoadAddress + Offset)
465 << " Value: " << format("%x",Value)
466 << " Type: " << format("%x",Type)
467 << " Addend: " << format("%x",Addend)
472 llvm_unreachable("Not implemented relocation type!");
475 *TargetPtr = Value + (*TargetPtr);
478 *TargetPtr = ((*TargetPtr) & 0xfc000000) | (( Value & 0x0fffffff) >> 2);
480 case ELF::R_MIPS_HI16:
481 // Get the higher 16-bits. Also add 1 if bit 15 is 1.
482 Value += ((*TargetPtr) & 0x0000ffff) << 16;
483 *TargetPtr = ((*TargetPtr) & 0xffff0000) |
484 (((Value + 0x8000) >> 16) & 0xffff);
486 case ELF::R_MIPS_LO16:
487 Value += ((*TargetPtr) & 0x0000ffff);
488 *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff);
493 // Return the .TOC. section address to R_PPC64_TOC relocations.
494 uint64_t RuntimeDyldELF::findPPC64TOC() const {
495 // The TOC consists of sections .got, .toc, .tocbss, .plt in that
496 // order. The TOC starts where the first of these sections starts.
497 SectionList::const_iterator it = Sections.begin();
498 SectionList::const_iterator ite = Sections.end();
499 for (; it != ite; ++it) {
500 if (it->Name == ".got" ||
501 it->Name == ".toc" ||
502 it->Name == ".tocbss" ||
507 // This may happen for
508 // * references to TOC base base (sym@toc, .odp relocation) without
510 // In this case just use the first section (which is usually
511 // the .odp) since the code won't reference the .toc base
513 it = Sections.begin();
516 // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
517 // thus permitting a full 64 Kbytes segment.
518 return it->LoadAddress + 0x8000;
521 // Returns the sections and offset associated with the ODP entry referenced
523 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
524 ObjSectionToIDMap &LocalSections,
525 RelocationValueRef &Rel) {
526 // Get the ELF symbol value (st_value) to compare with Relocation offset in
530 for (section_iterator si = Obj.begin_sections(),
531 se = Obj.end_sections(); si != se; si.increment(err)) {
532 StringRef SectionName;
533 check(si->getName(SectionName));
534 if (SectionName != ".opd")
537 for (relocation_iterator i = si->begin_relocations(),
538 e = si->end_relocations(); i != e;) {
541 // The R_PPC64_ADDR64 relocation indicates the first field
544 check(i->getType(TypeFunc));
545 if (TypeFunc != ELF::R_PPC64_ADDR64) {
550 SymbolRef TargetSymbol;
551 uint64_t TargetSymbolOffset;
552 check(i->getSymbol(TargetSymbol));
553 check(i->getOffset(TargetSymbolOffset));
555 check(getELFRelocationAddend(*i, Addend));
557 i = i.increment(err);
562 // Just check if following relocation is a R_PPC64_TOC
564 check(i->getType(TypeTOC));
565 if (TypeTOC != ELF::R_PPC64_TOC)
568 // Finally compares the Symbol value and the target symbol offset
569 // to check if this .opd entry refers to the symbol the relocation
571 if (Rel.Addend != (intptr_t)TargetSymbolOffset)
574 section_iterator tsi(Obj.end_sections());
575 check(TargetSymbol.getSection(tsi));
576 Rel.SectionID = findOrEmitSection(Obj, (*tsi), true, LocalSections);
577 Rel.Addend = (intptr_t)Addend;
581 llvm_unreachable("Attempting to get address of ODP entry!");
584 // Relocation masks following the #lo(value), #hi(value), #higher(value),
585 // and #highest(value) macros defined in section 4.5.1. Relocation Types
586 // in PPC-elf64abi document.
589 uint16_t applyPPClo (uint64_t value)
591 return value & 0xffff;
595 uint16_t applyPPChi (uint64_t value)
597 return (value >> 16) & 0xffff;
601 uint16_t applyPPChigher (uint64_t value)
603 return (value >> 32) & 0xffff;
607 uint16_t applyPPChighest (uint64_t value)
609 return (value >> 48) & 0xffff;
612 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
617 uint8_t* LocalAddress = Section.Address + Offset;
620 llvm_unreachable("Relocation type not implemented yet!");
622 case ELF::R_PPC64_ADDR16_LO :
623 writeInt16BE(LocalAddress, applyPPClo (Value + Addend));
625 case ELF::R_PPC64_ADDR16_HI :
626 writeInt16BE(LocalAddress, applyPPChi (Value + Addend));
628 case ELF::R_PPC64_ADDR16_HIGHER :
629 writeInt16BE(LocalAddress, applyPPChigher (Value + Addend));
631 case ELF::R_PPC64_ADDR16_HIGHEST :
632 writeInt16BE(LocalAddress, applyPPChighest (Value + Addend));
634 case ELF::R_PPC64_ADDR14 : {
635 assert(((Value + Addend) & 3) == 0);
636 // Preserve the AA/LK bits in the branch instruction
637 uint8_t aalk = *(LocalAddress+3);
638 writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
640 case ELF::R_PPC64_ADDR32 : {
641 int32_t Result = static_cast<int32_t>(Value + Addend);
642 if (SignExtend32<32>(Result) != Result)
643 llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
644 writeInt32BE(LocalAddress, Result);
646 case ELF::R_PPC64_REL24 : {
647 uint64_t FinalAddress = (Section.LoadAddress + Offset);
648 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
649 if (SignExtend32<24>(delta) != delta)
650 llvm_unreachable("Relocation R_PPC64_REL24 overflow");
651 // Generates a 'bl <address>' instruction
652 writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
654 case ELF::R_PPC64_REL32 : {
655 uint64_t FinalAddress = (Section.LoadAddress + Offset);
656 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend);
657 if (SignExtend32<32>(delta) != delta)
658 llvm_unreachable("Relocation R_PPC64_REL32 overflow");
659 writeInt32BE(LocalAddress, delta);
661 case ELF::R_PPC64_REL64: {
662 uint64_t FinalAddress = (Section.LoadAddress + Offset);
663 uint64_t Delta = Value - FinalAddress + Addend;
664 writeInt64BE(LocalAddress, Delta);
666 case ELF::R_PPC64_ADDR64 :
667 writeInt64BE(LocalAddress, Value + Addend);
669 case ELF::R_PPC64_TOC :
670 writeInt64BE(LocalAddress, findPPC64TOC());
672 case ELF::R_PPC64_TOC16 : {
673 uint64_t TOCStart = findPPC64TOC();
674 Value = applyPPClo((Value + Addend) - TOCStart);
675 writeInt16BE(LocalAddress, applyPPClo(Value));
677 case ELF::R_PPC64_TOC16_DS : {
678 uint64_t TOCStart = findPPC64TOC();
679 Value = ((Value + Addend) - TOCStart);
680 writeInt16BE(LocalAddress, applyPPClo(Value));
685 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
690 uint8_t *LocalAddress = Section.Address + Offset;
693 llvm_unreachable("Relocation type not implemented yet!");
695 case ELF::R_390_PC16DBL:
696 case ELF::R_390_PLT16DBL: {
697 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
698 assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
699 writeInt16BE(LocalAddress, Delta / 2);
702 case ELF::R_390_PC32DBL:
703 case ELF::R_390_PLT32DBL: {
704 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
705 assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
706 writeInt32BE(LocalAddress, Delta / 2);
709 case ELF::R_390_PC32: {
710 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset);
711 assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
712 writeInt32BE(LocalAddress, Delta);
716 writeInt64BE(LocalAddress, Value + Addend);
721 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
723 const SectionEntry &Section = Sections[RE.SectionID];
724 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend);
727 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
734 resolveX86_64Relocation(Section, Offset, Value, Type, Addend);
737 resolveX86Relocation(Section, Offset,
738 (uint32_t)(Value & 0xffffffffL), Type,
739 (uint32_t)(Addend & 0xffffffffL));
741 case Triple::aarch64:
742 resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
744 case Triple::arm: // Fall through.
746 resolveARMRelocation(Section, Offset,
747 (uint32_t)(Value & 0xffffffffL), Type,
748 (uint32_t)(Addend & 0xffffffffL));
750 case Triple::mips: // Fall through.
752 resolveMIPSRelocation(Section, Offset,
753 (uint32_t)(Value & 0xffffffffL), Type,
754 (uint32_t)(Addend & 0xffffffffL));
757 resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
759 case Triple::systemz:
760 resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
762 default: llvm_unreachable("Unsupported CPU type!");
766 void RuntimeDyldELF::processRelocationRef(unsigned SectionID,
769 ObjSectionToIDMap &ObjSectionToID,
770 const SymbolTableMap &Symbols,
773 Check(RelI.getType(RelType));
775 Check(getELFRelocationAddend(RelI, Addend));
777 Check(RelI.getSymbol(Symbol));
779 // Obtain the symbol name which is referenced in the relocation
780 StringRef TargetName;
781 Symbol.getName(TargetName);
782 DEBUG(dbgs() << "\t\tRelType: " << RelType
783 << " Addend: " << Addend
784 << " TargetName: " << TargetName
786 RelocationValueRef Value;
787 // First search for the symbol in the local symbol table
788 SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
789 SymbolRef::Type SymType;
790 Symbol.getType(SymType);
791 if (lsi != Symbols.end()) {
792 Value.SectionID = lsi->second.first;
793 Value.Addend = lsi->second.second + Addend;
795 // Search for the symbol in the global symbol table
796 SymbolTableMap::const_iterator gsi =
797 GlobalSymbolTable.find(TargetName.data());
798 if (gsi != GlobalSymbolTable.end()) {
799 Value.SectionID = gsi->second.first;
800 Value.Addend = gsi->second.second + Addend;
803 case SymbolRef::ST_Debug: {
804 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
805 // and can be changed by another developers. Maybe best way is add
806 // a new symbol type ST_Section to SymbolRef and use it.
807 section_iterator si(Obj.end_sections());
808 Symbol.getSection(si);
809 if (si == Obj.end_sections())
810 llvm_unreachable("Symbol section not found, bad object file format!");
811 DEBUG(dbgs() << "\t\tThis is section symbol\n");
812 // Default to 'true' in case isText fails (though it never does).
815 Value.SectionID = findOrEmitSection(Obj,
819 Value.Addend = Addend;
822 case SymbolRef::ST_Unknown: {
823 Value.SymbolName = TargetName.data();
824 Value.Addend = Addend;
828 llvm_unreachable("Unresolved symbol type!");
834 Check(RelI.getOffset(Offset));
836 DEBUG(dbgs() << "\t\tSectionID: " << SectionID
837 << " Offset: " << Offset
839 if (Arch == Triple::aarch64 &&
840 (RelType == ELF::R_AARCH64_CALL26 ||
841 RelType == ELF::R_AARCH64_JUMP26)) {
842 // This is an AArch64 branch relocation, need to use a stub function.
843 DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
844 SectionEntry &Section = Sections[SectionID];
846 // Look for an existing stub.
847 StubMap::const_iterator i = Stubs.find(Value);
848 if (i != Stubs.end()) {
849 resolveRelocation(Section, Offset,
850 (uint64_t)Section.Address + i->second, RelType, 0);
851 DEBUG(dbgs() << " Stub function found\n");
853 // Create a new stub function.
854 DEBUG(dbgs() << " Create a new stub function\n");
855 Stubs[Value] = Section.StubOffset;
856 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
859 RelocationEntry REmovz_g3(SectionID,
860 StubTargetAddr - Section.Address,
861 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
862 RelocationEntry REmovk_g2(SectionID,
863 StubTargetAddr - Section.Address + 4,
864 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
865 RelocationEntry REmovk_g1(SectionID,
866 StubTargetAddr - Section.Address + 8,
867 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
868 RelocationEntry REmovk_g0(SectionID,
869 StubTargetAddr - Section.Address + 12,
870 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
872 if (Value.SymbolName) {
873 addRelocationForSymbol(REmovz_g3, Value.SymbolName);
874 addRelocationForSymbol(REmovk_g2, Value.SymbolName);
875 addRelocationForSymbol(REmovk_g1, Value.SymbolName);
876 addRelocationForSymbol(REmovk_g0, Value.SymbolName);
878 addRelocationForSection(REmovz_g3, Value.SectionID);
879 addRelocationForSection(REmovk_g2, Value.SectionID);
880 addRelocationForSection(REmovk_g1, Value.SectionID);
881 addRelocationForSection(REmovk_g0, Value.SectionID);
883 resolveRelocation(Section, Offset,
884 (uint64_t)Section.Address + Section.StubOffset,
886 Section.StubOffset += getMaxStubSize();
888 } else if (Arch == Triple::arm &&
889 (RelType == ELF::R_ARM_PC24 ||
890 RelType == ELF::R_ARM_CALL ||
891 RelType == ELF::R_ARM_JUMP24)) {
892 // This is an ARM branch relocation, need to use a stub function.
893 DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.");
894 SectionEntry &Section = Sections[SectionID];
896 // Look for an existing stub.
897 StubMap::const_iterator i = Stubs.find(Value);
898 if (i != Stubs.end()) {
899 resolveRelocation(Section, Offset,
900 (uint64_t)Section.Address + i->second, RelType, 0);
901 DEBUG(dbgs() << " Stub function found\n");
903 // Create a new stub function.
904 DEBUG(dbgs() << " Create a new stub function\n");
905 Stubs[Value] = Section.StubOffset;
906 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
908 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
909 ELF::R_ARM_PRIVATE_0, Value.Addend);
910 if (Value.SymbolName)
911 addRelocationForSymbol(RE, Value.SymbolName);
913 addRelocationForSection(RE, Value.SectionID);
915 resolveRelocation(Section, Offset,
916 (uint64_t)Section.Address + Section.StubOffset,
918 Section.StubOffset += getMaxStubSize();
920 } else if ((Arch == Triple::mipsel || Arch == Triple::mips) &&
921 RelType == ELF::R_MIPS_26) {
922 // This is an Mips branch relocation, need to use a stub function.
923 DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
924 SectionEntry &Section = Sections[SectionID];
925 uint8_t *Target = Section.Address + Offset;
926 uint32_t *TargetAddress = (uint32_t *)Target;
928 // Extract the addend from the instruction.
929 uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2;
931 Value.Addend += Addend;
933 // Look up for existing stub.
934 StubMap::const_iterator i = Stubs.find(Value);
935 if (i != Stubs.end()) {
936 resolveRelocation(Section, Offset,
937 (uint64_t)Section.Address + i->second, RelType, 0);
938 DEBUG(dbgs() << " Stub function found\n");
940 // Create a new stub function.
941 DEBUG(dbgs() << " Create a new stub function\n");
942 Stubs[Value] = Section.StubOffset;
943 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
946 // Creating Hi and Lo relocations for the filled stub instructions.
947 RelocationEntry REHi(SectionID,
948 StubTargetAddr - Section.Address,
949 ELF::R_MIPS_HI16, Value.Addend);
950 RelocationEntry RELo(SectionID,
951 StubTargetAddr - Section.Address + 4,
952 ELF::R_MIPS_LO16, Value.Addend);
954 if (Value.SymbolName) {
955 addRelocationForSymbol(REHi, Value.SymbolName);
956 addRelocationForSymbol(RELo, Value.SymbolName);
958 addRelocationForSection(REHi, Value.SectionID);
959 addRelocationForSection(RELo, Value.SectionID);
962 resolveRelocation(Section, Offset,
963 (uint64_t)Section.Address + Section.StubOffset,
965 Section.StubOffset += getMaxStubSize();
967 } else if (Arch == Triple::ppc64) {
968 if (RelType == ELF::R_PPC64_REL24) {
969 // A PPC branch relocation will need a stub function if the target is
970 // an external symbol (Symbol::ST_Unknown) or if the target address
971 // is not within the signed 24-bits branch address.
972 SectionEntry &Section = Sections[SectionID];
973 uint8_t *Target = Section.Address + Offset;
974 bool RangeOverflow = false;
975 if (SymType != SymbolRef::ST_Unknown) {
976 // A function call may points to the .opd entry, so the final symbol value
977 // in calculated based in the relocation values in .opd section.
978 findOPDEntrySection(Obj, ObjSectionToID, Value);
979 uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend;
980 int32_t delta = static_cast<int32_t>(Target - RelocTarget);
981 // If it is within 24-bits branch range, just set the branch target
982 if (SignExtend32<24>(delta) == delta) {
983 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
984 if (Value.SymbolName)
985 addRelocationForSymbol(RE, Value.SymbolName);
987 addRelocationForSection(RE, Value.SectionID);
989 RangeOverflow = true;
992 if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) {
993 // It is an external symbol (SymbolRef::ST_Unknown) or within a range
994 // larger than 24-bits.
995 StubMap::const_iterator i = Stubs.find(Value);
996 if (i != Stubs.end()) {
997 // Symbol function stub already created, just relocate to it
998 resolveRelocation(Section, Offset,
999 (uint64_t)Section.Address + i->second, RelType, 0);
1000 DEBUG(dbgs() << " Stub function found\n");
1002 // Create a new stub function.
1003 DEBUG(dbgs() << " Create a new stub function\n");
1004 Stubs[Value] = Section.StubOffset;
1005 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
1006 Section.StubOffset);
1007 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
1008 ELF::R_PPC64_ADDR64, Value.Addend);
1010 // Generates the 64-bits address loads as exemplified in section
1011 // 4.5.1 in PPC64 ELF ABI.
1012 RelocationEntry REhst(SectionID,
1013 StubTargetAddr - Section.Address + 2,
1014 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1015 RelocationEntry REhr(SectionID,
1016 StubTargetAddr - Section.Address + 6,
1017 ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1018 RelocationEntry REh(SectionID,
1019 StubTargetAddr - Section.Address + 14,
1020 ELF::R_PPC64_ADDR16_HI, Value.Addend);
1021 RelocationEntry REl(SectionID,
1022 StubTargetAddr - Section.Address + 18,
1023 ELF::R_PPC64_ADDR16_LO, Value.Addend);
1025 if (Value.SymbolName) {
1026 addRelocationForSymbol(REhst, Value.SymbolName);
1027 addRelocationForSymbol(REhr, Value.SymbolName);
1028 addRelocationForSymbol(REh, Value.SymbolName);
1029 addRelocationForSymbol(REl, Value.SymbolName);
1031 addRelocationForSection(REhst, Value.SectionID);
1032 addRelocationForSection(REhr, Value.SectionID);
1033 addRelocationForSection(REh, Value.SectionID);
1034 addRelocationForSection(REl, Value.SectionID);
1037 resolveRelocation(Section, Offset,
1038 (uint64_t)Section.Address + Section.StubOffset,
1040 if (SymType == SymbolRef::ST_Unknown)
1041 // Restore the TOC for external calls
1042 writeInt32BE(Target+4, 0xE8410028); // ld r2,40(r1)
1043 Section.StubOffset += getMaxStubSize();
1047 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1048 // Extra check to avoid relocation againt empty symbols (usually
1049 // the R_PPC64_TOC).
1050 if (Value.SymbolName && !TargetName.empty())
1051 addRelocationForSymbol(RE, Value.SymbolName);
1053 addRelocationForSection(RE, Value.SectionID);
1055 } else if (Arch == Triple::systemz &&
1056 (RelType == ELF::R_390_PLT32DBL ||
1057 RelType == ELF::R_390_GOTENT)) {
1058 // Create function stubs for both PLT and GOT references, regardless of
1059 // whether the GOT reference is to data or code. The stub contains the
1060 // full address of the symbol, as needed by GOT references, and the
1061 // executable part only adds an overhead of 8 bytes.
1063 // We could try to conserve space by allocating the code and data
1064 // parts of the stub separately. However, as things stand, we allocate
1065 // a stub for every relocation, so using a GOT in JIT code should be
1066 // no less space efficient than using an explicit constant pool.
1067 DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1068 SectionEntry &Section = Sections[SectionID];
1070 // Look for an existing stub.
1071 StubMap::const_iterator i = Stubs.find(Value);
1072 uintptr_t StubAddress;
1073 if (i != Stubs.end()) {
1074 StubAddress = uintptr_t(Section.Address) + i->second;
1075 DEBUG(dbgs() << " Stub function found\n");
1077 // Create a new stub function.
1078 DEBUG(dbgs() << " Create a new stub function\n");
1080 uintptr_t BaseAddress = uintptr_t(Section.Address);
1081 uintptr_t StubAlignment = getStubAlignment();
1082 StubAddress = (BaseAddress + Section.StubOffset +
1083 StubAlignment - 1) & -StubAlignment;
1084 unsigned StubOffset = StubAddress - BaseAddress;
1086 Stubs[Value] = StubOffset;
1087 createStubFunction((uint8_t *)StubAddress);
1088 RelocationEntry RE(SectionID, StubOffset + 8,
1089 ELF::R_390_64, Value.Addend - Addend);
1090 if (Value.SymbolName)
1091 addRelocationForSymbol(RE, Value.SymbolName);
1093 addRelocationForSection(RE, Value.SectionID);
1094 Section.StubOffset = StubOffset + getMaxStubSize();
1097 if (RelType == ELF::R_390_GOTENT)
1098 resolveRelocation(Section, Offset, StubAddress + 8,
1099 ELF::R_390_PC32DBL, Addend);
1101 resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1103 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1104 if (Value.SymbolName)
1105 addRelocationForSymbol(RE, Value.SymbolName);
1107 addRelocationForSection(RE, Value.SectionID);
1111 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1112 if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1114 return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;