1 //===-- RuntimeDyldELF.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Implementation of ELF support for the MC-JIT runtime dynamic linker. 11 // 12 //===----------------------------------------------------------------------===// 13 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/Endian.h" 27 #include "llvm/Support/MemoryBuffer.h" 28 29 using namespace llvm; 30 using namespace llvm::object; 31 32 #define DEBUG_TYPE "dyld" 33 34 namespace { 35 36 static inline std::error_code check(std::error_code Err) { 37 if (Err) { 38 report_fatal_error(Err.message()); 39 } 40 return Err; 41 } 42 43 template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> { 44 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT) 45 46 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr; 47 typedef Elf_Sym_Impl<ELFT> Elf_Sym; 48 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel; 49 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela; 50 51 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr; 52 53 typedef typename ELFDataTypeTypedefHelper<ELFT>::value_type addr_type; 54 55 std::unique_ptr<ObjectFile> UnderlyingFile; 56 57 public: 58 DyldELFObject(std::unique_ptr<ObjectFile> UnderlyingFile, 59 MemoryBufferRef Wrapper, std::error_code &ec); 60 61 DyldELFObject(MemoryBufferRef Wrapper, std::error_code &ec); 62 63 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr); 64 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr); 65 66 // Methods for type inquiry through isa, cast and dyn_cast 67 static inline bool classof(const Binary *v) { 68 return (isa<ELFObjectFile<ELFT>>(v) && 69 classof(cast<ELFObjectFile<ELFT>>(v))); 70 } 71 static inline bool classof(const ELFObjectFile<ELFT> *v) { 72 return v->isDyldType(); 73 } 74 }; 75 76 template <class ELFT> class ELFObjectImage : public ObjectImageCommon { 77 bool Registered; 78 79 public: 80 ELFObjectImage(std::unique_ptr<ObjectBuffer> Input, 81 std::unique_ptr<DyldELFObject<ELFT>> Obj) 82 : ObjectImageCommon(std::move(Input), std::move(Obj)), Registered(false) { 83 } 84 85 virtual ~ELFObjectImage() { 86 if (Registered) 87 deregisterWithDebugger(); 88 } 89 90 // Subclasses can override these methods to update the image with loaded 91 // addresses for sections and common symbols 92 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr) override { 93 static_cast<DyldELFObject<ELFT>*>(getObjectFile()) 94 ->updateSectionAddress(Sec, Addr); 95 } 96 97 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr) override { 98 static_cast<DyldELFObject<ELFT>*>(getObjectFile()) 99 ->updateSymbolAddress(Sym, Addr); 100 } 101 102 void registerWithDebugger() override { 103 JITRegistrar::getGDBRegistrar().registerObject(*Buffer); 104 Registered = true; 105 } 106 void deregisterWithDebugger() override { 107 JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer); 108 } 109 }; 110 111 // The MemoryBuffer passed into this constructor is just a wrapper around the 112 // actual memory. Ultimately, the Binary parent class will take ownership of 113 // this MemoryBuffer object but not the underlying memory. 114 template <class ELFT> 115 DyldELFObject<ELFT>::DyldELFObject(MemoryBufferRef Wrapper, std::error_code &EC) 116 : ELFObjectFile<ELFT>(Wrapper, EC) { 117 this->isDyldELFObject = true; 118 } 119 120 template <class ELFT> 121 DyldELFObject<ELFT>::DyldELFObject(std::unique_ptr<ObjectFile> UnderlyingFile, 122 MemoryBufferRef Wrapper, std::error_code &EC) 123 : ELFObjectFile<ELFT>(Wrapper, EC), 124 UnderlyingFile(std::move(UnderlyingFile)) { 125 this->isDyldELFObject = true; 126 } 127 128 template <class ELFT> 129 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec, 130 uint64_t Addr) { 131 DataRefImpl ShdrRef = Sec.getRawDataRefImpl(); 132 Elf_Shdr *shdr = 133 const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p)); 134 135 // This assumes the address passed in matches the target address bitness 136 // The template-based type cast handles everything else. 137 shdr->sh_addr = static_cast<addr_type>(Addr); 138 } 139 140 template <class ELFT> 141 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef, 142 uint64_t Addr) { 143 144 Elf_Sym *sym = const_cast<Elf_Sym *>( 145 ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl())); 146 147 // This assumes the address passed in matches the target address bitness 148 // The template-based type cast handles everything else. 149 sym->st_value = static_cast<addr_type>(Addr); 150 } 151 152 } // namespace 153 154 namespace llvm { 155 156 void RuntimeDyldELF::registerEHFrames() { 157 if (!MemMgr) 158 return; 159 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) { 160 SID EHFrameSID = UnregisteredEHFrameSections[i]; 161 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address; 162 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress; 163 size_t EHFrameSize = Sections[EHFrameSID].Size; 164 MemMgr->registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize); 165 RegisteredEHFrameSections.push_back(EHFrameSID); 166 } 167 UnregisteredEHFrameSections.clear(); 168 } 169 170 void RuntimeDyldELF::deregisterEHFrames() { 171 if (!MemMgr) 172 return; 173 for (int i = 0, e = RegisteredEHFrameSections.size(); i != e; ++i) { 174 SID EHFrameSID = RegisteredEHFrameSections[i]; 175 uint8_t *EHFrameAddr = Sections[EHFrameSID].Address; 176 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].LoadAddress; 177 size_t EHFrameSize = Sections[EHFrameSID].Size; 178 MemMgr->deregisterEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize); 179 } 180 RegisteredEHFrameSections.clear(); 181 } 182 183 ObjectImage * 184 RuntimeDyldELF::createObjectImageFromFile(std::unique_ptr<object::ObjectFile> ObjFile) { 185 if (!ObjFile) 186 return nullptr; 187 188 std::error_code ec; 189 MemoryBufferRef Buffer = ObjFile->getMemoryBufferRef(); 190 191 if (ObjFile->getBytesInAddress() == 4 && ObjFile->isLittleEndian()) { 192 auto Obj = 193 llvm::make_unique<DyldELFObject<ELFType<support::little, 2, false>>>( 194 std::move(ObjFile), Buffer, ec); 195 return new ELFObjectImage<ELFType<support::little, 2, false>>( 196 nullptr, std::move(Obj)); 197 } else if (ObjFile->getBytesInAddress() == 4 && !ObjFile->isLittleEndian()) { 198 auto Obj = 199 llvm::make_unique<DyldELFObject<ELFType<support::big, 2, false>>>( 200 std::move(ObjFile), Buffer, ec); 201 return new ELFObjectImage<ELFType<support::big, 2, false>>(nullptr, std::move(Obj)); 202 } else if (ObjFile->getBytesInAddress() == 8 && !ObjFile->isLittleEndian()) { 203 auto Obj = llvm::make_unique<DyldELFObject<ELFType<support::big, 2, true>>>( 204 std::move(ObjFile), Buffer, ec); 205 return new ELFObjectImage<ELFType<support::big, 2, true>>(nullptr, 206 std::move(Obj)); 207 } else if (ObjFile->getBytesInAddress() == 8 && ObjFile->isLittleEndian()) { 208 auto Obj = 209 llvm::make_unique<DyldELFObject<ELFType<support::little, 2, true>>>( 210 std::move(ObjFile), Buffer, ec); 211 return new ELFObjectImage<ELFType<support::little, 2, true>>( 212 nullptr, std::move(Obj)); 213 } else 214 llvm_unreachable("Unexpected ELF format"); 215 } 216 217 std::unique_ptr<ObjectImage> 218 RuntimeDyldELF::createObjectImage(std::unique_ptr<ObjectBuffer> Buffer) { 219 if (Buffer->getBufferSize() < ELF::EI_NIDENT) 220 llvm_unreachable("Unexpected ELF object size"); 221 std::pair<unsigned char, unsigned char> Ident = 222 std::make_pair((uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS], 223 (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]); 224 std::error_code ec; 225 226 MemoryBufferRef Buf = Buffer->getMemBuffer(); 227 228 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) { 229 auto Obj = 230 llvm::make_unique<DyldELFObject<ELFType<support::little, 4, false>>>( 231 Buf, ec); 232 return llvm::make_unique< 233 ELFObjectImage<ELFType<support::little, 4, false>>>(std::move(Buffer), 234 std::move(Obj)); 235 } 236 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB) { 237 auto Obj = 238 llvm::make_unique<DyldELFObject<ELFType<support::big, 4, false>>>(Buf, 239 ec); 240 return llvm::make_unique<ELFObjectImage<ELFType<support::big, 4, false>>>( 241 std::move(Buffer), std::move(Obj)); 242 } 243 if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB) { 244 auto Obj = llvm::make_unique<DyldELFObject<ELFType<support::big, 8, true>>>( 245 Buf, ec); 246 return llvm::make_unique<ELFObjectImage<ELFType<support::big, 8, true>>>( 247 std::move(Buffer), std::move(Obj)); 248 } 249 assert(Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB && 250 "Unexpected ELF format"); 251 auto Obj = 252 llvm::make_unique<DyldELFObject<ELFType<support::little, 8, true>>>(Buf, 253 ec); 254 return llvm::make_unique<ELFObjectImage<ELFType<support::little, 8, true>>>( 255 std::move(Buffer), std::move(Obj)); 256 } 257 258 RuntimeDyldELF::~RuntimeDyldELF() {} 259 260 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section, 261 uint64_t Offset, uint64_t Value, 262 uint32_t Type, int64_t Addend, 263 uint64_t SymOffset) { 264 switch (Type) { 265 default: 266 llvm_unreachable("Relocation type not implemented yet!"); 267 break; 268 case ELF::R_X86_64_64: { 269 support::ulittle64_t::ref(Section.Address + Offset) = Value + Addend; 270 DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at " 271 << format("%p\n", Section.Address + Offset)); 272 break; 273 } 274 case ELF::R_X86_64_32: 275 case ELF::R_X86_64_32S: { 276 Value += Addend; 277 assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) || 278 (Type == ELF::R_X86_64_32S && 279 ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN))); 280 uint32_t TruncatedAddr = (Value & 0xFFFFFFFF); 281 support::ulittle32_t::ref(Section.Address + Offset) = TruncatedAddr; 282 DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at " 283 << format("%p\n", Section.Address + Offset)); 284 break; 285 } 286 case ELF::R_X86_64_GOTPCREL: { 287 // findGOTEntry returns the 'G + GOT' part of the relocation calculation 288 // based on the load/target address of the GOT (not the current/local addr). 289 uint64_t GOTAddr = findGOTEntry(Value, SymOffset); 290 uint64_t FinalAddress = Section.LoadAddress + Offset; 291 // The processRelocationRef method combines the symbol offset and the addend 292 // and in most cases that's what we want. For this relocation type, we need 293 // the raw addend, so we subtract the symbol offset to get it. 294 int64_t RealOffset = GOTAddr + Addend - SymOffset - FinalAddress; 295 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN); 296 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF); 297 support::ulittle32_t::ref(Section.Address + Offset) = TruncOffset; 298 break; 299 } 300 case ELF::R_X86_64_PC32: { 301 // Get the placeholder value from the generated object since 302 // a previous relocation attempt may have overwritten the loaded version 303 support::ulittle32_t::ref Placeholder( 304 (void *)(Section.ObjAddress + Offset)); 305 uint64_t FinalAddress = Section.LoadAddress + Offset; 306 int64_t RealOffset = Placeholder + Value + Addend - FinalAddress; 307 assert(RealOffset <= INT32_MAX && RealOffset >= INT32_MIN); 308 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF); 309 support::ulittle32_t::ref(Section.Address + Offset) = TruncOffset; 310 break; 311 } 312 case ELF::R_X86_64_PC64: { 313 // Get the placeholder value from the generated object since 314 // a previous relocation attempt may have overwritten the loaded version 315 support::ulittle64_t::ref Placeholder( 316 (void *)(Section.ObjAddress + Offset)); 317 uint64_t FinalAddress = Section.LoadAddress + Offset; 318 support::ulittle64_t::ref(Section.Address + Offset) = 319 Placeholder + Value + Addend - FinalAddress; 320 break; 321 } 322 } 323 } 324 325 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section, 326 uint64_t Offset, uint32_t Value, 327 uint32_t Type, int32_t Addend) { 328 switch (Type) { 329 case ELF::R_386_32: { 330 // Get the placeholder value from the generated object since 331 // a previous relocation attempt may have overwritten the loaded version 332 support::ulittle32_t::ref Placeholder( 333 (void *)(Section.ObjAddress + Offset)); 334 support::ulittle32_t::ref(Section.Address + Offset) = 335 Placeholder + Value + Addend; 336 break; 337 } 338 case ELF::R_386_PC32: { 339 // Get the placeholder value from the generated object since 340 // a previous relocation attempt may have overwritten the loaded version 341 support::ulittle32_t::ref Placeholder( 342 (void *)(Section.ObjAddress + Offset)); 343 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF); 344 uint32_t RealOffset = Placeholder + Value + Addend - FinalAddress; 345 support::ulittle32_t::ref(Section.Address + Offset) = RealOffset; 346 break; 347 } 348 default: 349 // There are other relocation types, but it appears these are the 350 // only ones currently used by the LLVM ELF object writer 351 llvm_unreachable("Relocation type not implemented yet!"); 352 break; 353 } 354 } 355 356 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section, 357 uint64_t Offset, uint64_t Value, 358 uint32_t Type, int64_t Addend) { 359 uint32_t *TargetPtr = reinterpret_cast<uint32_t *>(Section.Address + Offset); 360 uint64_t FinalAddress = Section.LoadAddress + Offset; 361 362 DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x" 363 << format("%llx", Section.Address + Offset) 364 << " FinalAddress: 0x" << format("%llx", FinalAddress) 365 << " Value: 0x" << format("%llx", Value) << " Type: 0x" 366 << format("%x", Type) << " Addend: 0x" << format("%llx", Addend) 367 << "\n"); 368 369 switch (Type) { 370 default: 371 llvm_unreachable("Relocation type not implemented yet!"); 372 break; 373 case ELF::R_AARCH64_ABS64: { 374 uint64_t *TargetPtr = 375 reinterpret_cast<uint64_t *>(Section.Address + Offset); 376 *TargetPtr = Value + Addend; 377 break; 378 } 379 case ELF::R_AARCH64_PREL32: { 380 uint64_t Result = Value + Addend - FinalAddress; 381 assert(static_cast<int64_t>(Result) >= INT32_MIN && 382 static_cast<int64_t>(Result) <= UINT32_MAX); 383 *TargetPtr = static_cast<uint32_t>(Result & 0xffffffffU); 384 break; 385 } 386 case ELF::R_AARCH64_CALL26: // fallthrough 387 case ELF::R_AARCH64_JUMP26: { 388 // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the 389 // calculation. 390 uint64_t BranchImm = Value + Addend - FinalAddress; 391 392 // "Check that -2^27 <= result < 2^27". 393 assert(-(1LL << 27) <= static_cast<int64_t>(BranchImm) && 394 static_cast<int64_t>(BranchImm) < (1LL << 27)); 395 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 &= 0xfc000000U; 399 // Immediate goes in bits 25:0 of B and BL. 400 *TargetPtr |= static_cast<uint32_t>(BranchImm & 0xffffffcU) >> 2; 401 break; 402 } 403 case ELF::R_AARCH64_MOVW_UABS_G3: { 404 uint64_t Result = Value + Addend; 405 406 // AArch64 code is emitted with .rela relocations. The data already in any 407 // bits affected by the relocation on entry is garbage. 408 *TargetPtr &= 0xffe0001fU; 409 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction 410 *TargetPtr |= Result >> (48 - 5); 411 // Shift must be "lsl #48", in bits 22:21 412 assert((*TargetPtr >> 21 & 0x3) == 3 && "invalid shift for relocation"); 413 break; 414 } 415 case ELF::R_AARCH64_MOVW_UABS_G2_NC: { 416 uint64_t Result = Value + Addend; 417 418 // AArch64 code is emitted with .rela relocations. The data already in any 419 // bits affected by the relocation on entry is garbage. 420 *TargetPtr &= 0xffe0001fU; 421 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction 422 *TargetPtr |= ((Result & 0xffff00000000ULL) >> (32 - 5)); 423 // Shift must be "lsl #32", in bits 22:21 424 assert((*TargetPtr >> 21 & 0x3) == 2 && "invalid shift for relocation"); 425 break; 426 } 427 case ELF::R_AARCH64_MOVW_UABS_G1_NC: { 428 uint64_t Result = Value + Addend; 429 430 // AArch64 code is emitted with .rela relocations. The data already in any 431 // bits affected by the relocation on entry is garbage. 432 *TargetPtr &= 0xffe0001fU; 433 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction 434 *TargetPtr |= ((Result & 0xffff0000U) >> (16 - 5)); 435 // Shift must be "lsl #16", in bits 22:2 436 assert((*TargetPtr >> 21 & 0x3) == 1 && "invalid shift for relocation"); 437 break; 438 } 439 case ELF::R_AARCH64_MOVW_UABS_G0_NC: { 440 uint64_t Result = Value + Addend; 441 442 // AArch64 code is emitted with .rela relocations. The data already in any 443 // bits affected by the relocation on entry is garbage. 444 *TargetPtr &= 0xffe0001fU; 445 // Immediate goes in bits 20:5 of MOVZ/MOVK instruction 446 *TargetPtr |= ((Result & 0xffffU) << 5); 447 // Shift must be "lsl #0", in bits 22:21. 448 assert((*TargetPtr >> 21 & 0x3) == 0 && "invalid shift for relocation"); 449 break; 450 } 451 case ELF::R_AARCH64_ADR_PREL_PG_HI21: { 452 // Operation: Page(S+A) - Page(P) 453 uint64_t Result = 454 ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL); 455 456 // Check that -2^32 <= X < 2^32 457 assert(static_cast<int64_t>(Result) >= (-1LL << 32) && 458 static_cast<int64_t>(Result) < (1LL << 32) && 459 "overflow check failed for relocation"); 460 461 // AArch64 code is emitted with .rela relocations. The data already in any 462 // bits affected by the relocation on entry is garbage. 463 *TargetPtr &= 0x9f00001fU; 464 // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken 465 // from bits 32:12 of X. 466 *TargetPtr |= ((Result & 0x3000U) << (29 - 12)); 467 *TargetPtr |= ((Result & 0x1ffffc000ULL) >> (14 - 5)); 468 break; 469 } 470 case ELF::R_AARCH64_LDST32_ABS_LO12_NC: { 471 // Operation: S + A 472 uint64_t Result = Value + Addend; 473 474 // AArch64 code is emitted with .rela relocations. The data already in any 475 // bits affected by the relocation on entry is garbage. 476 *TargetPtr &= 0xffc003ffU; 477 // Immediate goes in bits 21:10 of LD/ST instruction, taken 478 // from bits 11:2 of X 479 *TargetPtr |= ((Result & 0xffc) << (10 - 2)); 480 break; 481 } 482 case ELF::R_AARCH64_LDST64_ABS_LO12_NC: { 483 // Operation: S + A 484 uint64_t Result = Value + Addend; 485 486 // AArch64 code is emitted with .rela relocations. The data already in any 487 // bits affected by the relocation on entry is garbage. 488 *TargetPtr &= 0xffc003ffU; 489 // Immediate goes in bits 21:10 of LD/ST instruction, taken 490 // from bits 11:3 of X 491 *TargetPtr |= ((Result & 0xff8) << (10 - 3)); 492 break; 493 } 494 } 495 } 496 497 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section, 498 uint64_t Offset, uint32_t Value, 499 uint32_t Type, int32_t Addend) { 500 // TODO: Add Thumb relocations. 501 uint32_t *Placeholder = 502 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset); 503 uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset); 504 uint32_t FinalAddress = ((Section.LoadAddress + Offset) & 0xFFFFFFFF); 505 Value += Addend; 506 507 DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: " 508 << Section.Address + Offset 509 << " FinalAddress: " << format("%p", FinalAddress) << " Value: " 510 << format("%x", Value) << " Type: " << format("%x", Type) 511 << " Addend: " << format("%x", Addend) << "\n"); 512 513 switch (Type) { 514 default: 515 llvm_unreachable("Not implemented relocation type!"); 516 517 case ELF::R_ARM_NONE: 518 break; 519 // Write a 32bit value to relocation address, taking into account the 520 // implicit addend encoded in the target. 521 case ELF::R_ARM_PREL31: 522 case ELF::R_ARM_TARGET1: 523 case ELF::R_ARM_ABS32: 524 *TargetPtr = *Placeholder + Value; 525 break; 526 // Write first 16 bit of 32 bit value to the mov instruction. 527 // Last 4 bit should be shifted. 528 case ELF::R_ARM_MOVW_ABS_NC: 529 // We are not expecting any other addend in the relocation address. 530 // Using 0x000F0FFF because MOVW has its 16 bit immediate split into 2 531 // non-contiguous fields. 532 assert((*Placeholder & 0x000F0FFF) == 0); 533 Value = Value & 0xFFFF; 534 *TargetPtr = *Placeholder | (Value & 0xFFF); 535 *TargetPtr |= ((Value >> 12) & 0xF) << 16; 536 break; 537 // Write last 16 bit of 32 bit value to the mov instruction. 538 // Last 4 bit should be shifted. 539 case ELF::R_ARM_MOVT_ABS: 540 // We are not expecting any other addend in the relocation address. 541 // Use 0x000F0FFF for the same reason as R_ARM_MOVW_ABS_NC. 542 assert((*Placeholder & 0x000F0FFF) == 0); 543 544 Value = (Value >> 16) & 0xFFFF; 545 *TargetPtr = *Placeholder | (Value & 0xFFF); 546 *TargetPtr |= ((Value >> 12) & 0xF) << 16; 547 break; 548 // Write 24 bit relative value to the branch instruction. 549 case ELF::R_ARM_PC24: // Fall through. 550 case ELF::R_ARM_CALL: // Fall through. 551 case ELF::R_ARM_JUMP24: { 552 int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8); 553 RelValue = (RelValue & 0x03FFFFFC) >> 2; 554 assert((*TargetPtr & 0xFFFFFF) == 0xFFFFFE); 555 *TargetPtr &= 0xFF000000; 556 *TargetPtr |= RelValue; 557 break; 558 } 559 case ELF::R_ARM_PRIVATE_0: 560 // This relocation is reserved by the ARM ELF ABI for internal use. We 561 // appropriate it here to act as an R_ARM_ABS32 without any addend for use 562 // in the stubs created during JIT (which can't put an addend into the 563 // original object file). 564 *TargetPtr = Value; 565 break; 566 } 567 } 568 569 void RuntimeDyldELF::resolveMIPSRelocation(const SectionEntry &Section, 570 uint64_t Offset, uint32_t Value, 571 uint32_t Type, int32_t Addend) { 572 uint32_t *Placeholder = 573 reinterpret_cast<uint32_t *>(Section.ObjAddress + Offset); 574 uint32_t *TargetPtr = (uint32_t *)(Section.Address + Offset); 575 Value += Addend; 576 577 DEBUG(dbgs() << "resolveMipselocation, LocalAddress: " 578 << Section.Address + Offset << " FinalAddress: " 579 << format("%p", Section.LoadAddress + Offset) << " Value: " 580 << format("%x", Value) << " Type: " << format("%x", Type) 581 << " Addend: " << format("%x", Addend) << "\n"); 582 583 switch (Type) { 584 default: 585 llvm_unreachable("Not implemented relocation type!"); 586 break; 587 case ELF::R_MIPS_32: 588 *TargetPtr = Value + (*Placeholder); 589 break; 590 case ELF::R_MIPS_26: 591 *TargetPtr = ((*Placeholder) & 0xfc000000) | ((Value & 0x0fffffff) >> 2); 592 break; 593 case ELF::R_MIPS_HI16: 594 // Get the higher 16-bits. Also add 1 if bit 15 is 1. 595 Value += ((*Placeholder) & 0x0000ffff) << 16; 596 *TargetPtr = 597 ((*Placeholder) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff); 598 break; 599 case ELF::R_MIPS_LO16: 600 Value += ((*Placeholder) & 0x0000ffff); 601 *TargetPtr = ((*Placeholder) & 0xffff0000) | (Value & 0xffff); 602 break; 603 case ELF::R_MIPS_UNUSED1: 604 // Similar to ELF::R_ARM_PRIVATE_0, R_MIPS_UNUSED1 and R_MIPS_UNUSED2 605 // are used for internal JIT purpose. These relocations are similar to 606 // R_MIPS_HI16 and R_MIPS_LO16, but they do not take any addend into 607 // account. 608 *TargetPtr = 609 ((*TargetPtr) & 0xffff0000) | (((Value + 0x8000) >> 16) & 0xffff); 610 break; 611 case ELF::R_MIPS_UNUSED2: 612 *TargetPtr = ((*TargetPtr) & 0xffff0000) | (Value & 0xffff); 613 break; 614 } 615 } 616 617 // Return the .TOC. section and offset. 618 void RuntimeDyldELF::findPPC64TOCSection(ObjectImage &Obj, 619 ObjSectionToIDMap &LocalSections, 620 RelocationValueRef &Rel) { 621 // Set a default SectionID in case we do not find a TOC section below. 622 // This may happen for references to TOC base base (sym@toc, .odp 623 // relocation) without a .toc directive. In this case just use the 624 // first section (which is usually the .odp) since the code won't 625 // reference the .toc base directly. 626 Rel.SymbolName = NULL; 627 Rel.SectionID = 0; 628 629 // The TOC consists of sections .got, .toc, .tocbss, .plt in that 630 // order. The TOC starts where the first of these sections starts. 631 for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections(); 632 si != se; ++si) { 633 634 StringRef SectionName; 635 check(si->getName(SectionName)); 636 637 if (SectionName == ".got" 638 || SectionName == ".toc" 639 || SectionName == ".tocbss" 640 || SectionName == ".plt") { 641 Rel.SectionID = findOrEmitSection(Obj, *si, false, LocalSections); 642 break; 643 } 644 } 645 646 // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000 647 // thus permitting a full 64 Kbytes segment. 648 Rel.Addend = 0x8000; 649 } 650 651 // Returns the sections and offset associated with the ODP entry referenced 652 // by Symbol. 653 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj, 654 ObjSectionToIDMap &LocalSections, 655 RelocationValueRef &Rel) { 656 // Get the ELF symbol value (st_value) to compare with Relocation offset in 657 // .opd entries 658 for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections(); 659 si != se; ++si) { 660 section_iterator RelSecI = si->getRelocatedSection(); 661 if (RelSecI == Obj.end_sections()) 662 continue; 663 664 StringRef RelSectionName; 665 check(RelSecI->getName(RelSectionName)); 666 if (RelSectionName != ".opd") 667 continue; 668 669 for (relocation_iterator i = si->relocation_begin(), 670 e = si->relocation_end(); 671 i != e;) { 672 // The R_PPC64_ADDR64 relocation indicates the first field 673 // of a .opd entry 674 uint64_t TypeFunc; 675 check(i->getType(TypeFunc)); 676 if (TypeFunc != ELF::R_PPC64_ADDR64) { 677 ++i; 678 continue; 679 } 680 681 uint64_t TargetSymbolOffset; 682 symbol_iterator TargetSymbol = i->getSymbol(); 683 check(i->getOffset(TargetSymbolOffset)); 684 int64_t Addend; 685 check(getELFRelocationAddend(*i, Addend)); 686 687 ++i; 688 if (i == e) 689 break; 690 691 // Just check if following relocation is a R_PPC64_TOC 692 uint64_t TypeTOC; 693 check(i->getType(TypeTOC)); 694 if (TypeTOC != ELF::R_PPC64_TOC) 695 continue; 696 697 // Finally compares the Symbol value and the target symbol offset 698 // to check if this .opd entry refers to the symbol the relocation 699 // points to. 700 if (Rel.Addend != (int64_t)TargetSymbolOffset) 701 continue; 702 703 section_iterator tsi(Obj.end_sections()); 704 check(TargetSymbol->getSection(tsi)); 705 bool IsCode = tsi->isText(); 706 Rel.SectionID = findOrEmitSection(Obj, (*tsi), IsCode, LocalSections); 707 Rel.Addend = (intptr_t)Addend; 708 return; 709 } 710 } 711 llvm_unreachable("Attempting to get address of ODP entry!"); 712 } 713 714 // Relocation masks following the #lo(value), #hi(value), #ha(value), 715 // #higher(value), #highera(value), #highest(value), and #highesta(value) 716 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi 717 // document. 718 719 static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; } 720 721 static inline uint16_t applyPPChi(uint64_t value) { 722 return (value >> 16) & 0xffff; 723 } 724 725 static inline uint16_t applyPPCha (uint64_t value) { 726 return ((value + 0x8000) >> 16) & 0xffff; 727 } 728 729 static inline uint16_t applyPPChigher(uint64_t value) { 730 return (value >> 32) & 0xffff; 731 } 732 733 static inline uint16_t applyPPChighera (uint64_t value) { 734 return ((value + 0x8000) >> 32) & 0xffff; 735 } 736 737 static inline uint16_t applyPPChighest(uint64_t value) { 738 return (value >> 48) & 0xffff; 739 } 740 741 static inline uint16_t applyPPChighesta (uint64_t value) { 742 return ((value + 0x8000) >> 48) & 0xffff; 743 } 744 745 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section, 746 uint64_t Offset, uint64_t Value, 747 uint32_t Type, int64_t Addend) { 748 uint8_t *LocalAddress = Section.Address + Offset; 749 switch (Type) { 750 default: 751 llvm_unreachable("Relocation type not implemented yet!"); 752 break; 753 case ELF::R_PPC64_ADDR16: 754 writeInt16BE(LocalAddress, applyPPClo(Value + Addend)); 755 break; 756 case ELF::R_PPC64_ADDR16_DS: 757 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3); 758 break; 759 case ELF::R_PPC64_ADDR16_LO: 760 writeInt16BE(LocalAddress, applyPPClo(Value + Addend)); 761 break; 762 case ELF::R_PPC64_ADDR16_LO_DS: 763 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3); 764 break; 765 case ELF::R_PPC64_ADDR16_HI: 766 writeInt16BE(LocalAddress, applyPPChi(Value + Addend)); 767 break; 768 case ELF::R_PPC64_ADDR16_HA: 769 writeInt16BE(LocalAddress, applyPPCha(Value + Addend)); 770 break; 771 case ELF::R_PPC64_ADDR16_HIGHER: 772 writeInt16BE(LocalAddress, applyPPChigher(Value + Addend)); 773 break; 774 case ELF::R_PPC64_ADDR16_HIGHERA: 775 writeInt16BE(LocalAddress, applyPPChighera(Value + Addend)); 776 break; 777 case ELF::R_PPC64_ADDR16_HIGHEST: 778 writeInt16BE(LocalAddress, applyPPChighest(Value + Addend)); 779 break; 780 case ELF::R_PPC64_ADDR16_HIGHESTA: 781 writeInt16BE(LocalAddress, applyPPChighesta(Value + Addend)); 782 break; 783 case ELF::R_PPC64_ADDR14: { 784 assert(((Value + Addend) & 3) == 0); 785 // Preserve the AA/LK bits in the branch instruction 786 uint8_t aalk = *(LocalAddress + 3); 787 writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc)); 788 } break; 789 case ELF::R_PPC64_REL16_LO: { 790 uint64_t FinalAddress = (Section.LoadAddress + Offset); 791 uint64_t Delta = Value - FinalAddress + Addend; 792 writeInt16BE(LocalAddress, applyPPClo(Delta)); 793 } break; 794 case ELF::R_PPC64_REL16_HI: { 795 uint64_t FinalAddress = (Section.LoadAddress + Offset); 796 uint64_t Delta = Value - FinalAddress + Addend; 797 writeInt16BE(LocalAddress, applyPPChi(Delta)); 798 } break; 799 case ELF::R_PPC64_REL16_HA: { 800 uint64_t FinalAddress = (Section.LoadAddress + Offset); 801 uint64_t Delta = Value - FinalAddress + Addend; 802 writeInt16BE(LocalAddress, applyPPCha(Delta)); 803 } break; 804 case ELF::R_PPC64_ADDR32: { 805 int32_t Result = static_cast<int32_t>(Value + Addend); 806 if (SignExtend32<32>(Result) != Result) 807 llvm_unreachable("Relocation R_PPC64_ADDR32 overflow"); 808 writeInt32BE(LocalAddress, Result); 809 } break; 810 case ELF::R_PPC64_REL24: { 811 uint64_t FinalAddress = (Section.LoadAddress + Offset); 812 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend); 813 if (SignExtend32<24>(delta) != delta) 814 llvm_unreachable("Relocation R_PPC64_REL24 overflow"); 815 // Generates a 'bl <address>' instruction 816 writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC)); 817 } break; 818 case ELF::R_PPC64_REL32: { 819 uint64_t FinalAddress = (Section.LoadAddress + Offset); 820 int32_t delta = static_cast<int32_t>(Value - FinalAddress + Addend); 821 if (SignExtend32<32>(delta) != delta) 822 llvm_unreachable("Relocation R_PPC64_REL32 overflow"); 823 writeInt32BE(LocalAddress, delta); 824 } break; 825 case ELF::R_PPC64_REL64: { 826 uint64_t FinalAddress = (Section.LoadAddress + Offset); 827 uint64_t Delta = Value - FinalAddress + Addend; 828 writeInt64BE(LocalAddress, Delta); 829 } break; 830 case ELF::R_PPC64_ADDR64: 831 writeInt64BE(LocalAddress, Value + Addend); 832 break; 833 } 834 } 835 836 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section, 837 uint64_t Offset, uint64_t Value, 838 uint32_t Type, int64_t Addend) { 839 uint8_t *LocalAddress = Section.Address + Offset; 840 switch (Type) { 841 default: 842 llvm_unreachable("Relocation type not implemented yet!"); 843 break; 844 case ELF::R_390_PC16DBL: 845 case ELF::R_390_PLT16DBL: { 846 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset); 847 assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow"); 848 writeInt16BE(LocalAddress, Delta / 2); 849 break; 850 } 851 case ELF::R_390_PC32DBL: 852 case ELF::R_390_PLT32DBL: { 853 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset); 854 assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow"); 855 writeInt32BE(LocalAddress, Delta / 2); 856 break; 857 } 858 case ELF::R_390_PC32: { 859 int64_t Delta = (Value + Addend) - (Section.LoadAddress + Offset); 860 assert(int32_t(Delta) == Delta && "R_390_PC32 overflow"); 861 writeInt32BE(LocalAddress, Delta); 862 break; 863 } 864 case ELF::R_390_64: 865 writeInt64BE(LocalAddress, Value + Addend); 866 break; 867 } 868 } 869 870 // The target location for the relocation is described by RE.SectionID and 871 // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each 872 // SectionEntry has three members describing its location. 873 // SectionEntry::Address is the address at which the section has been loaded 874 // into memory in the current (host) process. SectionEntry::LoadAddress is the 875 // address that the section will have in the target process. 876 // SectionEntry::ObjAddress is the address of the bits for this section in the 877 // original emitted object image (also in the current address space). 878 // 879 // Relocations will be applied as if the section were loaded at 880 // SectionEntry::LoadAddress, but they will be applied at an address based 881 // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to 882 // Target memory contents if they are required for value calculations. 883 // 884 // The Value parameter here is the load address of the symbol for the 885 // relocation to be applied. For relocations which refer to symbols in the 886 // current object Value will be the LoadAddress of the section in which 887 // the symbol resides (RE.Addend provides additional information about the 888 // symbol location). For external symbols, Value will be the address of the 889 // symbol in the target address space. 890 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE, 891 uint64_t Value) { 892 const SectionEntry &Section = Sections[RE.SectionID]; 893 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend, 894 RE.SymOffset); 895 } 896 897 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section, 898 uint64_t Offset, uint64_t Value, 899 uint32_t Type, int64_t Addend, 900 uint64_t SymOffset) { 901 switch (Arch) { 902 case Triple::x86_64: 903 resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset); 904 break; 905 case Triple::x86: 906 resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type, 907 (uint32_t)(Addend & 0xffffffffL)); 908 break; 909 case Triple::aarch64: 910 case Triple::aarch64_be: 911 resolveAArch64Relocation(Section, Offset, Value, Type, Addend); 912 break; 913 case Triple::arm: // Fall through. 914 case Triple::armeb: 915 case Triple::thumb: 916 case Triple::thumbeb: 917 resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type, 918 (uint32_t)(Addend & 0xffffffffL)); 919 break; 920 case Triple::mips: // Fall through. 921 case Triple::mipsel: 922 resolveMIPSRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), 923 Type, (uint32_t)(Addend & 0xffffffffL)); 924 break; 925 case Triple::ppc64: // Fall through. 926 case Triple::ppc64le: 927 resolvePPC64Relocation(Section, Offset, Value, Type, Addend); 928 break; 929 case Triple::systemz: 930 resolveSystemZRelocation(Section, Offset, Value, Type, Addend); 931 break; 932 default: 933 llvm_unreachable("Unsupported CPU type!"); 934 } 935 } 936 937 relocation_iterator RuntimeDyldELF::processRelocationRef( 938 unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj, 939 ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols, 940 StubMap &Stubs) { 941 uint64_t RelType; 942 Check(RelI->getType(RelType)); 943 int64_t Addend; 944 Check(getELFRelocationAddend(*RelI, Addend)); 945 symbol_iterator Symbol = RelI->getSymbol(); 946 947 // Obtain the symbol name which is referenced in the relocation 948 StringRef TargetName; 949 if (Symbol != Obj.end_symbols()) 950 Symbol->getName(TargetName); 951 DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend 952 << " TargetName: " << TargetName << "\n"); 953 RelocationValueRef Value; 954 // First search for the symbol in the local symbol table 955 SymbolTableMap::const_iterator lsi = Symbols.end(); 956 SymbolRef::Type SymType = SymbolRef::ST_Unknown; 957 if (Symbol != Obj.end_symbols()) { 958 lsi = Symbols.find(TargetName.data()); 959 Symbol->getType(SymType); 960 } 961 if (lsi != Symbols.end()) { 962 Value.SectionID = lsi->second.first; 963 Value.Offset = lsi->second.second; 964 Value.Addend = lsi->second.second + Addend; 965 } else { 966 // Search for the symbol in the global symbol table 967 SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end(); 968 if (Symbol != Obj.end_symbols()) 969 gsi = GlobalSymbolTable.find(TargetName.data()); 970 if (gsi != GlobalSymbolTable.end()) { 971 Value.SectionID = gsi->second.first; 972 Value.Offset = gsi->second.second; 973 Value.Addend = gsi->second.second + Addend; 974 } else { 975 switch (SymType) { 976 case SymbolRef::ST_Debug: { 977 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously 978 // and can be changed by another developers. Maybe best way is add 979 // a new symbol type ST_Section to SymbolRef and use it. 980 section_iterator si(Obj.end_sections()); 981 Symbol->getSection(si); 982 if (si == Obj.end_sections()) 983 llvm_unreachable("Symbol section not found, bad object file format!"); 984 DEBUG(dbgs() << "\t\tThis is section symbol\n"); 985 bool isCode = si->isText(); 986 Value.SectionID = findOrEmitSection(Obj, (*si), isCode, ObjSectionToID); 987 Value.Addend = Addend; 988 break; 989 } 990 case SymbolRef::ST_Data: 991 case SymbolRef::ST_Unknown: { 992 Value.SymbolName = TargetName.data(); 993 Value.Addend = Addend; 994 995 // Absolute relocations will have a zero symbol ID (STN_UNDEF), which 996 // will manifest here as a NULL symbol name. 997 // We can set this as a valid (but empty) symbol name, and rely 998 // on addRelocationForSymbol to handle this. 999 if (!Value.SymbolName) 1000 Value.SymbolName = ""; 1001 break; 1002 } 1003 default: 1004 llvm_unreachable("Unresolved symbol type!"); 1005 break; 1006 } 1007 } 1008 } 1009 uint64_t Offset; 1010 Check(RelI->getOffset(Offset)); 1011 1012 DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset 1013 << "\n"); 1014 if ((Arch == Triple::aarch64 || Arch == Triple::aarch64_be) && 1015 (RelType == ELF::R_AARCH64_CALL26 || RelType == ELF::R_AARCH64_JUMP26)) { 1016 // This is an AArch64 branch relocation, need to use a stub function. 1017 DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation."); 1018 SectionEntry &Section = Sections[SectionID]; 1019 1020 // Look for an existing stub. 1021 StubMap::const_iterator i = Stubs.find(Value); 1022 if (i != Stubs.end()) { 1023 resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second, 1024 RelType, 0); 1025 DEBUG(dbgs() << " Stub function found\n"); 1026 } else { 1027 // Create a new stub function. 1028 DEBUG(dbgs() << " Create a new stub function\n"); 1029 Stubs[Value] = Section.StubOffset; 1030 uint8_t *StubTargetAddr = 1031 createStubFunction(Section.Address + Section.StubOffset); 1032 1033 RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.Address, 1034 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend); 1035 RelocationEntry REmovk_g2(SectionID, StubTargetAddr - Section.Address + 4, 1036 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend); 1037 RelocationEntry REmovk_g1(SectionID, StubTargetAddr - Section.Address + 8, 1038 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend); 1039 RelocationEntry REmovk_g0(SectionID, 1040 StubTargetAddr - Section.Address + 12, 1041 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend); 1042 1043 if (Value.SymbolName) { 1044 addRelocationForSymbol(REmovz_g3, Value.SymbolName); 1045 addRelocationForSymbol(REmovk_g2, Value.SymbolName); 1046 addRelocationForSymbol(REmovk_g1, Value.SymbolName); 1047 addRelocationForSymbol(REmovk_g0, Value.SymbolName); 1048 } else { 1049 addRelocationForSection(REmovz_g3, Value.SectionID); 1050 addRelocationForSection(REmovk_g2, Value.SectionID); 1051 addRelocationForSection(REmovk_g1, Value.SectionID); 1052 addRelocationForSection(REmovk_g0, Value.SectionID); 1053 } 1054 resolveRelocation(Section, Offset, 1055 (uint64_t)Section.Address + Section.StubOffset, RelType, 1056 0); 1057 Section.StubOffset += getMaxStubSize(); 1058 } 1059 } else if (Arch == Triple::arm && 1060 (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL || 1061 RelType == ELF::R_ARM_JUMP24)) { 1062 // This is an ARM branch relocation, need to use a stub function. 1063 DEBUG(dbgs() << "\t\tThis is an ARM branch relocation."); 1064 SectionEntry &Section = Sections[SectionID]; 1065 1066 // Look for an existing stub. 1067 StubMap::const_iterator i = Stubs.find(Value); 1068 if (i != Stubs.end()) { 1069 resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second, 1070 RelType, 0); 1071 DEBUG(dbgs() << " Stub function found\n"); 1072 } else { 1073 // Create a new stub function. 1074 DEBUG(dbgs() << " Create a new stub function\n"); 1075 Stubs[Value] = Section.StubOffset; 1076 uint8_t *StubTargetAddr = 1077 createStubFunction(Section.Address + Section.StubOffset); 1078 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address, 1079 ELF::R_ARM_PRIVATE_0, Value.Addend); 1080 if (Value.SymbolName) 1081 addRelocationForSymbol(RE, Value.SymbolName); 1082 else 1083 addRelocationForSection(RE, Value.SectionID); 1084 1085 resolveRelocation(Section, Offset, 1086 (uint64_t)Section.Address + Section.StubOffset, RelType, 1087 0); 1088 Section.StubOffset += getMaxStubSize(); 1089 } 1090 } else if ((Arch == Triple::mipsel || Arch == Triple::mips) && 1091 RelType == ELF::R_MIPS_26) { 1092 // This is an Mips branch relocation, need to use a stub function. 1093 DEBUG(dbgs() << "\t\tThis is a Mips branch relocation."); 1094 SectionEntry &Section = Sections[SectionID]; 1095 uint8_t *Target = Section.Address + Offset; 1096 uint32_t *TargetAddress = (uint32_t *)Target; 1097 1098 // Extract the addend from the instruction. 1099 uint32_t Addend = ((*TargetAddress) & 0x03ffffff) << 2; 1100 1101 Value.Addend += Addend; 1102 1103 // Look up for existing stub. 1104 StubMap::const_iterator i = Stubs.find(Value); 1105 if (i != Stubs.end()) { 1106 RelocationEntry RE(SectionID, Offset, RelType, i->second); 1107 addRelocationForSection(RE, SectionID); 1108 DEBUG(dbgs() << " Stub function found\n"); 1109 } else { 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 1116 // Creating Hi and Lo relocations for the filled stub instructions. 1117 RelocationEntry REHi(SectionID, StubTargetAddr - Section.Address, 1118 ELF::R_MIPS_UNUSED1, Value.Addend); 1119 RelocationEntry RELo(SectionID, StubTargetAddr - Section.Address + 4, 1120 ELF::R_MIPS_UNUSED2, Value.Addend); 1121 1122 if (Value.SymbolName) { 1123 addRelocationForSymbol(REHi, Value.SymbolName); 1124 addRelocationForSymbol(RELo, Value.SymbolName); 1125 } else { 1126 addRelocationForSection(REHi, Value.SectionID); 1127 addRelocationForSection(RELo, Value.SectionID); 1128 } 1129 1130 RelocationEntry RE(SectionID, Offset, RelType, Section.StubOffset); 1131 addRelocationForSection(RE, SectionID); 1132 Section.StubOffset += getMaxStubSize(); 1133 } 1134 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) { 1135 if (RelType == ELF::R_PPC64_REL24) { 1136 // Determine ABI variant in use for this object. 1137 unsigned AbiVariant; 1138 Obj.getObjectFile()->getPlatformFlags(AbiVariant); 1139 AbiVariant &= ELF::EF_PPC64_ABI; 1140 // A PPC branch relocation will need a stub function if the target is 1141 // an external symbol (Symbol::ST_Unknown) or if the target address 1142 // is not within the signed 24-bits branch address. 1143 SectionEntry &Section = Sections[SectionID]; 1144 uint8_t *Target = Section.Address + Offset; 1145 bool RangeOverflow = false; 1146 if (SymType != SymbolRef::ST_Unknown) { 1147 if (AbiVariant != 2) { 1148 // In the ELFv1 ABI, a function call may point to the .opd entry, 1149 // so the final symbol value is calculated based on the relocation 1150 // values in the .opd section. 1151 findOPDEntrySection(Obj, ObjSectionToID, Value); 1152 } else { 1153 // In the ELFv2 ABI, a function symbol may provide a local entry 1154 // point, which must be used for direct calls. 1155 uint8_t SymOther; 1156 Symbol->getOther(SymOther); 1157 Value.Addend += ELF::decodePPC64LocalEntryOffset(SymOther); 1158 } 1159 uint8_t *RelocTarget = Sections[Value.SectionID].Address + Value.Addend; 1160 int32_t delta = static_cast<int32_t>(Target - RelocTarget); 1161 // If it is within 24-bits branch range, just set the branch target 1162 if (SignExtend32<24>(delta) == delta) { 1163 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend); 1164 if (Value.SymbolName) 1165 addRelocationForSymbol(RE, Value.SymbolName); 1166 else 1167 addRelocationForSection(RE, Value.SectionID); 1168 } else { 1169 RangeOverflow = true; 1170 } 1171 } 1172 if (SymType == SymbolRef::ST_Unknown || RangeOverflow == true) { 1173 // It is an external symbol (SymbolRef::ST_Unknown) or within a range 1174 // larger than 24-bits. 1175 StubMap::const_iterator i = Stubs.find(Value); 1176 if (i != Stubs.end()) { 1177 // Symbol function stub already created, just relocate to it 1178 resolveRelocation(Section, Offset, 1179 (uint64_t)Section.Address + i->second, RelType, 0); 1180 DEBUG(dbgs() << " Stub function found\n"); 1181 } else { 1182 // Create a new stub function. 1183 DEBUG(dbgs() << " Create a new stub function\n"); 1184 Stubs[Value] = Section.StubOffset; 1185 uint8_t *StubTargetAddr = 1186 createStubFunction(Section.Address + Section.StubOffset, 1187 AbiVariant); 1188 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address, 1189 ELF::R_PPC64_ADDR64, Value.Addend); 1190 1191 // Generates the 64-bits address loads as exemplified in section 1192 // 4.5.1 in PPC64 ELF ABI. Note that the relocations need to 1193 // apply to the low part of the instructions, so we have to update 1194 // the offset according to the target endianness. 1195 uint64_t StubRelocOffset = StubTargetAddr - Section.Address; 1196 if (!IsTargetLittleEndian) 1197 StubRelocOffset += 2; 1198 1199 RelocationEntry REhst(SectionID, StubRelocOffset + 0, 1200 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend); 1201 RelocationEntry REhr(SectionID, StubRelocOffset + 4, 1202 ELF::R_PPC64_ADDR16_HIGHER, Value.Addend); 1203 RelocationEntry REh(SectionID, StubRelocOffset + 12, 1204 ELF::R_PPC64_ADDR16_HI, Value.Addend); 1205 RelocationEntry REl(SectionID, StubRelocOffset + 16, 1206 ELF::R_PPC64_ADDR16_LO, Value.Addend); 1207 1208 if (Value.SymbolName) { 1209 addRelocationForSymbol(REhst, Value.SymbolName); 1210 addRelocationForSymbol(REhr, Value.SymbolName); 1211 addRelocationForSymbol(REh, Value.SymbolName); 1212 addRelocationForSymbol(REl, Value.SymbolName); 1213 } else { 1214 addRelocationForSection(REhst, Value.SectionID); 1215 addRelocationForSection(REhr, Value.SectionID); 1216 addRelocationForSection(REh, Value.SectionID); 1217 addRelocationForSection(REl, Value.SectionID); 1218 } 1219 1220 resolveRelocation(Section, Offset, 1221 (uint64_t)Section.Address + Section.StubOffset, 1222 RelType, 0); 1223 Section.StubOffset += getMaxStubSize(); 1224 } 1225 if (SymType == SymbolRef::ST_Unknown) { 1226 // Restore the TOC for external calls 1227 if (AbiVariant == 2) 1228 writeInt32BE(Target + 4, 0xE8410018); // ld r2,28(r1) 1229 else 1230 writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1) 1231 } 1232 } 1233 } else if (RelType == ELF::R_PPC64_TOC16 || 1234 RelType == ELF::R_PPC64_TOC16_DS || 1235 RelType == ELF::R_PPC64_TOC16_LO || 1236 RelType == ELF::R_PPC64_TOC16_LO_DS || 1237 RelType == ELF::R_PPC64_TOC16_HI || 1238 RelType == ELF::R_PPC64_TOC16_HA) { 1239 // These relocations are supposed to subtract the TOC address from 1240 // the final value. This does not fit cleanly into the RuntimeDyld 1241 // scheme, since there may be *two* sections involved in determining 1242 // the relocation value (the section of the symbol refered to by the 1243 // relocation, and the TOC section associated with the current module). 1244 // 1245 // Fortunately, these relocations are currently only ever generated 1246 // refering to symbols that themselves reside in the TOC, which means 1247 // that the two sections are actually the same. Thus they cancel out 1248 // and we can immediately resolve the relocation right now. 1249 switch (RelType) { 1250 case ELF::R_PPC64_TOC16: RelType = ELF::R_PPC64_ADDR16; break; 1251 case ELF::R_PPC64_TOC16_DS: RelType = ELF::R_PPC64_ADDR16_DS; break; 1252 case ELF::R_PPC64_TOC16_LO: RelType = ELF::R_PPC64_ADDR16_LO; break; 1253 case ELF::R_PPC64_TOC16_LO_DS: RelType = ELF::R_PPC64_ADDR16_LO_DS; break; 1254 case ELF::R_PPC64_TOC16_HI: RelType = ELF::R_PPC64_ADDR16_HI; break; 1255 case ELF::R_PPC64_TOC16_HA: RelType = ELF::R_PPC64_ADDR16_HA; break; 1256 default: llvm_unreachable("Wrong relocation type."); 1257 } 1258 1259 RelocationValueRef TOCValue; 1260 findPPC64TOCSection(Obj, ObjSectionToID, TOCValue); 1261 if (Value.SymbolName || Value.SectionID != TOCValue.SectionID) 1262 llvm_unreachable("Unsupported TOC relocation."); 1263 Value.Addend -= TOCValue.Addend; 1264 resolveRelocation(Sections[SectionID], Offset, Value.Addend, RelType, 0); 1265 } else { 1266 // There are two ways to refer to the TOC address directly: either 1267 // via a ELF::R_PPC64_TOC relocation (where both symbol and addend are 1268 // ignored), or via any relocation that refers to the magic ".TOC." 1269 // symbols (in which case the addend is respected). 1270 if (RelType == ELF::R_PPC64_TOC) { 1271 RelType = ELF::R_PPC64_ADDR64; 1272 findPPC64TOCSection(Obj, ObjSectionToID, Value); 1273 } else if (TargetName == ".TOC.") { 1274 findPPC64TOCSection(Obj, ObjSectionToID, Value); 1275 Value.Addend += Addend; 1276 } 1277 1278 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend); 1279 1280 if (Value.SymbolName) 1281 addRelocationForSymbol(RE, Value.SymbolName); 1282 else 1283 addRelocationForSection(RE, Value.SectionID); 1284 } 1285 } else if (Arch == Triple::systemz && 1286 (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) { 1287 // Create function stubs for both PLT and GOT references, regardless of 1288 // whether the GOT reference is to data or code. The stub contains the 1289 // full address of the symbol, as needed by GOT references, and the 1290 // executable part only adds an overhead of 8 bytes. 1291 // 1292 // We could try to conserve space by allocating the code and data 1293 // parts of the stub separately. However, as things stand, we allocate 1294 // a stub for every relocation, so using a GOT in JIT code should be 1295 // no less space efficient than using an explicit constant pool. 1296 DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation."); 1297 SectionEntry &Section = Sections[SectionID]; 1298 1299 // Look for an existing stub. 1300 StubMap::const_iterator i = Stubs.find(Value); 1301 uintptr_t StubAddress; 1302 if (i != Stubs.end()) { 1303 StubAddress = uintptr_t(Section.Address) + i->second; 1304 DEBUG(dbgs() << " Stub function found\n"); 1305 } else { 1306 // Create a new stub function. 1307 DEBUG(dbgs() << " Create a new stub function\n"); 1308 1309 uintptr_t BaseAddress = uintptr_t(Section.Address); 1310 uintptr_t StubAlignment = getStubAlignment(); 1311 StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) & 1312 -StubAlignment; 1313 unsigned StubOffset = StubAddress - BaseAddress; 1314 1315 Stubs[Value] = StubOffset; 1316 createStubFunction((uint8_t *)StubAddress); 1317 RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64, 1318 Value.Offset); 1319 if (Value.SymbolName) 1320 addRelocationForSymbol(RE, Value.SymbolName); 1321 else 1322 addRelocationForSection(RE, Value.SectionID); 1323 Section.StubOffset = StubOffset + getMaxStubSize(); 1324 } 1325 1326 if (RelType == ELF::R_390_GOTENT) 1327 resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL, 1328 Addend); 1329 else 1330 resolveRelocation(Section, Offset, StubAddress, RelType, Addend); 1331 } else if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_PLT32) { 1332 // The way the PLT relocations normally work is that the linker allocates 1333 // the 1334 // PLT and this relocation makes a PC-relative call into the PLT. The PLT 1335 // entry will then jump to an address provided by the GOT. On first call, 1336 // the 1337 // GOT address will point back into PLT code that resolves the symbol. After 1338 // the first call, the GOT entry points to the actual function. 1339 // 1340 // For local functions we're ignoring all of that here and just replacing 1341 // the PLT32 relocation type with PC32, which will translate the relocation 1342 // into a PC-relative call directly to the function. For external symbols we 1343 // can't be sure the function will be within 2^32 bytes of the call site, so 1344 // we need to create a stub, which calls into the GOT. This case is 1345 // equivalent to the usual PLT implementation except that we use the stub 1346 // mechanism in RuntimeDyld (which puts stubs at the end of the section) 1347 // rather than allocating a PLT section. 1348 if (Value.SymbolName) { 1349 // This is a call to an external function. 1350 // Look for an existing stub. 1351 SectionEntry &Section = Sections[SectionID]; 1352 StubMap::const_iterator i = Stubs.find(Value); 1353 uintptr_t StubAddress; 1354 if (i != Stubs.end()) { 1355 StubAddress = uintptr_t(Section.Address) + i->second; 1356 DEBUG(dbgs() << " Stub function found\n"); 1357 } else { 1358 // Create a new stub function (equivalent to a PLT entry). 1359 DEBUG(dbgs() << " Create a new stub function\n"); 1360 1361 uintptr_t BaseAddress = uintptr_t(Section.Address); 1362 uintptr_t StubAlignment = getStubAlignment(); 1363 StubAddress = (BaseAddress + Section.StubOffset + StubAlignment - 1) & 1364 -StubAlignment; 1365 unsigned StubOffset = StubAddress - BaseAddress; 1366 Stubs[Value] = StubOffset; 1367 createStubFunction((uint8_t *)StubAddress); 1368 1369 // Create a GOT entry for the external function. 1370 GOTEntries.push_back(Value); 1371 1372 // Make our stub function a relative call to the GOT entry. 1373 RelocationEntry RE(SectionID, StubOffset + 2, ELF::R_X86_64_GOTPCREL, 1374 -4); 1375 addRelocationForSymbol(RE, Value.SymbolName); 1376 1377 // Bump our stub offset counter 1378 Section.StubOffset = StubOffset + getMaxStubSize(); 1379 } 1380 1381 // Make the target call a call into the stub table. 1382 resolveRelocation(Section, Offset, StubAddress, ELF::R_X86_64_PC32, 1383 Addend); 1384 } else { 1385 RelocationEntry RE(SectionID, Offset, ELF::R_X86_64_PC32, Value.Addend, 1386 Value.Offset); 1387 addRelocationForSection(RE, Value.SectionID); 1388 } 1389 } else { 1390 if (Arch == Triple::x86_64 && RelType == ELF::R_X86_64_GOTPCREL) { 1391 GOTEntries.push_back(Value); 1392 } 1393 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset); 1394 if (Value.SymbolName) 1395 addRelocationForSymbol(RE, Value.SymbolName); 1396 else 1397 addRelocationForSection(RE, Value.SectionID); 1398 } 1399 return ++RelI; 1400 } 1401 1402 void RuntimeDyldELF::updateGOTEntries(StringRef Name, uint64_t Addr) { 1403 1404 SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator it; 1405 SmallVectorImpl<std::pair<SID, GOTRelocations>>::iterator end = GOTs.end(); 1406 1407 for (it = GOTs.begin(); it != end; ++it) { 1408 GOTRelocations &GOTEntries = it->second; 1409 for (int i = 0, e = GOTEntries.size(); i != e; ++i) { 1410 if (GOTEntries[i].SymbolName != nullptr && 1411 GOTEntries[i].SymbolName == Name) { 1412 GOTEntries[i].Offset = Addr; 1413 } 1414 } 1415 } 1416 } 1417 1418 size_t RuntimeDyldELF::getGOTEntrySize() { 1419 // We don't use the GOT in all of these cases, but it's essentially free 1420 // to put them all here. 1421 size_t Result = 0; 1422 switch (Arch) { 1423 case Triple::x86_64: 1424 case Triple::aarch64: 1425 case Triple::aarch64_be: 1426 case Triple::ppc64: 1427 case Triple::ppc64le: 1428 case Triple::systemz: 1429 Result = sizeof(uint64_t); 1430 break; 1431 case Triple::x86: 1432 case Triple::arm: 1433 case Triple::thumb: 1434 case Triple::mips: 1435 case Triple::mipsel: 1436 Result = sizeof(uint32_t); 1437 break; 1438 default: 1439 llvm_unreachable("Unsupported CPU type!"); 1440 } 1441 return Result; 1442 } 1443 1444 uint64_t RuntimeDyldELF::findGOTEntry(uint64_t LoadAddress, uint64_t Offset) { 1445 1446 const size_t GOTEntrySize = getGOTEntrySize(); 1447 1448 SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator it; 1449 SmallVectorImpl<std::pair<SID, GOTRelocations>>::const_iterator end = 1450 GOTs.end(); 1451 1452 int GOTIndex = -1; 1453 for (it = GOTs.begin(); it != end; ++it) { 1454 SID GOTSectionID = it->first; 1455 const GOTRelocations &GOTEntries = it->second; 1456 1457 // Find the matching entry in our vector. 1458 uint64_t SymbolOffset = 0; 1459 for (int i = 0, e = GOTEntries.size(); i != e; ++i) { 1460 if (!GOTEntries[i].SymbolName) { 1461 if (getSectionLoadAddress(GOTEntries[i].SectionID) == LoadAddress && 1462 GOTEntries[i].Offset == Offset) { 1463 GOTIndex = i; 1464 SymbolOffset = GOTEntries[i].Offset; 1465 break; 1466 } 1467 } else { 1468 // GOT entries for external symbols use the addend as the address when 1469 // the external symbol has been resolved. 1470 if (GOTEntries[i].Offset == LoadAddress) { 1471 GOTIndex = i; 1472 // Don't use the Addend here. The relocation handler will use it. 1473 break; 1474 } 1475 } 1476 } 1477 1478 if (GOTIndex != -1) { 1479 if (GOTEntrySize == sizeof(uint64_t)) { 1480 uint64_t *LocalGOTAddr = (uint64_t *)getSectionAddress(GOTSectionID); 1481 // Fill in this entry with the address of the symbol being referenced. 1482 LocalGOTAddr[GOTIndex] = LoadAddress + SymbolOffset; 1483 } else { 1484 uint32_t *LocalGOTAddr = (uint32_t *)getSectionAddress(GOTSectionID); 1485 // Fill in this entry with the address of the symbol being referenced. 1486 LocalGOTAddr[GOTIndex] = (uint32_t)(LoadAddress + SymbolOffset); 1487 } 1488 1489 // Calculate the load address of this entry 1490 return getSectionLoadAddress(GOTSectionID) + (GOTIndex * GOTEntrySize); 1491 } 1492 } 1493 1494 assert(GOTIndex != -1 && "Unable to find requested GOT entry."); 1495 return 0; 1496 } 1497 1498 void RuntimeDyldELF::finalizeLoad(ObjectImage &ObjImg, 1499 ObjSectionToIDMap &SectionMap) { 1500 // If necessary, allocate the global offset table 1501 if (MemMgr) { 1502 // Allocate the GOT if necessary 1503 size_t numGOTEntries = GOTEntries.size(); 1504 if (numGOTEntries != 0) { 1505 // Allocate memory for the section 1506 unsigned SectionID = Sections.size(); 1507 size_t TotalSize = numGOTEntries * getGOTEntrySize(); 1508 uint8_t *Addr = MemMgr->allocateDataSection(TotalSize, getGOTEntrySize(), 1509 SectionID, ".got", false); 1510 if (!Addr) 1511 report_fatal_error("Unable to allocate memory for GOT!"); 1512 1513 GOTs.push_back(std::make_pair(SectionID, GOTEntries)); 1514 Sections.push_back(SectionEntry(".got", Addr, TotalSize, 0)); 1515 // For now, initialize all GOT entries to zero. We'll fill them in as 1516 // needed when GOT-based relocations are applied. 1517 memset(Addr, 0, TotalSize); 1518 } 1519 } else { 1520 report_fatal_error("Unable to allocate memory for GOT!"); 1521 } 1522 1523 // Look for and record the EH frame section. 1524 ObjSectionToIDMap::iterator i, e; 1525 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) { 1526 const SectionRef &Section = i->first; 1527 StringRef Name; 1528 Section.getName(Name); 1529 if (Name == ".eh_frame") { 1530 UnregisteredEHFrameSections.push_back(i->second); 1531 break; 1532 } 1533 } 1534 } 1535 1536 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const { 1537 if (Buffer->getBufferSize() < strlen(ELF::ElfMagic)) 1538 return false; 1539 return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic, 1540 strlen(ELF::ElfMagic))) == 0; 1541 } 1542 1543 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile *Obj) const { 1544 return Obj->isELF(); 1545 } 1546 1547 } // namespace llvm 1548