LLVM 24.0.0git
RuntimeDyldELF.cpp
Go to the documentation of this file.
1//===-- RuntimeDyldELF.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implementation of ELF support for the MC-JIT runtime dynamic linker.
10//
11//===----------------------------------------------------------------------===//
12
13#include "RuntimeDyldELF.h"
15#include "llvm/ADT/StringRef.h"
20#include "llvm/Support/Endian.h"
24
25using namespace llvm;
26using namespace llvm::object;
27using namespace llvm::support::endian;
28
29#define DEBUG_TYPE "dyld"
30
31static void or32le(void *P, int32_t V) { write32le(P, read32le(P) | V); }
32
33static void or32AArch64Imm(void *L, uint64_t Imm) {
34 or32le(L, (Imm & 0xFFF) << 10);
35}
36
37template <class T> static void write(bool isBE, void *P, T V) {
40}
41
42static void write32AArch64Addr(void *L, uint64_t Imm) {
43 uint32_t ImmLo = (Imm & 0x3) << 29;
44 uint32_t ImmHi = (Imm & 0x1FFFFC) << 3;
45 uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3);
46 write32le(L, (read32le(L) & ~Mask) | ImmLo | ImmHi);
47}
48
49// Return the bits [Start, End] from Val shifted Start bits.
50// For instance, getBits(0xF0, 4, 8) returns 0xF.
51static uint64_t getBits(uint64_t Val, int Start, int End) {
52 uint64_t Mask = ((uint64_t)1 << (End + 1 - Start)) - 1;
53 return (Val >> Start) & Mask;
54}
55
56namespace {
57
58template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> {
60
61 typedef typename ELFT::uint addr_type;
62
63 DyldELFObject(ELFObjectFile<ELFT> &&Obj);
64
65public:
66 static Expected<std::unique_ptr<DyldELFObject>>
67 create(MemoryBufferRef Wrapper);
68
69 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
70
71 void updateSymbolAddress(const SymbolRef &SymRef, uint64_t Addr);
72
73 // Methods for type inquiry through isa, cast and dyn_cast
74 static bool classof(const Binary *v) {
75 return (isa<ELFObjectFile<ELFT>>(v) &&
76 classof(cast<ELFObjectFile<ELFT>>(v)));
77 }
78 static bool classof(const ELFObjectFile<ELFT> *v) {
79 return v->isDyldType();
80 }
81};
82
83
84
85// The MemoryBuffer passed into this constructor is just a wrapper around the
86// actual memory. Ultimately, the Binary parent class will take ownership of
87// this MemoryBuffer object but not the underlying memory.
88template <class ELFT>
89DyldELFObject<ELFT>::DyldELFObject(ELFObjectFile<ELFT> &&Obj)
90 : ELFObjectFile<ELFT>(std::move(Obj)) {
91 this->isDyldELFObject = true;
92}
93
94template <class ELFT>
96DyldELFObject<ELFT>::create(MemoryBufferRef Wrapper) {
98 if (auto E = Obj.takeError())
99 return std::move(E);
100 std::unique_ptr<DyldELFObject<ELFT>> Ret(
101 new DyldELFObject<ELFT>(std::move(*Obj)));
102 return std::move(Ret);
103}
104
105template <class ELFT>
106void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
107 uint64_t Addr) {
108 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
109 Elf_Shdr *shdr =
110 const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
111
112 // This assumes the address passed in matches the target address bitness
113 // The template-based type cast handles everything else.
114 shdr->sh_addr = static_cast<addr_type>(Addr);
115}
116
117template <class ELFT>
118void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
119 uint64_t Addr) {
120
121 Elf_Sym *sym = const_cast<Elf_Sym *>(
123
124 // This assumes the address passed in matches the target address bitness
125 // The template-based type cast handles everything else.
126 sym->st_value = static_cast<addr_type>(Addr);
127}
128
129class LoadedELFObjectInfo final
130 : public LoadedObjectInfoHelper<LoadedELFObjectInfo,
131 RuntimeDyld::LoadedObjectInfo> {
132public:
133 LoadedELFObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
134 : LoadedObjectInfoHelper(RTDyld, std::move(ObjSecToIDMap)) {}
135
136 OwningBinary<ObjectFile>
137 getObjectForDebug(const ObjectFile &Obj) const override;
138};
139
140template <typename ELFT>
142createRTDyldELFObject(MemoryBufferRef Buffer, const ObjectFile &SourceObject,
143 const LoadedELFObjectInfo &L) {
144 typedef typename ELFT::Shdr Elf_Shdr;
145 typedef typename ELFT::uint addr_type;
146
148 DyldELFObject<ELFT>::create(Buffer);
149 if (Error E = ObjOrErr.takeError())
150 return std::move(E);
151
152 std::unique_ptr<DyldELFObject<ELFT>> Obj = std::move(*ObjOrErr);
153
154 // Iterate over all sections in the object.
155 auto SI = SourceObject.section_begin();
156 for (const auto &Sec : Obj->sections()) {
157 Expected<StringRef> NameOrErr = Sec.getName();
158 if (!NameOrErr) {
159 consumeError(NameOrErr.takeError());
160 continue;
161 }
162
163 if (*NameOrErr != "") {
164 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
165 Elf_Shdr *shdr = const_cast<Elf_Shdr *>(
166 reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
167
168 if (uint64_t SecLoadAddr = L.getSectionLoadAddress(*SI)) {
169 // This assumes that the address passed in matches the target address
170 // bitness. The template-based type cast handles everything else.
171 shdr->sh_addr = static_cast<addr_type>(SecLoadAddr);
172 }
173 }
174 ++SI;
175 }
176
177 return std::move(Obj);
178}
179
181createELFDebugObject(const ObjectFile &Obj, const LoadedELFObjectInfo &L) {
182 assert(Obj.isELF() && "Not an ELF object file.");
183
184 std::unique_ptr<MemoryBuffer> Buffer =
185 MemoryBuffer::getMemBufferCopy(Obj.getData(), Obj.getFileName());
186
187 Expected<std::unique_ptr<ObjectFile>> DebugObj(nullptr);
188 handleAllErrors(DebugObj.takeError());
189 if (Obj.getBytesInAddress() == 4 && Obj.isLittleEndian())
190 DebugObj =
191 createRTDyldELFObject<ELF32LE>(Buffer->getMemBufferRef(), Obj, L);
192 else if (Obj.getBytesInAddress() == 4 && !Obj.isLittleEndian())
193 DebugObj =
194 createRTDyldELFObject<ELF32BE>(Buffer->getMemBufferRef(), Obj, L);
195 else if (Obj.getBytesInAddress() == 8 && !Obj.isLittleEndian())
196 DebugObj =
197 createRTDyldELFObject<ELF64BE>(Buffer->getMemBufferRef(), Obj, L);
198 else if (Obj.getBytesInAddress() == 8 && Obj.isLittleEndian())
199 DebugObj =
200 createRTDyldELFObject<ELF64LE>(Buffer->getMemBufferRef(), Obj, L);
201 else
202 llvm_unreachable("Unexpected ELF format");
203
204 handleAllErrors(DebugObj.takeError());
205 return OwningBinary<ObjectFile>(std::move(*DebugObj), std::move(Buffer));
206}
207
209LoadedELFObjectInfo::getObjectForDebug(const ObjectFile &Obj) const {
210 return createELFDebugObject(Obj, *this);
211}
212
213} // anonymous namespace
214
215namespace llvm {
216
221
223 for (SID EHFrameSID : UnregisteredEHFrameSections) {
224 uint8_t *EHFrameAddr = Sections[EHFrameSID].getAddress();
225 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].getLoadAddress();
226 size_t EHFrameSize = Sections[EHFrameSID].getSize();
227 MemMgr.registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
228 }
229 UnregisteredEHFrameSections.clear();
230}
231
232std::unique_ptr<RuntimeDyldELF>
236 switch (Arch) {
237 default:
238 return std::make_unique<RuntimeDyldELF>(MemMgr, Resolver);
239 case Triple::mips:
240 case Triple::mipsel:
241 case Triple::mips64:
242 case Triple::mips64el:
243 return std::make_unique<RuntimeDyldELFMips>(MemMgr, Resolver);
244 }
245}
246
247std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
249 if (auto ObjSectionToIDOrErr = loadObjectImpl(O))
250 return std::make_unique<LoadedELFObjectInfo>(*this, *ObjSectionToIDOrErr);
251 else {
252 HasError = true;
253 raw_string_ostream ErrStream(ErrorStr);
254 logAllUnhandledErrors(ObjSectionToIDOrErr.takeError(), ErrStream);
255 return nullptr;
256 }
257}
258
259void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
260 uint64_t Offset, uint64_t Value,
261 uint32_t Type, int64_t Addend,
262 uint64_t SymOffset) {
263 switch (Type) {
264 default:
265 report_fatal_error("Relocation type not implemented yet!");
266 break;
267 case ELF::R_X86_64_NONE:
268 break;
269 case ELF::R_X86_64_8: {
270 Value += Addend;
271 assert((int64_t)Value <= INT8_MAX && (int64_t)Value >= INT8_MIN);
272 uint8_t TruncatedAddr = (Value & 0xFF);
273 *Section.getAddressWithOffset(Offset) = TruncatedAddr;
274 LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
275 << format("%p\n", Section.getAddressWithOffset(Offset)));
276 break;
277 }
278 case ELF::R_X86_64_16: {
279 Value += Addend;
280 assert((int64_t)Value <= INT16_MAX && (int64_t)Value >= INT16_MIN);
281 uint16_t TruncatedAddr = (Value & 0xFFFF);
282 support::ulittle16_t::ref(Section.getAddressWithOffset(Offset)) =
283 TruncatedAddr;
284 LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
285 << format("%p\n", Section.getAddressWithOffset(Offset)));
286 break;
287 }
288 case ELF::R_X86_64_64: {
289 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
290 Value + Addend;
291 LLVM_DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
292 << format("%p\n", Section.getAddressWithOffset(Offset)));
293 break;
294 }
295 case ELF::R_X86_64_32:
296 case ELF::R_X86_64_32S: {
297 Value += Addend;
298 assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
299 (Type == ELF::R_X86_64_32S &&
300 ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
301 uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
302 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
303 TruncatedAddr;
304 LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
305 << format("%p\n", Section.getAddressWithOffset(Offset)));
306 break;
307 }
308 case ELF::R_X86_64_PC8: {
309 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
310 int64_t RealOffset = Value + Addend - FinalAddress;
311 assert(isInt<8>(RealOffset));
312 int8_t TruncOffset = (RealOffset & 0xFF);
313 Section.getAddress()[Offset] = TruncOffset;
314 break;
315 }
316 case ELF::R_X86_64_PC32: {
317 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
318 int64_t RealOffset = Value + Addend - FinalAddress;
319 assert(isInt<32>(RealOffset));
320 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
321 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
322 TruncOffset;
323 break;
324 }
325 case ELF::R_X86_64_PC64: {
326 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
327 int64_t RealOffset = Value + Addend - FinalAddress;
328 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
329 RealOffset;
330 LLVM_DEBUG(dbgs() << "Writing " << format("%p", RealOffset) << " at "
331 << format("%p\n", FinalAddress));
332 break;
333 }
334 case ELF::R_X86_64_GOTOFF64: {
335 // Compute Value - GOTBase.
336 uint64_t GOTBase = 0;
337 for (const auto &Section : Sections) {
338 if (Section.getName() == ".got") {
339 GOTBase = Section.getLoadAddressWithOffset(0);
340 break;
341 }
342 }
343 assert(GOTBase != 0 && "missing GOT");
344 int64_t GOTOffset = Value - GOTBase + Addend;
345 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) = GOTOffset;
346 break;
347 }
348 case ELF::R_X86_64_DTPMOD64: {
349 // We only have one DSO, so the module id is always 1.
350 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) = 1;
351 break;
352 }
353 case ELF::R_X86_64_DTPOFF64:
354 case ELF::R_X86_64_TPOFF64: {
355 // DTPOFF64 should resolve to the offset in the TLS block, TPOFF64 to the
356 // offset in the *initial* TLS block. Since we are statically linking, all
357 // TLS blocks already exist in the initial block, so resolve both
358 // relocations equally.
359 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
360 Value + Addend;
361 break;
362 }
363 case ELF::R_X86_64_DTPOFF32:
364 case ELF::R_X86_64_TPOFF32: {
365 // As for the (D)TPOFF64 relocations above, both DTPOFF32 and TPOFF32 can
366 // be resolved equally.
367 int64_t RealValue = Value + Addend;
368 assert(RealValue >= INT32_MIN && RealValue <= INT32_MAX);
369 int32_t TruncValue = RealValue;
370 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
371 TruncValue;
372 break;
373 }
374 }
375}
376
377void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
378 uint64_t Offset, uint32_t Value,
379 uint32_t Type, int32_t Addend) {
380 switch (Type) {
381 case ELF::R_386_32: {
382 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
383 Value + Addend;
384 break;
385 }
386 // Handle R_386_PLT32 like R_386_PC32 since it should be able to
387 // reach any 32 bit address.
388 case ELF::R_386_PLT32:
389 case ELF::R_386_PC32: {
390 uint32_t FinalAddress =
391 Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
392 uint32_t RealOffset = Value + Addend - FinalAddress;
393 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
394 RealOffset;
395 break;
396 }
397 default:
398 // There are other relocation types, but it appears these are the
399 // only ones currently used by the LLVM ELF object writer
400 report_fatal_error("Relocation type not implemented yet!");
401 break;
402 }
403}
404
405void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
407 uint32_t Type, int64_t Addend) {
408 uint32_t *TargetPtr =
409 reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
410 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
411 // Data should use target endian. Code should always use little endian.
412 bool isBE = Arch == Triple::aarch64_be;
413
414 LLVM_DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
415 << format("%llx", Section.getAddressWithOffset(Offset))
416 << " FinalAddress: 0x" << format("%llx", FinalAddress)
417 << " Value: 0x" << format("%llx", Value) << " Type: 0x"
418 << format("%x", Type) << " Addend: 0x"
419 << format("%llx", Addend) << "\n");
420
421 switch (Type) {
422 default:
423 report_fatal_error("Relocation type not implemented yet!");
424 break;
425 case ELF::R_AARCH64_NONE:
426 break;
427 case ELF::R_AARCH64_ABS16: {
428 uint64_t Result = Value + Addend;
429 assert(Result == static_cast<uint64_t>(llvm::SignExtend64(Result, 16)) ||
430 (Result >> 16) == 0);
431 write(isBE, TargetPtr, static_cast<uint16_t>(Result & 0xffffU));
432 break;
433 }
434 case ELF::R_AARCH64_ABS32: {
435 uint64_t Result = Value + Addend;
436 assert(Result == static_cast<uint64_t>(llvm::SignExtend64(Result, 32)) ||
437 (Result >> 32) == 0);
438 write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
439 break;
440 }
441 case ELF::R_AARCH64_ABS64:
442 write(isBE, TargetPtr, Value + Addend);
443 break;
444 case ELF::R_AARCH64_PLT32: {
445 uint64_t Result = Value + Addend - FinalAddress;
446 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
447 static_cast<int64_t>(Result) <= INT32_MAX);
448 write(isBE, TargetPtr, static_cast<uint32_t>(Result));
449 break;
450 }
451 case ELF::R_AARCH64_PREL16: {
452 uint64_t Result = Value + Addend - FinalAddress;
453 assert(static_cast<int64_t>(Result) >= INT16_MIN &&
454 static_cast<int64_t>(Result) <= UINT16_MAX);
455 write(isBE, TargetPtr, static_cast<uint16_t>(Result & 0xffffU));
456 break;
457 }
458 case ELF::R_AARCH64_PREL32: {
459 uint64_t Result = Value + Addend - FinalAddress;
460 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
461 static_cast<int64_t>(Result) <= UINT32_MAX);
462 write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
463 break;
464 }
465 case ELF::R_AARCH64_PREL64:
466 write(isBE, TargetPtr, Value + Addend - FinalAddress);
467 break;
468 case ELF::R_AARCH64_CONDBR19: {
469 uint64_t BranchImm = Value + Addend - FinalAddress;
470
471 assert(isInt<21>(BranchImm));
472 *TargetPtr &= 0xff00001fU;
473 // Immediate:20:2 goes in bits 23:5 of Bcc, CBZ, CBNZ
474 or32le(TargetPtr, (BranchImm & 0x001FFFFC) << 3);
475 break;
476 }
477 case ELF::R_AARCH64_TSTBR14: {
478 uint64_t BranchImm = Value + Addend - FinalAddress;
479
480 assert(isInt<16>(BranchImm));
481
482 uint32_t RawInstr = *(support::little32_t *)TargetPtr;
483 *(support::little32_t *)TargetPtr = RawInstr & 0xfff8001fU;
484
485 // Immediate:15:2 goes in bits 18:5 of TBZ, TBNZ
486 or32le(TargetPtr, (BranchImm & 0x0000FFFC) << 3);
487 break;
488 }
489 case ELF::R_AARCH64_CALL26: // fallthrough
490 case ELF::R_AARCH64_JUMP26: {
491 // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
492 // calculation.
493 uint64_t BranchImm = Value + Addend - FinalAddress;
494
495 // "Check that -2^27 <= result < 2^27".
496 assert(isInt<28>(BranchImm));
497 or32le(TargetPtr, (BranchImm & 0x0FFFFFFC) >> 2);
498 break;
499 }
500 case ELF::R_AARCH64_MOVW_UABS_G3:
501 or32le(TargetPtr, ((Value + Addend) & 0xFFFF000000000000) >> 43);
502 break;
503 case ELF::R_AARCH64_MOVW_UABS_G2_NC:
504 or32le(TargetPtr, ((Value + Addend) & 0xFFFF00000000) >> 27);
505 break;
506 case ELF::R_AARCH64_MOVW_UABS_G1_NC:
507 or32le(TargetPtr, ((Value + Addend) & 0xFFFF0000) >> 11);
508 break;
509 case ELF::R_AARCH64_MOVW_UABS_G0_NC:
510 or32le(TargetPtr, ((Value + Addend) & 0xFFFF) << 5);
511 break;
512 case ELF::R_AARCH64_ADR_PREL_PG_HI21: {
513 // Operation: Page(S+A) - Page(P)
515 ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL);
516
517 // Check that -2^32 <= X < 2^32
518 assert(isInt<33>(Result) && "overflow check failed for relocation");
519
520 // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken
521 // from bits 32:12 of X.
522 write32AArch64Addr(TargetPtr, Result >> 12);
523 break;
524 }
525 case ELF::R_AARCH64_ADD_ABS_LO12_NC:
526 // Operation: S + A
527 // Immediate goes in bits 21:10 of LD/ST instruction, taken
528 // from bits 11:0 of X
529 or32AArch64Imm(TargetPtr, Value + Addend);
530 break;
531 case ELF::R_AARCH64_LDST8_ABS_LO12_NC:
532 // Operation: S + A
533 // Immediate goes in bits 21:10 of LD/ST instruction, taken
534 // from bits 11:0 of X
535 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 0, 11));
536 break;
537 case ELF::R_AARCH64_LDST16_ABS_LO12_NC:
538 // Operation: S + A
539 // Immediate goes in bits 21:10 of LD/ST instruction, taken
540 // from bits 11:1 of X
541 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 1, 11));
542 break;
543 case ELF::R_AARCH64_LDST32_ABS_LO12_NC:
544 // Operation: S + A
545 // Immediate goes in bits 21:10 of LD/ST instruction, taken
546 // from bits 11:2 of X
547 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 2, 11));
548 break;
549 case ELF::R_AARCH64_LDST64_ABS_LO12_NC:
550 // Operation: S + A
551 // Immediate goes in bits 21:10 of LD/ST instruction, taken
552 // from bits 11:3 of X
553 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 3, 11));
554 break;
555 case ELF::R_AARCH64_LDST128_ABS_LO12_NC:
556 // Operation: S + A
557 // Immediate goes in bits 21:10 of LD/ST instruction, taken
558 // from bits 11:4 of X
559 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 4, 11));
560 break;
561 case ELF::R_AARCH64_LD_PREL_LO19: {
562 // Operation: S + A - P
563 uint64_t Result = Value + Addend - FinalAddress;
564
565 // "Check that -2^20 <= result < 2^20".
566 assert(isInt<21>(Result));
567
568 *TargetPtr &= 0xff00001fU;
569 // Immediate goes in bits 23:5 of LD imm instruction, taken
570 // from bits 20:2 of X
571 *TargetPtr |= ((Result & 0xffc) << (5 - 2));
572 break;
573 }
574 case ELF::R_AARCH64_ADR_PREL_LO21: {
575 // Operation: S + A - P
576 uint64_t Result = Value + Addend - FinalAddress;
577
578 // "Check that -2^20 <= result < 2^20".
579 assert(isInt<21>(Result));
580
581 *TargetPtr &= 0x9f00001fU;
582 // Immediate goes in bits 23:5, 30:29 of ADR imm instruction, taken
583 // from bits 20:0 of X
584 *TargetPtr |= ((Result & 0xffc) << (5 - 2));
585 *TargetPtr |= (Result & 0x3) << 29;
586 break;
587 }
588 }
589}
590
591void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
592 uint64_t Offset, uint32_t Value,
593 uint32_t Type, int32_t Addend) {
594 // TODO: Add Thumb relocations.
595 uint32_t *TargetPtr =
596 reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
597 uint32_t FinalAddress = Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
598 Value += Addend;
599
600 LLVM_DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
601 << Section.getAddressWithOffset(Offset)
602 << " FinalAddress: " << format("%p", FinalAddress)
603 << " Value: " << format("%x", Value)
604 << " Type: " << format("%x", Type)
605 << " Addend: " << format("%x", Addend) << "\n");
606
607 switch (Type) {
608 default:
609 llvm_unreachable("Not implemented relocation type!");
610
611 case ELF::R_ARM_NONE:
612 break;
613 // Write a 31bit signed offset
614 case ELF::R_ARM_PREL31:
615 support::ulittle32_t::ref{TargetPtr} =
616 (support::ulittle32_t::ref{TargetPtr} & 0x80000000) |
617 ((Value - FinalAddress) & ~0x80000000);
618 break;
619 case ELF::R_ARM_TARGET1:
620 case ELF::R_ARM_ABS32:
621 support::ulittle32_t::ref{TargetPtr} = Value;
622 break;
623 // Write first 16 bit of 32 bit value to the mov instruction.
624 // Last 4 bit should be shifted.
625 case ELF::R_ARM_MOVW_ABS_NC:
626 case ELF::R_ARM_MOVT_ABS:
627 if (Type == ELF::R_ARM_MOVW_ABS_NC)
628 Value = Value & 0xFFFF;
629 else if (Type == ELF::R_ARM_MOVT_ABS)
630 Value = (Value >> 16) & 0xFFFF;
631 support::ulittle32_t::ref{TargetPtr} =
632 (support::ulittle32_t::ref{TargetPtr} & ~0x000F0FFF) | (Value & 0xFFF) |
633 (((Value >> 12) & 0xF) << 16);
634 break;
635 // Write 24 bit relative value to the branch instruction.
636 case ELF::R_ARM_PC24: // Fall through.
637 case ELF::R_ARM_CALL: // Fall through.
638 case ELF::R_ARM_JUMP24:
639 int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
640 RelValue = (RelValue & 0x03FFFFFC) >> 2;
641 assert((support::ulittle32_t::ref{TargetPtr} & 0xFFFFFF) == 0xFFFFFE);
642 support::ulittle32_t::ref{TargetPtr} =
643 (support::ulittle32_t::ref{TargetPtr} & 0xFF000000) | RelValue;
644 break;
645 }
646}
647
648bool RuntimeDyldELF::resolveLoongArch64ShortBranch(
649 unsigned SectionID, relocation_iterator RelI,
650 const RelocationValueRef &Value) {
652 if (Value.SymbolName) {
653 auto Loc = GlobalSymbolTable.find(Value.SymbolName);
654 // Don't create direct branch for external symbols.
655 if (Loc == GlobalSymbolTable.end())
656 return false;
657 const auto &SymInfo = Loc->second;
658 Address = Sections[SymInfo.getSectionID()].getLoadAddressWithOffset(
659 SymInfo.getOffset());
660 } else {
661 Address = Sections[Value.SectionID].getLoadAddress();
662 }
663 uint64_t Offset = RelI->getOffset();
664 uint64_t SourceAddress = Sections[SectionID].getLoadAddressWithOffset(Offset);
665 uint64_t Delta = Address + Value.Addend - SourceAddress;
666 // Normal call
667 if (RelI->getType() == ELF::R_LARCH_B26) {
668 if (!isInt<28>(Delta))
669 return false;
670 resolveRelocation(Sections[SectionID], Offset, Address, RelI->getType(),
671 Value.Addend);
672 return true;
673 }
674 // Medium call: R_LARCH_CALL36
675 // Range: [-128G - 0x20000, +128G - 0x20000)
676 if (((int64_t)Delta + 0x20000) != llvm::SignExtend64(Delta + 0x20000, 38))
677 return false;
678 resolveRelocation(Sections[SectionID], Offset, Address, RelI->getType(),
679 Value.Addend);
680 return true;
681}
682
683void RuntimeDyldELF::resolveLoongArch64Branch(unsigned SectionID,
686 StubMap &Stubs) {
687 LLVM_DEBUG(dbgs() << "\t\tThis is an LoongArch64 branch relocation.\n");
688
689 if (resolveLoongArch64ShortBranch(SectionID, RelI, Value))
690 return;
691
692 SectionEntry &Section = Sections[SectionID];
693 uint64_t Offset = RelI->getOffset();
694 unsigned RelType = RelI->getType();
695 // Look for an existing stub.
696 auto [It, Inserted] = Stubs.try_emplace(Value);
697 if (!Inserted) {
698 resolveRelocation(Section, Offset,
699 (uint64_t)Section.getAddressWithOffset(It->second),
700 RelType, 0);
701 LLVM_DEBUG(dbgs() << " Stub function found\n");
702 return;
703 }
704 // Create a new stub function.
705 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
706 It->second = Section.getStubOffset();
707 uint8_t *StubTargetAddr =
708 createStubFunction(Section.getAddressWithOffset(Section.getStubOffset()));
709 RelocationEntry LU12I_W(SectionID, StubTargetAddr - Section.getAddress(),
710 ELF::R_LARCH_ABS_HI20, Value.Addend);
711 RelocationEntry ORI(SectionID, StubTargetAddr - Section.getAddress() + 4,
712 ELF::R_LARCH_ABS_LO12, Value.Addend);
713 RelocationEntry LU32I_D(SectionID, StubTargetAddr - Section.getAddress() + 8,
714 ELF::R_LARCH_ABS64_LO20, Value.Addend);
715 RelocationEntry LU52I_D(SectionID, StubTargetAddr - Section.getAddress() + 12,
716 ELF::R_LARCH_ABS64_HI12, Value.Addend);
717 if (Value.SymbolName) {
718 addRelocationForSymbol(LU12I_W, Value.SymbolName);
719 addRelocationForSymbol(ORI, Value.SymbolName);
720 addRelocationForSymbol(LU32I_D, Value.SymbolName);
721 addRelocationForSymbol(LU52I_D, Value.SymbolName);
722 } else {
723 addRelocationForSection(LU12I_W, Value.SectionID);
724 addRelocationForSection(ORI, Value.SectionID);
725 addRelocationForSection(LU32I_D, Value.SectionID);
726
727 addRelocationForSection(LU52I_D, Value.SectionID);
728 }
729 resolveRelocation(Section, Offset,
730 reinterpret_cast<uint64_t>(
731 Section.getAddressWithOffset(Section.getStubOffset())),
732 RelType, 0);
733 Section.advanceStubOffset(getMaxStubSize());
734}
735
736// Returns extract bits Val[Hi:Lo].
737static inline uint32_t extractBits(uint64_t Val, uint32_t Hi, uint32_t Lo) {
738 return Hi == 63 ? Val >> Lo : (Val & (((1ULL << (Hi + 1)) - 1))) >> Lo;
739}
740
741// Calculate the adjusted page delta between dest and PC. The code is copied
742// from lld and see comments there for more details.
743static uint64_t getLoongArchPageDelta(uint64_t dest, uint64_t pc,
744 uint32_t type) {
745 uint64_t pcalau12i_pc;
746 switch (type) {
747 case ELF::R_LARCH_PCALA64_LO20:
748 case ELF::R_LARCH_GOT64_PC_LO20:
749 pcalau12i_pc = pc - 8;
750 break;
751 case ELF::R_LARCH_PCALA64_HI12:
752 case ELF::R_LARCH_GOT64_PC_HI12:
753 pcalau12i_pc = pc - 12;
754 break;
755 default:
756 pcalau12i_pc = pc;
757 break;
758 }
759 uint64_t result = (dest & ~0xfffULL) - (pcalau12i_pc & ~0xfffULL);
760 if (dest & 0x800)
761 result += 0x1000 - 0x1'0000'0000;
762 if (result & 0x8000'0000)
763 result += 0x1'0000'0000;
764 return result;
765}
766
767void RuntimeDyldELF::resolveLoongArch64Relocation(const SectionEntry &Section,
770 int64_t Addend) {
771 auto *TargetPtr = Section.getAddressWithOffset(Offset);
772 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
773
774 LLVM_DEBUG(dbgs() << "resolveLoongArch64Relocation, LocalAddress: 0x"
775 << format("%llx", Section.getAddressWithOffset(Offset))
776 << " FinalAddress: 0x" << format("%llx", FinalAddress)
777 << " Value: 0x" << format("%llx", Value) << " Type: 0x"
778 << format("%x", Type) << " Addend: 0x"
779 << format("%llx", Addend) << "\n");
780
781 switch (Type) {
782 default:
783 report_fatal_error("Relocation type not implemented yet!");
784 break;
785 case ELF::R_LARCH_MARK_LA:
786 // ignore
787 break;
788 case ELF::R_LARCH_32:
789 support::ulittle32_t::ref{TargetPtr} =
790 static_cast<uint32_t>(Value + Addend);
791 break;
792 case ELF::R_LARCH_64:
793 support::ulittle64_t::ref{TargetPtr} = Value + Addend;
794 break;
795 case ELF::R_LARCH_32_PCREL:
796 support::ulittle32_t::ref{TargetPtr} =
797 static_cast<uint32_t>(Value + Addend - FinalAddress);
798 break;
799 case ELF::R_LARCH_B26: {
800 uint64_t B26 = (Value + Addend - FinalAddress) >> 2;
801 auto Instr = support::ulittle32_t::ref(TargetPtr);
802 uint32_t Imm15_0 = extractBits(B26, /*Hi=*/15, /*Lo=*/0) << 10;
803 uint32_t Imm25_16 = extractBits(B26, /*Hi=*/25, /*Lo=*/16);
804 Instr = (Instr & 0xfc000000) | Imm15_0 | Imm25_16;
805 break;
806 }
807 case ELF::R_LARCH_CALL36: {
808 uint64_t Call36 = (Value + Addend - FinalAddress) >> 2;
809 auto Pcaddu18i = support::ulittle32_t::ref(TargetPtr);
810 uint32_t Imm35_16 =
811 extractBits((Call36 + (1UL << 15)), /*Hi=*/35, /*Lo=*/16) << 5;
812 Pcaddu18i = (Pcaddu18i & 0xfe00001f) | Imm35_16;
813 auto Jirl = support::ulittle32_t::ref(TargetPtr + 4);
814 uint32_t Imm15_0 = extractBits(Call36, /*Hi=*/15, /*Lo=*/0) << 10;
815 Jirl = (Jirl & 0xfc0003ff) | Imm15_0;
816 break;
817 }
818 case ELF::R_LARCH_GOT_PC_HI20:
819 case ELF::R_LARCH_PCALA_HI20: {
820 uint64_t Target = Value + Addend;
821 int64_t PageDelta = getLoongArchPageDelta(Target, FinalAddress, Type);
822 auto Instr = support::ulittle32_t::ref(TargetPtr);
823 uint32_t Imm31_12 = extractBits(PageDelta, /*Hi=*/31, /*Lo=*/12) << 5;
824 Instr = (Instr & 0xfe00001f) | Imm31_12;
825 break;
826 }
827 case ELF::R_LARCH_GOT_PC_LO12:
828 case ELF::R_LARCH_PCALA_LO12: {
829 uint64_t TargetOffset = (Value + Addend) & 0xfff;
830 auto Instr = support::ulittle32_t::ref(TargetPtr);
831 uint32_t Imm11_0 = TargetOffset << 10;
832 Instr = (Instr & 0xffc003ff) | Imm11_0;
833 break;
834 }
835 case ELF::R_LARCH_GOT64_PC_LO20:
836 case ELF::R_LARCH_PCALA64_LO20: {
837 uint64_t Target = Value + Addend;
838 int64_t PageDelta = getLoongArchPageDelta(Target, FinalAddress, Type);
839 auto Instr = support::ulittle32_t::ref(TargetPtr);
840 uint32_t Imm51_32 = extractBits(PageDelta, /*Hi=*/51, /*Lo=*/32) << 5;
841 Instr = (Instr & 0xfe00001f) | Imm51_32;
842 break;
843 }
844 case ELF::R_LARCH_GOT64_PC_HI12:
845 case ELF::R_LARCH_PCALA64_HI12: {
846 uint64_t Target = Value + Addend;
847 int64_t PageDelta = getLoongArchPageDelta(Target, FinalAddress, Type);
848 auto Instr = support::ulittle32_t::ref(TargetPtr);
849 uint32_t Imm63_52 = extractBits(PageDelta, /*Hi=*/63, /*Lo=*/52) << 10;
850 Instr = (Instr & 0xffc003ff) | Imm63_52;
851 break;
852 }
853 case ELF::R_LARCH_ABS_HI20: {
854 uint64_t Target = Value + Addend;
855 auto Instr = support::ulittle32_t::ref(TargetPtr);
856 uint32_t Imm31_12 = extractBits(Target, /*Hi=*/31, /*Lo=*/12) << 5;
857 Instr = (Instr & 0xfe00001f) | Imm31_12;
858 break;
859 }
860 case ELF::R_LARCH_ABS_LO12: {
861 uint64_t Target = Value + Addend;
862 auto Instr = support::ulittle32_t::ref(TargetPtr);
863 uint32_t Imm11_0 = extractBits(Target, /*Hi=*/11, /*Lo=*/0) << 10;
864 Instr = (Instr & 0xffc003ff) | Imm11_0;
865 break;
866 }
867 case ELF::R_LARCH_ABS64_LO20: {
868 uint64_t Target = Value + Addend;
869 auto Instr = support::ulittle32_t::ref(TargetPtr);
870 uint32_t Imm51_32 = extractBits(Target, /*Hi=*/51, /*Lo=*/32) << 5;
871 Instr = (Instr & 0xfe00001f) | Imm51_32;
872 break;
873 }
874 case ELF::R_LARCH_ABS64_HI12: {
875 uint64_t Target = Value + Addend;
876 auto Instr = support::ulittle32_t::ref(TargetPtr);
877 uint32_t Imm63_52 = extractBits(Target, /*Hi=*/63, /*Lo=*/52) << 10;
878 Instr = (Instr & 0xffc003ff) | Imm63_52;
879 break;
880 }
881 case ELF::R_LARCH_ADD32:
882 support::ulittle32_t::ref{TargetPtr} =
883 (support::ulittle32_t::ref{TargetPtr} +
884 static_cast<uint32_t>(Value + Addend));
885 break;
886 case ELF::R_LARCH_SUB32:
887 support::ulittle32_t::ref{TargetPtr} =
888 (support::ulittle32_t::ref{TargetPtr} -
889 static_cast<uint32_t>(Value + Addend));
890 break;
891 case ELF::R_LARCH_ADD64:
892 support::ulittle64_t::ref{TargetPtr} =
893 (support::ulittle64_t::ref{TargetPtr} + Value + Addend);
894 break;
895 case ELF::R_LARCH_SUB64:
896 support::ulittle64_t::ref{TargetPtr} =
897 (support::ulittle64_t::ref{TargetPtr} - Value - Addend);
898 break;
899 }
900}
901
902void RuntimeDyldELF::setMipsABI(const ObjectFile &Obj) {
903 if (Arch == Triple::UnknownArch ||
904 Triple::getArchTypePrefix(Arch) != "mips") {
905 IsMipsO32ABI = false;
906 IsMipsN32ABI = false;
907 IsMipsN64ABI = false;
908 return;
909 }
910 if (auto *E = dyn_cast<ELFObjectFileBase>(&Obj)) {
911 unsigned AbiVariant = E->getPlatformFlags();
912 IsMipsO32ABI = AbiVariant & ELF::EF_MIPS_ABI_O32;
913 IsMipsN32ABI = AbiVariant & ELF::EF_MIPS_ABI2;
914 }
915 IsMipsN64ABI = Obj.getFileFormatName() == "elf64-mips";
916}
917
918// Return the .TOC. section and offset.
919Error RuntimeDyldELF::findPPC64TOCSection(const ELFObjectFileBase &Obj,
920 ObjSectionToIDMap &LocalSections,
921 RelocationValueRef &Rel) {
922 // Set a default SectionID in case we do not find a TOC section below.
923 // This may happen for references to TOC base base (sym@toc, .odp
924 // relocation) without a .toc directive. In this case just use the
925 // first section (which is usually the .odp) since the code won't
926 // reference the .toc base directly.
927 Rel.SymbolName = nullptr;
928 Rel.SectionID = 0;
929
930 // The TOC consists of sections .got, .toc, .tocbss, .plt in that
931 // order. The TOC starts where the first of these sections starts.
932 for (auto &Section : Obj.sections()) {
933 Expected<StringRef> NameOrErr = Section.getName();
934 if (!NameOrErr)
935 return NameOrErr.takeError();
936 StringRef SectionName = *NameOrErr;
937
938 if (SectionName == ".got"
939 || SectionName == ".toc"
940 || SectionName == ".tocbss"
941 || SectionName == ".plt") {
942 if (auto SectionIDOrErr =
943 findOrEmitSection(Obj, Section, false, LocalSections))
944 Rel.SectionID = *SectionIDOrErr;
945 else
946 return SectionIDOrErr.takeError();
947 break;
948 }
949 }
950
951 // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
952 // thus permitting a full 64 Kbytes segment.
953 Rel.Addend = 0x8000;
954
955 return Error::success();
956}
957
958// Returns the sections and offset associated with the ODP entry referenced
959// by Symbol.
960Error RuntimeDyldELF::findOPDEntrySection(const ELFObjectFileBase &Obj,
961 ObjSectionToIDMap &LocalSections,
962 RelocationValueRef &Rel) {
963 // Get the ELF symbol value (st_value) to compare with Relocation offset in
964 // .opd entries
965 for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
966 si != se; ++si) {
967
968 Expected<section_iterator> RelSecOrErr = si->getRelocatedSection();
969 if (!RelSecOrErr)
970 report_fatal_error(Twine(toString(RelSecOrErr.takeError())));
971
972 section_iterator RelSecI = *RelSecOrErr;
973 if (RelSecI == Obj.section_end())
974 continue;
975
976 Expected<StringRef> NameOrErr = RelSecI->getName();
977 if (!NameOrErr)
978 return NameOrErr.takeError();
979 StringRef RelSectionName = *NameOrErr;
980
981 if (RelSectionName != ".opd")
982 continue;
983
984 for (elf_relocation_iterator i = si->relocation_begin(),
985 e = si->relocation_end();
986 i != e;) {
987 // The R_PPC64_ADDR64 relocation indicates the first field
988 // of a .opd entry
989 uint64_t TypeFunc = i->getType();
990 if (TypeFunc != ELF::R_PPC64_ADDR64) {
991 ++i;
992 continue;
993 }
994
995 uint64_t TargetSymbolOffset = i->getOffset();
996 symbol_iterator TargetSymbol = i->getSymbol();
997 int64_t Addend;
998 if (auto AddendOrErr = i->getAddend())
999 Addend = *AddendOrErr;
1000 else
1001 return AddendOrErr.takeError();
1002
1003 ++i;
1004 if (i == e)
1005 break;
1006
1007 // Just check if following relocation is a R_PPC64_TOC
1008 uint64_t TypeTOC = i->getType();
1009 if (TypeTOC != ELF::R_PPC64_TOC)
1010 continue;
1011
1012 // Finally compares the Symbol value and the target symbol offset
1013 // to check if this .opd entry refers to the symbol the relocation
1014 // points to.
1015 if (Rel.Addend != (int64_t)TargetSymbolOffset)
1016 continue;
1017
1018 section_iterator TSI = Obj.section_end();
1019 if (auto TSIOrErr = TargetSymbol->getSection())
1020 TSI = *TSIOrErr;
1021 else
1022 return TSIOrErr.takeError();
1023 assert(TSI != Obj.section_end() && "TSI should refer to a valid section");
1024
1025 bool IsCode = TSI->isText();
1026 if (auto SectionIDOrErr = findOrEmitSection(Obj, *TSI, IsCode,
1027 LocalSections))
1028 Rel.SectionID = *SectionIDOrErr;
1029 else
1030 return SectionIDOrErr.takeError();
1031 Rel.Addend = (intptr_t)Addend;
1032 return Error::success();
1033 }
1034 }
1035 llvm_unreachable("Attempting to get address of ODP entry!");
1036}
1037
1038// Relocation masks following the #lo(value), #hi(value), #ha(value),
1039// #higher(value), #highera(value), #highest(value), and #highesta(value)
1040// macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
1041// document.
1042
1043static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
1044
1045static inline uint16_t applyPPChi(uint64_t value) {
1046 return (value >> 16) & 0xffff;
1047}
1048
1049static inline uint16_t applyPPCha (uint64_t value) {
1050 return ((value + 0x8000) >> 16) & 0xffff;
1051}
1052
1053static inline uint16_t applyPPChigher(uint64_t value) {
1054 return (value >> 32) & 0xffff;
1055}
1056
1057static inline uint16_t applyPPChighera (uint64_t value) {
1058 return ((value + 0x8000) >> 32) & 0xffff;
1059}
1060
1061static inline uint16_t applyPPChighest(uint64_t value) {
1062 return (value >> 48) & 0xffff;
1063}
1064
1065static inline uint16_t applyPPChighesta (uint64_t value) {
1066 return ((value + 0x8000) >> 48) & 0xffff;
1067}
1068
1069void RuntimeDyldELF::resolvePPC32Relocation(const SectionEntry &Section,
1071 uint32_t Type, int64_t Addend) {
1072 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
1073 uint32_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
1074 switch (Type) {
1075 default:
1076 report_fatal_error("Relocation type not implemented yet!");
1077 break;
1078 case ELF::R_PPC_ADDR16_LO:
1079 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
1080 break;
1081 case ELF::R_PPC_ADDR16_HI:
1082 writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
1083 break;
1084 case ELF::R_PPC_ADDR16_HA:
1085 writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
1086 break;
1087 case ELF::R_PPC_ADDR32:
1088 writeInt32BE(LocalAddress, Value + Addend);
1089 break;
1090 case ELF::R_PPC_REL16_LO:
1091 writeInt16BE(LocalAddress, applyPPClo(Value - FinalAddress + Addend));
1092 break;
1093 case ELF::R_PPC_REL16_HA:
1094 writeInt16BE(LocalAddress, applyPPCha(Value - FinalAddress + Addend));
1095 break;
1096 case ELF::R_PPC_REL24: {
1097 int32_t Delta = static_cast<int32_t>(Value - FinalAddress + Addend);
1098 if (SignExtend32<26>(Delta) != Delta)
1099 report_fatal_error("Relocation R_PPC_REL24 overflow");
1100 // Keep the opcode and the AA and LK bits.
1101 uint32_t Inst = readBytesUnaligned(LocalAddress, 4);
1102 writeInt32BE(LocalAddress, (Inst & 0xFC000003) | (Delta & 0x03FFFFFC));
1103 } break;
1104 case ELF::R_PPC_REL32:
1105 writeInt32BE(LocalAddress, Value - FinalAddress + Addend);
1106 break;
1107 }
1108}
1109
1110void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
1112 uint32_t Type, int64_t Addend) {
1113 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
1114 switch (Type) {
1115 default:
1116 report_fatal_error("Relocation type not implemented yet!");
1117 break;
1118 case ELF::R_PPC64_ADDR16:
1119 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
1120 break;
1121 case ELF::R_PPC64_ADDR16_DS:
1122 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
1123 break;
1124 case ELF::R_PPC64_ADDR16_LO:
1125 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
1126 break;
1127 case ELF::R_PPC64_ADDR16_LO_DS:
1128 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
1129 break;
1130 case ELF::R_PPC64_ADDR16_HI:
1131 case ELF::R_PPC64_ADDR16_HIGH:
1132 writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
1133 break;
1134 case ELF::R_PPC64_ADDR16_HA:
1135 case ELF::R_PPC64_ADDR16_HIGHA:
1136 writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
1137 break;
1138 case ELF::R_PPC64_ADDR16_HIGHER:
1139 writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
1140 break;
1141 case ELF::R_PPC64_ADDR16_HIGHERA:
1142 writeInt16BE(LocalAddress, applyPPChighera(Value + Addend));
1143 break;
1144 case ELF::R_PPC64_ADDR16_HIGHEST:
1145 writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
1146 break;
1147 case ELF::R_PPC64_ADDR16_HIGHESTA:
1148 writeInt16BE(LocalAddress, applyPPChighesta(Value + Addend));
1149 break;
1150 case ELF::R_PPC64_ADDR14: {
1151 assert(((Value + Addend) & 3) == 0);
1152 // Preserve the AA/LK bits in the branch instruction
1153 uint8_t aalk = *(LocalAddress + 3);
1154 writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
1155 } break;
1156 case ELF::R_PPC64_REL16_LO: {
1157 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
1158 uint64_t Delta = Value - FinalAddress + Addend;
1159 writeInt16BE(LocalAddress, applyPPClo(Delta));
1160 } break;
1161 case ELF::R_PPC64_REL16_HI: {
1162 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
1163 uint64_t Delta = Value - FinalAddress + Addend;
1164 writeInt16BE(LocalAddress, applyPPChi(Delta));
1165 } break;
1166 case ELF::R_PPC64_REL16_HA: {
1167 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
1168 uint64_t Delta = Value - FinalAddress + Addend;
1169 writeInt16BE(LocalAddress, applyPPCha(Delta));
1170 } break;
1171 case ELF::R_PPC64_ADDR32: {
1172 int64_t Result = static_cast<int64_t>(Value + Addend);
1173 if (SignExtend64<32>(Result) != Result)
1174 llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
1175 writeInt32BE(LocalAddress, Result);
1176 } break;
1177 case ELF::R_PPC64_REL24: {
1178 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
1179 int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
1180 if (SignExtend64<26>(delta) != delta)
1181 llvm_unreachable("Relocation R_PPC64_REL24 overflow");
1182 // We preserve bits other than LI field, i.e. PO and AA/LK fields.
1183 uint32_t Inst = readBytesUnaligned(LocalAddress, 4);
1184 writeInt32BE(LocalAddress, (Inst & 0xFC000003) | (delta & 0x03FFFFFC));
1185 } break;
1186 case ELF::R_PPC64_REL32: {
1187 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
1188 int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
1189 if (SignExtend64<32>(delta) != delta)
1190 llvm_unreachable("Relocation R_PPC64_REL32 overflow");
1191 writeInt32BE(LocalAddress, delta);
1192 } break;
1193 case ELF::R_PPC64_REL64: {
1194 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
1195 uint64_t Delta = Value - FinalAddress + Addend;
1196 writeInt64BE(LocalAddress, Delta);
1197 } break;
1198 case ELF::R_PPC64_ADDR64:
1199 writeInt64BE(LocalAddress, Value + Addend);
1200 break;
1201 }
1202}
1203
1204void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
1206 uint32_t Type, int64_t Addend) {
1207 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
1208 switch (Type) {
1209 default:
1210 report_fatal_error("Relocation type not implemented yet!");
1211 break;
1212 case ELF::R_390_PC16DBL:
1213 case ELF::R_390_PLT16DBL: {
1214 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
1215 assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
1216 writeInt16BE(LocalAddress, Delta / 2);
1217 break;
1218 }
1219 case ELF::R_390_PC32DBL:
1220 case ELF::R_390_PLT32DBL: {
1221 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
1222 assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
1223 writeInt32BE(LocalAddress, Delta / 2);
1224 break;
1225 }
1226 case ELF::R_390_PC16: {
1227 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
1228 assert(int16_t(Delta) == Delta && "R_390_PC16 overflow");
1229 writeInt16BE(LocalAddress, Delta);
1230 break;
1231 }
1232 case ELF::R_390_PC32: {
1233 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
1234 assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
1235 writeInt32BE(LocalAddress, Delta);
1236 break;
1237 }
1238 case ELF::R_390_PC64: {
1239 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
1240 writeInt64BE(LocalAddress, Delta);
1241 break;
1242 }
1243 case ELF::R_390_8:
1244 *LocalAddress = (uint8_t)(Value + Addend);
1245 break;
1246 case ELF::R_390_16:
1247 writeInt16BE(LocalAddress, Value + Addend);
1248 break;
1249 case ELF::R_390_32:
1250 writeInt32BE(LocalAddress, Value + Addend);
1251 break;
1252 case ELF::R_390_64:
1253 writeInt64BE(LocalAddress, Value + Addend);
1254 break;
1255 }
1256}
1257
1258#ifdef HEXAGON_TARGET_ENABLED
1259// Hexagon relocations that need GOT, TLS, GP-relative or dynamic-linker
1260// semantics. RuntimeDyld implements none of these, and resolving them as a
1261// plain S + A would silently produce a wrong value, so they are rejected.
1262static bool isUnsupportedHexagonRelocation(uint32_t Type) {
1263 switch (Type) {
1264 case ELF::R_HEX_GPREL16_0:
1265 case ELF::R_HEX_GPREL16_1:
1266 case ELF::R_HEX_GPREL16_2:
1267 case ELF::R_HEX_GPREL16_3:
1268 case ELF::R_HEX_COPY:
1269 case ELF::R_HEX_GLOB_DAT:
1270 case ELF::R_HEX_JMP_SLOT:
1271 case ELF::R_HEX_RELATIVE:
1272 case ELF::R_HEX_GOTREL_LO16:
1273 case ELF::R_HEX_GOTREL_HI16:
1274 case ELF::R_HEX_GOTREL_32:
1275 case ELF::R_HEX_GOT_LO16:
1276 case ELF::R_HEX_GOT_HI16:
1277 case ELF::R_HEX_GOT_32:
1278 case ELF::R_HEX_GOT_16:
1279 case ELF::R_HEX_DTPMOD_32:
1280 case ELF::R_HEX_DTPREL_LO16:
1281 case ELF::R_HEX_DTPREL_HI16:
1282 case ELF::R_HEX_DTPREL_32:
1283 case ELF::R_HEX_DTPREL_16:
1284 case ELF::R_HEX_GD_PLT_B22_PCREL:
1285 case ELF::R_HEX_GD_GOT_LO16:
1286 case ELF::R_HEX_GD_GOT_HI16:
1287 case ELF::R_HEX_GD_GOT_32:
1288 case ELF::R_HEX_GD_GOT_16:
1289 case ELF::R_HEX_IE_LO16:
1290 case ELF::R_HEX_IE_HI16:
1291 case ELF::R_HEX_IE_32:
1292 case ELF::R_HEX_IE_GOT_LO16:
1293 case ELF::R_HEX_IE_GOT_HI16:
1294 case ELF::R_HEX_IE_GOT_32:
1295 case ELF::R_HEX_IE_GOT_16:
1296 case ELF::R_HEX_TPREL_LO16:
1297 case ELF::R_HEX_TPREL_HI16:
1298 case ELF::R_HEX_TPREL_32:
1299 case ELF::R_HEX_TPREL_16:
1300 case ELF::R_HEX_GOTREL_32_6_X:
1301 case ELF::R_HEX_GOTREL_16_X:
1302 case ELF::R_HEX_GOTREL_11_X:
1303 case ELF::R_HEX_GOT_32_6_X:
1304 case ELF::R_HEX_GOT_16_X:
1305 case ELF::R_HEX_GOT_11_X:
1306 case ELF::R_HEX_DTPREL_32_6_X:
1307 case ELF::R_HEX_DTPREL_16_X:
1308 case ELF::R_HEX_DTPREL_11_X:
1309 case ELF::R_HEX_GD_GOT_32_6_X:
1310 case ELF::R_HEX_GD_GOT_16_X:
1311 case ELF::R_HEX_GD_GOT_11_X:
1312 case ELF::R_HEX_IE_32_6_X:
1313 case ELF::R_HEX_IE_16_X:
1314 case ELF::R_HEX_IE_GOT_32_6_X:
1315 case ELF::R_HEX_IE_GOT_16_X:
1316 case ELF::R_HEX_IE_GOT_11_X:
1317 case ELF::R_HEX_TPREL_32_6_X:
1318 case ELF::R_HEX_TPREL_16_X:
1319 case ELF::R_HEX_TPREL_11_X:
1320 case ELF::R_HEX_LD_PLT_B22_PCREL:
1321 case ELF::R_HEX_LD_GOT_LO16:
1322 case ELF::R_HEX_LD_GOT_HI16:
1323 case ELF::R_HEX_LD_GOT_32:
1324 case ELF::R_HEX_LD_GOT_16:
1325 case ELF::R_HEX_LD_GOT_32_6_X:
1326 case ELF::R_HEX_LD_GOT_16_X:
1327 case ELF::R_HEX_LD_GOT_11_X:
1328 case ELF::R_HEX_GD_PLT_B22_PCREL_X:
1329 case ELF::R_HEX_GD_PLT_B32_PCREL_X:
1330 case ELF::R_HEX_LD_PLT_B22_PCREL_X:
1331 case ELF::R_HEX_LD_PLT_B32_PCREL_X:
1332 return true;
1333 default:
1334 return false;
1335 }
1336}
1337
1338// Hexagon call/branch immediates are encoded as the displacement from the
1339// instruction's own address, not the absolute target address, so these
1340// relocation types must have the instruction's load address subtracted out
1341// before LLVMHexagonApplyRelocation scatters the value into the instruction.
1342static bool isHexagonPCRelRelocation(uint32_t Type) {
1343 switch (Type) {
1344 case ELF::R_HEX_B22_PCREL:
1345 case ELF::R_HEX_B15_PCREL:
1346 case ELF::R_HEX_B7_PCREL:
1347 case ELF::R_HEX_B13_PCREL:
1348 case ELF::R_HEX_B9_PCREL:
1349 case ELF::R_HEX_B32_PCREL_X:
1350 case ELF::R_HEX_B22_PCREL_X:
1351 case ELF::R_HEX_B15_PCREL_X:
1352 case ELF::R_HEX_B13_PCREL_X:
1353 case ELF::R_HEX_B9_PCREL_X:
1354 case ELF::R_HEX_B7_PCREL_X:
1355 case ELF::R_HEX_32_PCREL:
1356 case ELF::R_HEX_PLT_B22_PCREL:
1357 case ELF::R_HEX_6_PCREL_X:
1358 return true;
1359 default:
1360 return false;
1361 }
1362}
1363
1364// The branch relocation that follows an extender applies only displacement
1365// bits 5:0; the extender's relocation carries the rest. The branch's ABI range
1366// therefore does not apply to the full displacement.
1367static bool isHexagonExtendedBranchLowRelocation(uint32_t Type) {
1368 switch (Type) {
1369 case ELF::R_HEX_B22_PCREL_X:
1370 case ELF::R_HEX_B15_PCREL_X:
1371 case ELF::R_HEX_B13_PCREL_X:
1372 case ELF::R_HEX_B9_PCREL_X:
1373 case ELF::R_HEX_B7_PCREL_X:
1374 return true;
1375 default:
1376 return false;
1377 }
1378}
1379
1380// Number of bytes a relocation reads and writes at its site. Data relocations
1381// are narrower than an instruction word, so a 4-byte access could run past
1382// the end of the section.
1383static unsigned getHexagonRelocationSize(uint32_t Type) {
1384 switch (Type) {
1385 case ELF::R_HEX_8:
1386 return 1;
1387 case ELF::R_HEX_16:
1388 return 2;
1389 default:
1390 return 4;
1391 }
1392}
1393
1394#endif // HEXAGON_TARGET_ENABLED
1395
1396void RuntimeDyldELF::resolveHexagonRelocation(const SectionEntry &Section,
1398 uint32_t Type, int64_t Addend) {
1399#ifdef HEXAGON_TARGET_ENABLED
1400 if (Type == ELF::R_HEX_NONE)
1401 return;
1402
1403 // Report the first failure through the RuntimeDyld error state and leave the
1404 // relocation site untouched.
1405 auto Fail = [&](const Twine &Msg) {
1406 if (!HasError) {
1407 HasError = true;
1408 ErrorStr = Msg.str();
1409 }
1410 };
1411
1414 return Fail("Unknown Hexagon relocation type " + Twine(Type));
1415
1416 unsigned Size = getHexagonRelocationSize(Type);
1417 if (Offset > Section.getSize() || Size > Section.getSize() - Offset)
1418 return Fail(Twine(Info.Name) + " relocation at offset 0x" +
1419 utohexstr(Offset) + " is outside its section");
1420
1421 // Keep S + A (- P) wide until it has been validated; narrowing first could
1422 // turn an unrepresentable value into a plausible-looking one.
1423 int64_t Wide = static_cast<int64_t>(Value + Addend);
1424 if (isHexagonPCRelRelocation(Type))
1425 Wide -= static_cast<int64_t>(Section.getLoadAddressWithOffset(Offset));
1426
1427 // The relocation table records whether the ABI verifies a relocation's range
1428 // and alignment; relocations that are allowed to truncate must not be
1429 // rejected.
1430 if (Info.VerifyRange && !isHexagonExtendedBranchLowRelocation(Type) &&
1431 !(Info.IsSigned ? isInt<32>(Wide) : isUInt<32>(Wide)))
1432 return Fail(Twine(Info.Name) + " relocation out of range");
1433
1434 uint32_t Reloc = static_cast<uint32_t>(Wide);
1435 if (Info.VerifyAlignment && !LLVMHexagonVerifyAlignment(Type, Reloc))
1436 return Fail(Twine(Info.Name) + " relocation target 0x" + utohexstr(Reloc) +
1437 " is not " + Twine(Info.Alignment) + "-byte aligned");
1438
1439 // LLVMHexagonVerifyRange expects the value after the relocation's shift.
1440 if (Info.VerifyRange && !isHexagonExtendedBranchLowRelocation(Type)) {
1441 uint32_t Shifted =
1442 Info.IsSigned
1443 ? static_cast<uint32_t>(static_cast<int32_t>(Reloc) >> Info.Shift)
1444 : Reloc >> Info.Shift;
1445 if (!LLVMHexagonVerifyRange(Type, Shifted))
1446 return Fail(Twine(Info.Name) + " relocation out of range: 0x" +
1447 utohexstr(Reloc) + " does not fit in " +
1448 Twine(Info.EffectiveBits) + " bits");
1449 }
1450
1451 uint8_t *TargetPtr = Section.getAddressWithOffset(Offset);
1452 LLVM_DEBUG(dbgs() << "resolveHexagonRelocation, LocalAddress: "
1453 << Section.getAddressWithOffset(Offset) << " FinalAddress: "
1454 << format("%p", Section.getLoadAddressWithOffset(Offset))
1455 << " Value: " << format("%x", Reloc)
1456 << " Type: " << format("%x", Type)
1457 << " Addend: " << format("%llx", Addend) << "\n");
1458 uint32_t Insn = readBytesUnaligned(TargetPtr, Size);
1459 LLVM_DEBUG(dbgs() << " Ins: " << format("%x", Insn));
1460 Insn = LLVMHexagonApplyRelocation(Type, Insn, Reloc);
1461 writeBytesUnaligned(Insn, TargetPtr, Size);
1462#else
1463 llvm_unreachable("Hexagon target not enabled");
1464#endif
1465}
1466
1467void RuntimeDyldELF::resolveBPFRelocation(const SectionEntry &Section,
1469 uint32_t Type, int64_t Addend) {
1470 bool isBE = Arch == Triple::bpfeb;
1471
1472 switch (Type) {
1473 default:
1474 report_fatal_error("Relocation type not implemented yet!");
1475 break;
1476 case ELF::R_BPF_NONE:
1477 case ELF::R_BPF_64_64:
1478 case ELF::R_BPF_64_32:
1479 case ELF::R_BPF_64_NODYLD32:
1480 break;
1481 case ELF::R_BPF_64_ABS64: {
1482 write(isBE, Section.getAddressWithOffset(Offset), Value + Addend);
1483 LLVM_DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
1484 << format("%p\n", Section.getAddressWithOffset(Offset)));
1485 break;
1486 }
1487 case ELF::R_BPF_64_ABS32: {
1488 Value += Addend;
1489 assert(Value <= UINT32_MAX);
1490 write(isBE, Section.getAddressWithOffset(Offset), static_cast<uint32_t>(Value));
1491 LLVM_DEBUG(dbgs() << "Writing " << format("%p", Value) << " at "
1492 << format("%p\n", Section.getAddressWithOffset(Offset)));
1493 break;
1494 }
1495 }
1496}
1497
1498static void applyUTypeImmRISCV(uint8_t *InstrAddr, uint32_t Imm) {
1499 uint32_t UpperImm = (Imm + 0x800) & 0xfffff000;
1500 auto Instr = support::ulittle32_t::ref(InstrAddr);
1501 Instr = (Instr & 0xfff) | UpperImm;
1502}
1503
1504static void applyITypeImmRISCV(uint8_t *InstrAddr, uint32_t Imm) {
1505 uint32_t LowerImm = Imm & 0xfff;
1506 auto Instr = support::ulittle32_t::ref(InstrAddr);
1507 Instr = (Instr & 0xfffff) | (LowerImm << 20);
1508}
1509
1510void RuntimeDyldELF::resolveRISCVRelocation(const SectionEntry &Section,
1512 uint32_t Type, int64_t Addend,
1513 SID SectionID) {
1514 switch (Type) {
1515 default: {
1516 std::string Err = "Unimplemented reloc type: " + std::to_string(Type);
1517 llvm::report_fatal_error(Err.c_str());
1518 }
1519 // 32-bit PC-relative function call, macros call, tail (PIC)
1520 // Write first 20 bits of 32 bit value to the auipc instruction
1521 // Last 12 bits to the jalr instruction
1522 case ELF::R_RISCV_CALL:
1523 case ELF::R_RISCV_CALL_PLT: {
1524 uint64_t P = Section.getLoadAddressWithOffset(Offset);
1525 uint64_t PCOffset = Value + Addend - P;
1526 applyUTypeImmRISCV(Section.getAddressWithOffset(Offset), PCOffset);
1527 applyITypeImmRISCV(Section.getAddressWithOffset(Offset + 4), PCOffset);
1528 break;
1529 }
1530 // High 20 bits of 32-bit absolute address, %hi(symbol)
1531 case ELF::R_RISCV_HI20: {
1532 uint64_t PCOffset = Value + Addend;
1533 applyUTypeImmRISCV(Section.getAddressWithOffset(Offset), PCOffset);
1534 break;
1535 }
1536 // Low 12 bits of 32-bit absolute address, %lo(symbol)
1537 case ELF::R_RISCV_LO12_I: {
1538 uint64_t PCOffset = Value + Addend;
1539 applyITypeImmRISCV(Section.getAddressWithOffset(Offset), PCOffset);
1540 break;
1541 }
1542 // High 20 bits of 32-bit PC-relative reference, %pcrel_hi(symbol)
1543 case ELF::R_RISCV_GOT_HI20:
1544 case ELF::R_RISCV_PCREL_HI20: {
1545 uint64_t P = Section.getLoadAddressWithOffset(Offset);
1546 uint64_t PCOffset = Value + Addend - P;
1547 applyUTypeImmRISCV(Section.getAddressWithOffset(Offset), PCOffset);
1548 break;
1549 }
1550
1551 // label:
1552 // auipc a0, %pcrel_hi(symbol) // R_RISCV_PCREL_HI20
1553 // addi a0, a0, %pcrel_lo(label) // R_RISCV_PCREL_LO12_I
1554 //
1555 // The low 12 bits of relative address between pc and symbol.
1556 // The symbol is related to the high part instruction which is marked by
1557 // label.
1558 case ELF::R_RISCV_PCREL_LO12_I: {
1559 for (auto &&PendingReloc : PendingRelocs) {
1560 const RelocationValueRef &MatchingValue = PendingReloc.first;
1561 RelocationEntry &Reloc = PendingReloc.second;
1562 uint64_t HIRelocPC =
1563 getSectionLoadAddress(Reloc.SectionID) + Reloc.Offset;
1564 if (Value + Addend == HIRelocPC) {
1566 MatchingValue.Addend;
1567 auto PCOffset = Symbol - HIRelocPC;
1568 applyITypeImmRISCV(Section.getAddressWithOffset(Offset), PCOffset);
1569 return;
1570 }
1571 }
1572
1574 "R_RISCV_PCREL_LO12_I without matching R_RISCV_PCREL_HI20");
1575 }
1576 case ELF::R_RISCV_32_PCREL: {
1577 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
1578 int64_t RealOffset = Value + Addend - FinalAddress;
1579 int32_t TruncOffset = Lo_32(RealOffset);
1580 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
1581 TruncOffset;
1582 break;
1583 }
1584 case ELF::R_RISCV_32: {
1585 auto Ref = support::ulittle32_t::ref(Section.getAddressWithOffset(Offset));
1586 Ref = Value + Addend;
1587 break;
1588 }
1589 case ELF::R_RISCV_64: {
1590 auto Ref = support::ulittle64_t::ref(Section.getAddressWithOffset(Offset));
1591 Ref = Value + Addend;
1592 break;
1593 }
1594 case ELF::R_RISCV_ADD8: {
1595 auto Ref = support::ulittle8_t::ref(Section.getAddressWithOffset(Offset));
1596 Ref = Ref + Value + Addend;
1597 break;
1598 }
1599 case ELF::R_RISCV_ADD16: {
1600 auto Ref = support::ulittle16_t::ref(Section.getAddressWithOffset(Offset));
1601 Ref = Ref + Value + Addend;
1602 break;
1603 }
1604 case ELF::R_RISCV_ADD32: {
1605 auto Ref = support::ulittle32_t::ref(Section.getAddressWithOffset(Offset));
1606 Ref = Ref + Value + Addend;
1607 break;
1608 }
1609 case ELF::R_RISCV_ADD64: {
1610 auto Ref = support::ulittle64_t::ref(Section.getAddressWithOffset(Offset));
1611 Ref = Ref + Value + Addend;
1612 break;
1613 }
1614 case ELF::R_RISCV_SUB8: {
1615 auto Ref = support::ulittle8_t::ref(Section.getAddressWithOffset(Offset));
1616 Ref = Ref - Value - Addend;
1617 break;
1618 }
1619 case ELF::R_RISCV_SUB16: {
1620 auto Ref = support::ulittle16_t::ref(Section.getAddressWithOffset(Offset));
1621 Ref = Ref - Value - Addend;
1622 break;
1623 }
1624 case ELF::R_RISCV_SUB32: {
1625 auto Ref = support::ulittle32_t::ref(Section.getAddressWithOffset(Offset));
1626 Ref = Ref - Value - Addend;
1627 break;
1628 }
1629 case ELF::R_RISCV_SUB64: {
1630 auto Ref = support::ulittle64_t::ref(Section.getAddressWithOffset(Offset));
1631 Ref = Ref - Value - Addend;
1632 break;
1633 }
1634 case ELF::R_RISCV_SET8: {
1635 auto Ref = support::ulittle8_t::ref(Section.getAddressWithOffset(Offset));
1636 Ref = Value + Addend;
1637 break;
1638 }
1639 case ELF::R_RISCV_SET16: {
1640 auto Ref = support::ulittle16_t::ref(Section.getAddressWithOffset(Offset));
1641 Ref = Value + Addend;
1642 break;
1643 }
1644 case ELF::R_RISCV_SET32: {
1645 auto Ref = support::ulittle32_t::ref(Section.getAddressWithOffset(Offset));
1646 Ref = Value + Addend;
1647 break;
1648 }
1649 }
1650}
1651
1652// The target location for the relocation is described by RE.SectionID and
1653// RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
1654// SectionEntry has three members describing its location.
1655// SectionEntry::Address is the address at which the section has been loaded
1656// into memory in the current (host) process. SectionEntry::LoadAddress is the
1657// address that the section will have in the target process.
1658// SectionEntry::ObjAddress is the address of the bits for this section in the
1659// original emitted object image (also in the current address space).
1660//
1661// Relocations will be applied as if the section were loaded at
1662// SectionEntry::LoadAddress, but they will be applied at an address based
1663// on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
1664// Target memory contents if they are required for value calculations.
1665//
1666// The Value parameter here is the load address of the symbol for the
1667// relocation to be applied. For relocations which refer to symbols in the
1668// current object Value will be the LoadAddress of the section in which
1669// the symbol resides (RE.Addend provides additional information about the
1670// symbol location). For external symbols, Value will be the address of the
1671// symbol in the target address space.
1672void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
1673 uint64_t Value) {
1674 const SectionEntry &Section = Sections[RE.SectionID];
1675 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
1676 RE.SymOffset, RE.SectionID);
1677}
1678
1679void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
1680 uint64_t Offset, uint64_t Value,
1681 uint32_t Type, int64_t Addend,
1682 uint64_t SymOffset, SID SectionID) {
1683 switch (Arch) {
1684 case Triple::x86_64:
1685 resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
1686 break;
1687 case Triple::x86:
1688 resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
1689 (uint32_t)(Addend & 0xffffffffL));
1690 break;
1691 case Triple::aarch64:
1692 case Triple::aarch64_be:
1693 resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
1694 break;
1695 case Triple::arm: // Fall through.
1696 case Triple::armeb:
1697 case Triple::thumb:
1698 case Triple::thumbeb:
1699 resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
1700 (uint32_t)(Addend & 0xffffffffL));
1701 break;
1703 resolveLoongArch64Relocation(Section, Offset, Value, Type, Addend);
1704 break;
1705 case Triple::hexagon:
1706 resolveHexagonRelocation(Section, Offset, Value, Type, Addend);
1707 break;
1708 case Triple::ppc: // Fall through.
1709 case Triple::ppcle:
1710 resolvePPC32Relocation(Section, Offset, Value, Type, Addend);
1711 break;
1712 case Triple::ppc64: // Fall through.
1713 case Triple::ppc64le:
1714 resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
1715 break;
1716 case Triple::systemz:
1717 resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
1718 break;
1719 case Triple::bpfel:
1720 case Triple::bpfeb:
1721 resolveBPFRelocation(Section, Offset, Value, Type, Addend);
1722 break;
1723 case Triple::riscv32: // Fall through.
1724 case Triple::riscv64:
1725 resolveRISCVRelocation(Section, Offset, Value, Type, Addend, SectionID);
1726 break;
1727 default:
1728 llvm_unreachable("Unsupported CPU type!");
1729 }
1730}
1731
1732void *RuntimeDyldELF::computePlaceholderAddress(unsigned SectionID,
1733 uint64_t Offset) const {
1734 return (void *)(Sections[SectionID].getObjAddress() + Offset);
1735}
1736
1737void RuntimeDyldELF::processSimpleRelocation(unsigned SectionID, uint64_t Offset, unsigned RelType, RelocationValueRef Value) {
1738 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1739 if (Value.SymbolName)
1740 addRelocationForSymbol(RE, Value.SymbolName);
1741 else
1742 addRelocationForSection(RE, Value.SectionID);
1743}
1744
1745uint32_t RuntimeDyldELF::getMatchingLoRelocation(uint32_t RelType,
1746 bool IsLocal) const {
1747 switch (RelType) {
1748 case ELF::R_MICROMIPS_GOT16:
1749 if (IsLocal)
1750 return ELF::R_MICROMIPS_LO16;
1751 break;
1752 case ELF::R_MICROMIPS_HI16:
1753 return ELF::R_MICROMIPS_LO16;
1754 case ELF::R_MIPS_GOT16:
1755 if (IsLocal)
1756 return ELF::R_MIPS_LO16;
1757 break;
1758 case ELF::R_MIPS_HI16:
1759 return ELF::R_MIPS_LO16;
1760 case ELF::R_MIPS_PCHI16:
1761 return ELF::R_MIPS_PCLO16;
1762 default:
1763 break;
1764 }
1765 return ELF::R_MIPS_NONE;
1766}
1767
1768// Sometimes we don't need to create thunk for a branch.
1769// This typically happens when branch target is located
1770// in the same object file. In such case target is either
1771// a weak symbol or symbol in a different executable section.
1772// This function checks if branch target is located in the
1773// same object file and if distance between source and target
1774// fits R_AARCH64_CALL26 relocation. If both conditions are
1775// met, it emits direct jump to the target and returns true.
1776// Otherwise false is returned and thunk is created.
1777bool RuntimeDyldELF::resolveAArch64ShortBranch(
1778 unsigned SectionID, relocation_iterator RelI,
1779 const RelocationValueRef &Value) {
1780 uint64_t TargetOffset;
1781 unsigned TargetSectionID;
1782 if (Value.SymbolName) {
1783 auto Loc = GlobalSymbolTable.find(Value.SymbolName);
1784
1785 // Don't create direct branch for external symbols.
1786 if (Loc == GlobalSymbolTable.end())
1787 return false;
1788
1789 const auto &SymInfo = Loc->second;
1790
1791 TargetSectionID = SymInfo.getSectionID();
1792 TargetOffset = SymInfo.getOffset();
1793 } else {
1794 TargetSectionID = Value.SectionID;
1795 TargetOffset = 0;
1796 }
1797
1798 // We don't actually know the load addresses at this point, so if the
1799 // branch is cross-section, we don't know exactly how far away it is.
1800 if (TargetSectionID != SectionID)
1801 return false;
1802
1803 uint64_t SourceOffset = RelI->getOffset();
1804
1805 // R_AARCH64_CALL26 requires immediate to be in range -2^27 <= imm < 2^27
1806 // If distance between source and target is out of range then we should
1807 // create thunk.
1808 if (!isInt<28>(TargetOffset + Value.Addend - SourceOffset))
1809 return false;
1810
1811 RelocationEntry RE(SectionID, SourceOffset, RelI->getType(), Value.Addend);
1812 if (Value.SymbolName)
1813 addRelocationForSymbol(RE, Value.SymbolName);
1814 else
1815 addRelocationForSection(RE, Value.SectionID);
1816
1817 return true;
1818}
1819
1820void RuntimeDyldELF::resolveAArch64Branch(unsigned SectionID,
1823 StubMap &Stubs) {
1824
1825 LLVM_DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
1826 SectionEntry &Section = Sections[SectionID];
1827
1828 uint64_t Offset = RelI->getOffset();
1829 unsigned RelType = RelI->getType();
1830 // Look for an existing stub.
1831 StubMap::const_iterator i = Stubs.find(Value);
1832 if (i != Stubs.end()) {
1833 resolveRelocation(Section, Offset,
1834 Section.getLoadAddressWithOffset(i->second), RelType, 0);
1835 LLVM_DEBUG(dbgs() << " Stub function found\n");
1836 } else if (!resolveAArch64ShortBranch(SectionID, RelI, Value)) {
1837 // Create a new stub function.
1838 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1839 Stubs[Value] = Section.getStubOffset();
1840 uint8_t *StubTargetAddr = createStubFunction(
1841 Section.getAddressWithOffset(Section.getStubOffset()));
1842
1843 RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.getAddress(),
1844 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
1845 RelocationEntry REmovk_g2(SectionID,
1846 StubTargetAddr - Section.getAddress() + 4,
1847 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
1848 RelocationEntry REmovk_g1(SectionID,
1849 StubTargetAddr - Section.getAddress() + 8,
1850 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
1851 RelocationEntry REmovk_g0(SectionID,
1852 StubTargetAddr - Section.getAddress() + 12,
1853 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
1854
1855 if (Value.SymbolName) {
1856 addRelocationForSymbol(REmovz_g3, Value.SymbolName);
1857 addRelocationForSymbol(REmovk_g2, Value.SymbolName);
1858 addRelocationForSymbol(REmovk_g1, Value.SymbolName);
1859 addRelocationForSymbol(REmovk_g0, Value.SymbolName);
1860 } else {
1861 addRelocationForSection(REmovz_g3, Value.SectionID);
1862 addRelocationForSection(REmovk_g2, Value.SectionID);
1863 addRelocationForSection(REmovk_g1, Value.SectionID);
1864 addRelocationForSection(REmovk_g0, Value.SectionID);
1865 }
1866 resolveRelocation(Section, Offset,
1867 Section.getLoadAddressWithOffset(Section.getStubOffset()),
1868 RelType, 0);
1869 Section.advanceStubOffset(getMaxStubSize());
1870 }
1871}
1872
1875 unsigned SectionID, relocation_iterator RelI, const ObjectFile &O,
1876 ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs) {
1877 const auto &Obj = cast<ELFObjectFileBase>(O);
1878 uint64_t RelType = RelI->getType();
1879 if (Arch == Triple::hexagon) {
1880#ifdef HEXAGON_TARGET_ENABLED
1882 if (isUnsupportedHexagonRelocation(RelType) ||
1883 !LLVMHexagonGetRelocationInfo(RelType, &Info)) {
1884 SmallString<32> TypeName;
1885 RelI->getTypeName(TypeName);
1886 return make_error<RuntimeDyldError>(("Unsupported Hexagon relocation " +
1887 TypeName + " (" + Twine(RelType) +
1888 ")")
1889 .str());
1890 }
1891#else
1893 "Hexagon relocations require an LLVM build with the Hexagon target");
1894#endif
1895 }
1896 int64_t Addend = 0;
1897 if (Expected<int64_t> AddendOrErr = ELFRelocationRef(*RelI).getAddend())
1898 Addend = *AddendOrErr;
1899 else
1900 consumeError(AddendOrErr.takeError());
1901 elf_symbol_iterator Symbol = RelI->getSymbol();
1902
1903 // Obtain the symbol name which is referenced in the relocation
1904 StringRef TargetName;
1905 if (Symbol != Obj.symbol_end()) {
1906 if (auto TargetNameOrErr = Symbol->getName())
1907 TargetName = *TargetNameOrErr;
1908 else
1909 return TargetNameOrErr.takeError();
1910 }
1911 LLVM_DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
1912 << " TargetName: " << TargetName << "\n");
1914 // First search for the symbol in the local symbol table
1916
1917 // Search for the symbol in the global symbol table
1919 if (Symbol != Obj.symbol_end()) {
1920 gsi = GlobalSymbolTable.find(TargetName.data());
1921 Expected<SymbolRef::Type> SymTypeOrErr = Symbol->getType();
1922 if (!SymTypeOrErr) {
1923 std::string Buf;
1924 raw_string_ostream OS(Buf);
1925 logAllUnhandledErrors(SymTypeOrErr.takeError(), OS);
1927 }
1928 SymType = *SymTypeOrErr;
1929 }
1930 if (gsi != GlobalSymbolTable.end()) {
1931 const auto &SymInfo = gsi->second;
1932 Value.SectionID = SymInfo.getSectionID();
1933 Value.Offset = SymInfo.getOffset();
1934 Value.Addend = SymInfo.getOffset() + Addend;
1935 } else {
1936 switch (SymType) {
1937 case SymbolRef::ST_Debug: {
1938 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
1939 // and can be changed by another developers. Maybe best way is add
1940 // a new symbol type ST_Section to SymbolRef and use it.
1941 auto SectionOrErr = Symbol->getSection();
1942 if (!SectionOrErr) {
1943 std::string Buf;
1944 raw_string_ostream OS(Buf);
1945 logAllUnhandledErrors(SectionOrErr.takeError(), OS);
1947 }
1948 section_iterator si = *SectionOrErr;
1949 if (si == Obj.section_end())
1950 llvm_unreachable("Symbol section not found, bad object file format!");
1951 LLVM_DEBUG(dbgs() << "\t\tThis is section symbol\n");
1952 bool isCode = si->isText();
1953 if (auto SectionIDOrErr = findOrEmitSection(Obj, (*si), isCode,
1954 ObjSectionToID))
1955 Value.SectionID = *SectionIDOrErr;
1956 else
1957 return SectionIDOrErr.takeError();
1958 Value.Addend = Addend;
1959 break;
1960 }
1961 case SymbolRef::ST_Data:
1964 case SymbolRef::ST_Unknown: {
1965 Value.SymbolName = TargetName.data();
1966 Value.Addend = Addend;
1967
1968 // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
1969 // will manifest here as a NULL symbol name.
1970 // We can set this as a valid (but empty) symbol name, and rely
1971 // on addRelocationForSymbol to handle this.
1972 if (!Value.SymbolName)
1973 Value.SymbolName = "";
1974 break;
1975 }
1976 default:
1977 llvm_unreachable("Unresolved symbol type!");
1978 break;
1979 }
1980 }
1981
1982 uint64_t Offset = RelI->getOffset();
1983
1984 LLVM_DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
1985 << "\n");
1987 if ((RelType == ELF::R_AARCH64_CALL26 ||
1988 RelType == ELF::R_AARCH64_JUMP26) &&
1989 MemMgr.allowStubAllocation()) {
1990 resolveAArch64Branch(SectionID, Value, RelI, Stubs);
1991 } else if (RelType == ELF::R_AARCH64_ADR_GOT_PAGE) {
1992 // Create new GOT entry or find existing one. If GOT entry is
1993 // to be created, then we also emit ABS64 relocation for it.
1994 uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
1995 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1996 ELF::R_AARCH64_ADR_PREL_PG_HI21);
1997
1998 } else if (RelType == ELF::R_AARCH64_LD64_GOT_LO12_NC) {
1999 uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
2000 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
2001 ELF::R_AARCH64_LDST64_ABS_LO12_NC);
2002 } else {
2003 processSimpleRelocation(SectionID, Offset, RelType, Value);
2004 }
2005 } else if (Arch == Triple::arm) {
2006 if (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
2007 RelType == ELF::R_ARM_JUMP24) {
2008 // This is an ARM branch relocation, need to use a stub function.
2009 LLVM_DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.\n");
2010 SectionEntry &Section = Sections[SectionID];
2011
2012 // Look for an existing stub.
2013 auto [It, Inserted] = Stubs.try_emplace(Value);
2014 if (!Inserted) {
2015 resolveRelocation(Section, Offset,
2016 Section.getLoadAddressWithOffset(It->second), RelType,
2017 0);
2018 LLVM_DEBUG(dbgs() << " Stub function found\n");
2019 } else {
2020 // Create a new stub function.
2021 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
2022 It->second = Section.getStubOffset();
2023 uint8_t *StubTargetAddr = createStubFunction(
2024 Section.getAddressWithOffset(Section.getStubOffset()));
2025 RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
2026 ELF::R_ARM_ABS32, Value.Addend);
2027 if (Value.SymbolName)
2028 addRelocationForSymbol(RE, Value.SymbolName);
2029 else
2030 addRelocationForSection(RE, Value.SectionID);
2031
2032 resolveRelocation(
2033 Section, Offset,
2034 Section.getLoadAddressWithOffset(Section.getStubOffset()), RelType,
2035 0);
2036 Section.advanceStubOffset(getMaxStubSize());
2037 }
2038 } else {
2039 uint32_t *Placeholder =
2040 reinterpret_cast<uint32_t*>(computePlaceholderAddress(SectionID, Offset));
2041 if (RelType == ELF::R_ARM_PREL31 || RelType == ELF::R_ARM_TARGET1 ||
2042 RelType == ELF::R_ARM_ABS32) {
2043 Value.Addend += *Placeholder;
2044 } else if (RelType == ELF::R_ARM_MOVW_ABS_NC || RelType == ELF::R_ARM_MOVT_ABS) {
2045 // See ELF for ARM documentation
2046 Value.Addend += (int16_t)((*Placeholder & 0xFFF) | (((*Placeholder >> 16) & 0xF) << 12));
2047 }
2048 processSimpleRelocation(SectionID, Offset, RelType, Value);
2049 }
2050 } else if (Arch == Triple::loongarch64) {
2051 if ((RelType == ELF::R_LARCH_B26 || RelType == ELF::R_LARCH_CALL36) &&
2052 MemMgr.allowStubAllocation()) {
2053 resolveLoongArch64Branch(SectionID, Value, RelI, Stubs);
2054 } else if (RelType == ELF::R_LARCH_GOT_PC_HI20 ||
2055 RelType == ELF::R_LARCH_GOT_PC_LO12 ||
2056 RelType == ELF::R_LARCH_GOT64_PC_HI12 ||
2057 RelType == ELF::R_LARCH_GOT64_PC_LO20) {
2058 uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_LARCH_64);
2059 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
2060 RelType);
2061 } else {
2062 processSimpleRelocation(SectionID, Offset, RelType, Value);
2063 }
2064 } else if (IsMipsO32ABI) {
2065 uint8_t *Placeholder = reinterpret_cast<uint8_t *>(
2066 computePlaceholderAddress(SectionID, Offset));
2067 uint32_t Opcode = readBytesUnaligned(Placeholder, 4);
2068 if (RelType == ELF::R_MIPS_26) {
2069 // This is an Mips branch relocation, need to use a stub function.
2070 LLVM_DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
2071 SectionEntry &Section = Sections[SectionID];
2072
2073 // Extract the addend from the instruction.
2074 // We shift up by two since the Value will be down shifted again
2075 // when applying the relocation.
2076 uint32_t Addend = (Opcode & 0x03ffffff) << 2;
2077
2078 Value.Addend += Addend;
2079
2080 // Look up for existing stub.
2081 auto [It, Inserted] = Stubs.try_emplace(Value);
2082 if (!Inserted) {
2083 RelocationEntry RE(SectionID, Offset, RelType, It->second);
2084 addRelocationForSection(RE, SectionID);
2085 LLVM_DEBUG(dbgs() << " Stub function found\n");
2086 } else {
2087 // Create a new stub function.
2088 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
2089 It->second = Section.getStubOffset();
2090
2091 unsigned AbiVariant = Obj.getPlatformFlags();
2092
2093 uint8_t *StubTargetAddr = createStubFunction(
2094 Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
2095
2096 // Creating Hi and Lo relocations for the filled stub instructions.
2097 RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
2098 ELF::R_MIPS_HI16, Value.Addend);
2099 RelocationEntry RELo(SectionID,
2100 StubTargetAddr - Section.getAddress() + 4,
2101 ELF::R_MIPS_LO16, Value.Addend);
2102
2103 if (Value.SymbolName) {
2104 addRelocationForSymbol(REHi, Value.SymbolName);
2105 addRelocationForSymbol(RELo, Value.SymbolName);
2106 } else {
2107 addRelocationForSection(REHi, Value.SectionID);
2108 addRelocationForSection(RELo, Value.SectionID);
2109 }
2110
2111 RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
2112 addRelocationForSection(RE, SectionID);
2113 Section.advanceStubOffset(getMaxStubSize());
2114 }
2115 } else if (RelType == ELF::R_MIPS_HI16 || RelType == ELF::R_MIPS_PCHI16) {
2116 int64_t Addend = (Opcode & 0x0000ffff) << 16;
2117 RelocationEntry RE(SectionID, Offset, RelType, Addend);
2118 PendingRelocs.push_back(std::make_pair(Value, RE));
2119 } else if (RelType == ELF::R_MIPS_LO16 || RelType == ELF::R_MIPS_PCLO16) {
2120 int64_t Addend = Value.Addend + SignExtend32<16>(Opcode & 0x0000ffff);
2121 for (auto I = PendingRelocs.begin(); I != PendingRelocs.end();) {
2122 const RelocationValueRef &MatchingValue = I->first;
2123 RelocationEntry &Reloc = I->second;
2124 if (MatchingValue == Value &&
2125 RelType == getMatchingLoRelocation(Reloc.RelType) &&
2126 SectionID == Reloc.SectionID) {
2127 Reloc.Addend += Addend;
2128 if (Value.SymbolName)
2129 addRelocationForSymbol(Reloc, Value.SymbolName);
2130 else
2132 I = PendingRelocs.erase(I);
2133 } else
2134 ++I;
2135 }
2136 RelocationEntry RE(SectionID, Offset, RelType, Addend);
2137 if (Value.SymbolName)
2138 addRelocationForSymbol(RE, Value.SymbolName);
2139 else
2140 addRelocationForSection(RE, Value.SectionID);
2141 } else {
2142 if (RelType == ELF::R_MIPS_32)
2143 Value.Addend += Opcode;
2144 else if (RelType == ELF::R_MIPS_PC16)
2145 Value.Addend += SignExtend32<18>((Opcode & 0x0000ffff) << 2);
2146 else if (RelType == ELF::R_MIPS_PC19_S2)
2147 Value.Addend += SignExtend32<21>((Opcode & 0x0007ffff) << 2);
2148 else if (RelType == ELF::R_MIPS_PC21_S2)
2149 Value.Addend += SignExtend32<23>((Opcode & 0x001fffff) << 2);
2150 else if (RelType == ELF::R_MIPS_PC26_S2)
2151 Value.Addend += SignExtend32<28>((Opcode & 0x03ffffff) << 2);
2152 processSimpleRelocation(SectionID, Offset, RelType, Value);
2153 }
2154 } else if (IsMipsN32ABI || IsMipsN64ABI) {
2155 uint32_t r_type = RelType & 0xff;
2156 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
2157 if (r_type == ELF::R_MIPS_CALL16 || r_type == ELF::R_MIPS_GOT_PAGE
2158 || r_type == ELF::R_MIPS_GOT_DISP) {
2159 auto [I, Inserted] = GOTSymbolOffsets.try_emplace(TargetName);
2160 if (Inserted)
2161 I->second = allocateGOTEntries(1);
2162 RE.SymOffset = I->second;
2163 if (Value.SymbolName)
2164 addRelocationForSymbol(RE, Value.SymbolName);
2165 else
2166 addRelocationForSection(RE, Value.SectionID);
2167 } else if (RelType == ELF::R_MIPS_26) {
2168 // This is an Mips branch relocation, need to use a stub function.
2169 LLVM_DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
2170 SectionEntry &Section = Sections[SectionID];
2171
2172 // Look up for existing stub.
2173 StubMap::const_iterator i = Stubs.find(Value);
2174 if (i != Stubs.end()) {
2175 RelocationEntry RE(SectionID, Offset, RelType, i->second);
2176 addRelocationForSection(RE, SectionID);
2177 LLVM_DEBUG(dbgs() << " Stub function found\n");
2178 } else {
2179 // Create a new stub function.
2180 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
2181 Stubs[Value] = Section.getStubOffset();
2182
2183 unsigned AbiVariant = Obj.getPlatformFlags();
2184
2185 uint8_t *StubTargetAddr = createStubFunction(
2186 Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
2187
2188 if (IsMipsN32ABI) {
2189 // Creating Hi and Lo relocations for the filled stub instructions.
2190 RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
2191 ELF::R_MIPS_HI16, Value.Addend);
2192 RelocationEntry RELo(SectionID,
2193 StubTargetAddr - Section.getAddress() + 4,
2194 ELF::R_MIPS_LO16, Value.Addend);
2195 if (Value.SymbolName) {
2196 addRelocationForSymbol(REHi, Value.SymbolName);
2197 addRelocationForSymbol(RELo, Value.SymbolName);
2198 } else {
2199 addRelocationForSection(REHi, Value.SectionID);
2200 addRelocationForSection(RELo, Value.SectionID);
2201 }
2202 } else {
2203 // Creating Highest, Higher, Hi and Lo relocations for the filled stub
2204 // instructions.
2205 RelocationEntry REHighest(SectionID,
2206 StubTargetAddr - Section.getAddress(),
2207 ELF::R_MIPS_HIGHEST, Value.Addend);
2208 RelocationEntry REHigher(SectionID,
2209 StubTargetAddr - Section.getAddress() + 4,
2210 ELF::R_MIPS_HIGHER, Value.Addend);
2211 RelocationEntry REHi(SectionID,
2212 StubTargetAddr - Section.getAddress() + 12,
2213 ELF::R_MIPS_HI16, Value.Addend);
2214 RelocationEntry RELo(SectionID,
2215 StubTargetAddr - Section.getAddress() + 20,
2216 ELF::R_MIPS_LO16, Value.Addend);
2217 if (Value.SymbolName) {
2218 addRelocationForSymbol(REHighest, Value.SymbolName);
2219 addRelocationForSymbol(REHigher, Value.SymbolName);
2220 addRelocationForSymbol(REHi, Value.SymbolName);
2221 addRelocationForSymbol(RELo, Value.SymbolName);
2222 } else {
2223 addRelocationForSection(REHighest, Value.SectionID);
2224 addRelocationForSection(REHigher, Value.SectionID);
2225 addRelocationForSection(REHi, Value.SectionID);
2226 addRelocationForSection(RELo, Value.SectionID);
2227 }
2228 }
2229 RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
2230 addRelocationForSection(RE, SectionID);
2231 Section.advanceStubOffset(getMaxStubSize());
2232 }
2233 } else {
2234 processSimpleRelocation(SectionID, Offset, RelType, Value);
2235 }
2236
2237 } else if (Arch == Triple::ppc) {
2238 if (RelType == ELF::R_PPC_PLTREL24) {
2239 // The addend selects the GOT pointer of a PLT call stub. It is not an
2240 // offset from the symbol.
2241 Value.Addend -= Addend;
2242 RelType = ELF::R_PPC_REL24;
2243 }
2244
2245 // A branch needs a stub if its target is external or out of range.
2246 SectionEntry &Section = Sections[SectionID];
2247 bool NeedsStub = RelType == ELF::R_PPC_REL24 &&
2248 (Value.SymbolName ||
2249 !isInt<26>(Sections[Value.SectionID].getAddressWithOffset(
2250 Value.Addend) -
2251 Section.getAddressWithOffset(Offset)));
2252 if (!NeedsStub) {
2253 processSimpleRelocation(SectionID, Offset, RelType, Value);
2254 } else {
2255 auto [It, Inserted] = Stubs.try_emplace(Value, Section.getStubOffset());
2256 if (Inserted) {
2257 createStubFunction(Section.getAddressWithOffset(It->second));
2258 // The relocations apply to the low half of the lis and the ori.
2259 processSimpleRelocation(SectionID, It->second + 2, ELF::R_PPC_ADDR16_HI,
2260 Value);
2261 processSimpleRelocation(SectionID, It->second + 6, ELF::R_PPC_ADDR16_LO,
2262 Value);
2263 Section.advanceStubOffset(getMaxStubSize());
2264 }
2265 resolveRelocation(Section, Offset,
2266 Section.getLoadAddressWithOffset(It->second), RelType,
2267 0);
2268 }
2269 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
2270 if (RelType == ELF::R_PPC64_REL24) {
2271 // Determine ABI variant in use for this object.
2272 unsigned AbiVariant = Obj.getPlatformFlags();
2273 AbiVariant &= ELF::EF_PPC64_ABI;
2274 // A PPC branch relocation will need a stub function if the target is
2275 // an external symbol (either Value.SymbolName is set, or SymType is
2276 // Symbol::ST_Unknown) or if the target address is not within the
2277 // signed 24-bits branch address.
2278 SectionEntry &Section = Sections[SectionID];
2279 uint8_t *Target = Section.getAddressWithOffset(Offset);
2280 bool RangeOverflow = false;
2281 bool IsExtern = Value.SymbolName || SymType == SymbolRef::ST_Unknown;
2282 if (!IsExtern) {
2283 if (AbiVariant != 2) {
2284 // In the ELFv1 ABI, a function call may point to the .opd entry,
2285 // so the final symbol value is calculated based on the relocation
2286 // values in the .opd section.
2287 if (auto Err = findOPDEntrySection(Obj, ObjSectionToID, Value))
2288 return std::move(Err);
2289 } else {
2290 // In the ELFv2 ABI, a function symbol may provide a local entry
2291 // point, which must be used for direct calls.
2292 if (Value.SectionID == SectionID){
2293 uint8_t SymOther = Symbol->getOther();
2294 Value.Addend += ELF::decodePPC64LocalEntryOffset(SymOther);
2295 }
2296 }
2297 uint8_t *RelocTarget =
2298 Sections[Value.SectionID].getAddressWithOffset(Value.Addend);
2299 int64_t delta = static_cast<int64_t>(Target - RelocTarget);
2300 // If it is within 26-bits branch range, just set the branch target
2301 if (SignExtend64<26>(delta) != delta) {
2302 RangeOverflow = true;
2303 } else if ((AbiVariant != 2) ||
2304 (AbiVariant == 2 && Value.SectionID == SectionID)) {
2305 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
2306 addRelocationForSection(RE, Value.SectionID);
2307 }
2308 }
2309 if (IsExtern || (AbiVariant == 2 && Value.SectionID != SectionID) ||
2310 RangeOverflow) {
2311 // It is an external symbol (either Value.SymbolName is set, or
2312 // SymType is SymbolRef::ST_Unknown) or out of range.
2313 auto [It, Inserted] = Stubs.try_emplace(Value);
2314 if (!Inserted) {
2315 // Symbol function stub already created, just relocate to it
2316 resolveRelocation(Section, Offset,
2317 Section.getLoadAddressWithOffset(It->second),
2318 RelType, 0);
2319 LLVM_DEBUG(dbgs() << " Stub function found\n");
2320 } else {
2321 // Create a new stub function.
2322 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
2323 It->second = Section.getStubOffset();
2324 uint8_t *StubTargetAddr = createStubFunction(
2325 Section.getAddressWithOffset(Section.getStubOffset()),
2326 AbiVariant);
2327 RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
2328 ELF::R_PPC64_ADDR64, Value.Addend);
2329
2330 // Generates the 64-bits address loads as exemplified in section
2331 // 4.5.1 in PPC64 ELF ABI. Note that the relocations need to
2332 // apply to the low part of the instructions, so we have to update
2333 // the offset according to the target endianness.
2334 uint64_t StubRelocOffset = StubTargetAddr - Section.getAddress();
2336 StubRelocOffset += 2;
2337
2338 RelocationEntry REhst(SectionID, StubRelocOffset + 0,
2339 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
2340 RelocationEntry REhr(SectionID, StubRelocOffset + 4,
2341 ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
2342 RelocationEntry REh(SectionID, StubRelocOffset + 12,
2343 ELF::R_PPC64_ADDR16_HI, Value.Addend);
2344 RelocationEntry REl(SectionID, StubRelocOffset + 16,
2345 ELF::R_PPC64_ADDR16_LO, Value.Addend);
2346
2347 if (Value.SymbolName) {
2348 addRelocationForSymbol(REhst, Value.SymbolName);
2349 addRelocationForSymbol(REhr, Value.SymbolName);
2350 addRelocationForSymbol(REh, Value.SymbolName);
2351 addRelocationForSymbol(REl, Value.SymbolName);
2352 } else {
2353 addRelocationForSection(REhst, Value.SectionID);
2354 addRelocationForSection(REhr, Value.SectionID);
2355 addRelocationForSection(REh, Value.SectionID);
2356 addRelocationForSection(REl, Value.SectionID);
2357 }
2358
2359 resolveRelocation(
2360 Section, Offset,
2361 Section.getLoadAddressWithOffset(Section.getStubOffset()),
2362 RelType, 0);
2363 Section.advanceStubOffset(getMaxStubSize());
2364 }
2365 if (IsExtern || (AbiVariant == 2 && Value.SectionID != SectionID)) {
2366 // Restore the TOC for external calls
2367 if (AbiVariant == 2)
2368 writeInt32BE(Target + 4, 0xE8410018); // ld r2,24(r1)
2369 else
2370 writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
2371 }
2372 }
2373 } else if (RelType == ELF::R_PPC64_TOC16 ||
2374 RelType == ELF::R_PPC64_TOC16_DS ||
2375 RelType == ELF::R_PPC64_TOC16_LO ||
2376 RelType == ELF::R_PPC64_TOC16_LO_DS ||
2377 RelType == ELF::R_PPC64_TOC16_HI ||
2378 RelType == ELF::R_PPC64_TOC16_HA) {
2379 // These relocations are supposed to subtract the TOC address from
2380 // the final value. This does not fit cleanly into the RuntimeDyld
2381 // scheme, since there may be *two* sections involved in determining
2382 // the relocation value (the section of the symbol referred to by the
2383 // relocation, and the TOC section associated with the current module).
2384 //
2385 // Fortunately, these relocations are currently only ever generated
2386 // referring to symbols that themselves reside in the TOC, which means
2387 // that the two sections are actually the same. Thus they cancel out
2388 // and we can immediately resolve the relocation right now.
2389 switch (RelType) {
2390 case ELF::R_PPC64_TOC16: RelType = ELF::R_PPC64_ADDR16; break;
2391 case ELF::R_PPC64_TOC16_DS: RelType = ELF::R_PPC64_ADDR16_DS; break;
2392 case ELF::R_PPC64_TOC16_LO: RelType = ELF::R_PPC64_ADDR16_LO; break;
2393 case ELF::R_PPC64_TOC16_LO_DS: RelType = ELF::R_PPC64_ADDR16_LO_DS; break;
2394 case ELF::R_PPC64_TOC16_HI: RelType = ELF::R_PPC64_ADDR16_HI; break;
2395 case ELF::R_PPC64_TOC16_HA: RelType = ELF::R_PPC64_ADDR16_HA; break;
2396 default: llvm_unreachable("Wrong relocation type.");
2397 }
2398
2399 RelocationValueRef TOCValue;
2400 if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, TOCValue))
2401 return std::move(Err);
2402 if (Value.SymbolName || Value.SectionID != TOCValue.SectionID)
2403 llvm_unreachable("Unsupported TOC relocation.");
2404 Value.Addend -= TOCValue.Addend;
2405 resolveRelocation(Sections[SectionID], Offset, Value.Addend, RelType, 0);
2406 } else {
2407 // There are two ways to refer to the TOC address directly: either
2408 // via a ELF::R_PPC64_TOC relocation (where both symbol and addend are
2409 // ignored), or via any relocation that refers to the magic ".TOC."
2410 // symbols (in which case the addend is respected).
2411 if (RelType == ELF::R_PPC64_TOC) {
2412 RelType = ELF::R_PPC64_ADDR64;
2413 if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
2414 return std::move(Err);
2415 } else if (TargetName == ".TOC.") {
2416 if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
2417 return std::move(Err);
2418 Value.Addend += Addend;
2419 }
2420
2421 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
2422
2423 if (Value.SymbolName)
2424 addRelocationForSymbol(RE, Value.SymbolName);
2425 else
2426 addRelocationForSection(RE, Value.SectionID);
2427 }
2428 } else if (Arch == Triple::systemz &&
2429 (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
2430 // Create function stubs for both PLT and GOT references, regardless of
2431 // whether the GOT reference is to data or code. The stub contains the
2432 // full address of the symbol, as needed by GOT references, and the
2433 // executable part only adds an overhead of 8 bytes.
2434 //
2435 // We could try to conserve space by allocating the code and data
2436 // parts of the stub separately. However, as things stand, we allocate
2437 // a stub for every relocation, so using a GOT in JIT code should be
2438 // no less space efficient than using an explicit constant pool.
2439 LLVM_DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
2440 SectionEntry &Section = Sections[SectionID];
2441
2442 // Look for an existing stub.
2443 StubMap::const_iterator i = Stubs.find(Value);
2444 uintptr_t StubAddress;
2445 if (i != Stubs.end()) {
2446 StubAddress = uintptr_t(Section.getAddressWithOffset(i->second));
2447 LLVM_DEBUG(dbgs() << " Stub function found\n");
2448 } else {
2449 // Create a new stub function.
2450 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
2451
2452 uintptr_t BaseAddress = uintptr_t(Section.getAddress());
2453 StubAddress =
2454 alignTo(BaseAddress + Section.getStubOffset(), getStubAlignment());
2455 unsigned StubOffset = StubAddress - BaseAddress;
2456
2457 Stubs[Value] = StubOffset;
2458 createStubFunction((uint8_t *)StubAddress);
2459 RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
2460 Value.Offset);
2461 if (Value.SymbolName)
2462 addRelocationForSymbol(RE, Value.SymbolName);
2463 else
2464 addRelocationForSection(RE, Value.SectionID);
2465 Section.advanceStubOffset(getMaxStubSize());
2466 }
2467
2468 if (RelType == ELF::R_390_GOTENT)
2469 resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
2470 Addend);
2471 else
2472 resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
2473 } else if (Arch == Triple::x86_64) {
2474 if (RelType == ELF::R_X86_64_PLT32) {
2475 // The way the PLT relocations normally work is that the linker allocates
2476 // the
2477 // PLT and this relocation makes a PC-relative call into the PLT. The PLT
2478 // entry will then jump to an address provided by the GOT. On first call,
2479 // the
2480 // GOT address will point back into PLT code that resolves the symbol. After
2481 // the first call, the GOT entry points to the actual function.
2482 //
2483 // For local functions we're ignoring all of that here and just replacing
2484 // the PLT32 relocation type with PC32, which will translate the relocation
2485 // into a PC-relative call directly to the function. For external symbols we
2486 // can't be sure the function will be within 2^32 bytes of the call site, so
2487 // we need to create a stub, which calls into the GOT. This case is
2488 // equivalent to the usual PLT implementation except that we use the stub
2489 // mechanism in RuntimeDyld (which puts stubs at the end of the section)
2490 // rather than allocating a PLT section.
2491 if (Value.SymbolName && MemMgr.allowStubAllocation()) {
2492 // This is a call to an external function.
2493 // Look for an existing stub.
2494 SectionEntry *Section = &Sections[SectionID];
2495 auto [It, Inserted] = Stubs.try_emplace(Value);
2496 uintptr_t StubAddress;
2497 if (!Inserted) {
2498 StubAddress = uintptr_t(Section->getAddress()) + It->second;
2499 LLVM_DEBUG(dbgs() << " Stub function found\n");
2500 } else {
2501 // Create a new stub function (equivalent to a PLT entry).
2502 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
2503
2504 uintptr_t BaseAddress = uintptr_t(Section->getAddress());
2505 StubAddress = alignTo(BaseAddress + Section->getStubOffset(),
2506 getStubAlignment());
2507 unsigned StubOffset = StubAddress - BaseAddress;
2508 It->second = StubOffset;
2509 createStubFunction((uint8_t *)StubAddress);
2510
2511 // Bump our stub offset counter
2512 Section->advanceStubOffset(getMaxStubSize());
2513
2514 // Allocate a GOT Entry
2515 uint64_t GOTOffset = allocateGOTEntries(1);
2516 // This potentially creates a new Section which potentially
2517 // invalidates the Section pointer, so reload it.
2518 Section = &Sections[SectionID];
2519
2520 // The load of the GOT address has an addend of -4
2521 resolveGOTOffsetRelocation(SectionID, StubOffset + 2, GOTOffset - 4,
2522 ELF::R_X86_64_PC32);
2523
2524 // Fill in the value of the symbol we're targeting into the GOT
2526 computeGOTOffsetRE(GOTOffset, 0, ELF::R_X86_64_64),
2527 Value.SymbolName);
2528 }
2529
2530 // Make the target call a call into the stub table.
2531 resolveRelocation(*Section, Offset, StubAddress, ELF::R_X86_64_PC32,
2532 Addend);
2533 } else {
2534 Value.Addend += support::ulittle32_t::ref(
2535 computePlaceholderAddress(SectionID, Offset));
2536 processSimpleRelocation(SectionID, Offset, ELF::R_X86_64_PC32, Value);
2537 }
2538 } else if (RelType == ELF::R_X86_64_GOTPCREL ||
2539 RelType == ELF::R_X86_64_GOTPCRELX ||
2540 RelType == ELF::R_X86_64_REX_GOTPCRELX) {
2541 uint64_t GOTOffset = allocateGOTEntries(1);
2542 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
2543 ELF::R_X86_64_PC32);
2544
2545 // Fill in the value of the symbol we're targeting into the GOT
2546 RelocationEntry RE =
2547 computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_64);
2548 if (Value.SymbolName)
2549 addRelocationForSymbol(RE, Value.SymbolName);
2550 else
2551 addRelocationForSection(RE, Value.SectionID);
2552 } else if (RelType == ELF::R_X86_64_GOT64) {
2553 // Fill in a 64-bit GOT offset.
2554 uint64_t GOTOffset = allocateGOTEntries(1);
2555 resolveRelocation(Sections[SectionID], Offset, GOTOffset,
2556 ELF::R_X86_64_64, 0);
2557
2558 // Fill in the value of the symbol we're targeting into the GOT
2559 RelocationEntry RE =
2560 computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_64);
2561 if (Value.SymbolName)
2562 addRelocationForSymbol(RE, Value.SymbolName);
2563 else
2564 addRelocationForSection(RE, Value.SectionID);
2565 } else if (RelType == ELF::R_X86_64_GOTPC32) {
2566 // Materialize the address of the base of the GOT relative to the PC.
2567 // This doesn't create a GOT entry, but it does mean we need a GOT
2568 // section.
2569 (void)allocateGOTEntries(0);
2570 resolveGOTOffsetRelocation(SectionID, Offset, Addend, ELF::R_X86_64_PC32);
2571 } else if (RelType == ELF::R_X86_64_GOTPC64) {
2572 (void)allocateGOTEntries(0);
2573 resolveGOTOffsetRelocation(SectionID, Offset, Addend, ELF::R_X86_64_PC64);
2574 } else if (RelType == ELF::R_X86_64_GOTOFF64) {
2575 // GOTOFF relocations ultimately require a section difference relocation.
2576 (void)allocateGOTEntries(0);
2577 processSimpleRelocation(SectionID, Offset, RelType, Value);
2578 } else if (RelType == ELF::R_X86_64_PC32) {
2579 Value.Addend += support::ulittle32_t::ref(computePlaceholderAddress(SectionID, Offset));
2580 processSimpleRelocation(SectionID, Offset, RelType, Value);
2581 } else if (RelType == ELF::R_X86_64_PC64) {
2582 Value.Addend += support::ulittle64_t::ref(
2583 computePlaceholderAddress(SectionID, Offset));
2584 processSimpleRelocation(SectionID, Offset, RelType, Value);
2585 } else if (RelType == ELF::R_X86_64_GOTTPOFF) {
2586 processX86_64GOTTPOFFRelocation(SectionID, Offset, Value, Addend);
2587 } else if (RelType == ELF::R_X86_64_TLSGD ||
2588 RelType == ELF::R_X86_64_TLSLD) {
2589 // The next relocation must be the relocation for __tls_get_addr.
2590 ++RelI;
2591 auto &GetAddrRelocation = *RelI;
2592 processX86_64TLSRelocation(SectionID, Offset, RelType, Value, Addend,
2593 GetAddrRelocation);
2594 } else {
2595 processSimpleRelocation(SectionID, Offset, RelType, Value);
2596 }
2597 } else if (Arch == Triple::riscv32 || Arch == Triple::riscv64) {
2598 // *_LO12 relocation receive information about a symbol from the
2599 // corresponding *_HI20 relocation, so we have to collect this information
2600 // before resolving
2601 if (RelType == ELF::R_RISCV_GOT_HI20 ||
2602 RelType == ELF::R_RISCV_PCREL_HI20 ||
2603 RelType == ELF::R_RISCV_TPREL_HI20 ||
2604 RelType == ELF::R_RISCV_TLS_GD_HI20 ||
2605 RelType == ELF::R_RISCV_TLS_GOT_HI20) {
2606 RelocationEntry RE(SectionID, Offset, RelType, Addend);
2607 PendingRelocs.push_back({Value, RE});
2608 }
2609 processSimpleRelocation(SectionID, Offset, RelType, Value);
2610 } else {
2611 if (Arch == Triple::x86) {
2612 Value.Addend += support::ulittle32_t::ref(
2613 computePlaceholderAddress(SectionID, Offset));
2614 }
2615 processSimpleRelocation(SectionID, Offset, RelType, Value);
2616 }
2617 return ++RelI;
2618}
2619
2620void RuntimeDyldELF::processX86_64GOTTPOFFRelocation(unsigned SectionID,
2621 uint64_t Offset,
2623 int64_t Addend) {
2624 // Use the approach from "x86-64 Linker Optimizations" from the TLS spec
2625 // to replace the GOTTPOFF relocation with a TPOFF relocation. The spec
2626 // only mentions one optimization even though there are two different
2627 // code sequences for the Initial Exec TLS Model. We match the code to
2628 // find out which one was used.
2629
2630 // A possible TLS code sequence and its replacement
2631 struct CodeSequence {
2632 // The expected code sequence
2633 ArrayRef<uint8_t> ExpectedCodeSequence;
2634 // The negative offset of the GOTTPOFF relocation to the beginning of
2635 // the sequence
2636 uint64_t TLSSequenceOffset;
2637 // The new code sequence
2638 ArrayRef<uint8_t> NewCodeSequence;
2639 // The offset of the new TPOFF relocation
2640 uint64_t TpoffRelocationOffset;
2641 };
2642
2643 std::array<CodeSequence, 2> CodeSequences;
2644
2645 // Initial Exec Code Model Sequence
2646 {
2647 static const std::initializer_list<uint8_t> ExpectedCodeSequenceList = {
2648 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00,
2649 0x00, // mov %fs:0, %rax
2650 0x48, 0x03, 0x05, 0x00, 0x00, 0x00, 0x00 // add x@gotpoff(%rip),
2651 // %rax
2652 };
2653 CodeSequences[0].ExpectedCodeSequence =
2654 ArrayRef<uint8_t>(ExpectedCodeSequenceList);
2655 CodeSequences[0].TLSSequenceOffset = 12;
2656
2657 static const std::initializer_list<uint8_t> NewCodeSequenceList = {
2658 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:0, %rax
2659 0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00 // lea x@tpoff(%rax), %rax
2660 };
2661 CodeSequences[0].NewCodeSequence = ArrayRef<uint8_t>(NewCodeSequenceList);
2662 CodeSequences[0].TpoffRelocationOffset = 12;
2663 }
2664
2665 // Initial Exec Code Model Sequence, II
2666 {
2667 static const std::initializer_list<uint8_t> ExpectedCodeSequenceList = {
2668 0x48, 0x8b, 0x05, 0x00, 0x00, 0x00, 0x00, // mov x@gotpoff(%rip), %rax
2669 0x64, 0x48, 0x8b, 0x00, 0x00, 0x00, 0x00 // mov %fs:(%rax), %rax
2670 };
2671 CodeSequences[1].ExpectedCodeSequence =
2672 ArrayRef<uint8_t>(ExpectedCodeSequenceList);
2673 CodeSequences[1].TLSSequenceOffset = 3;
2674
2675 static const std::initializer_list<uint8_t> NewCodeSequenceList = {
2676 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00, // 6 byte nop
2677 0x64, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:x@tpoff, %rax
2678 };
2679 CodeSequences[1].NewCodeSequence = ArrayRef<uint8_t>(NewCodeSequenceList);
2680 CodeSequences[1].TpoffRelocationOffset = 10;
2681 }
2682
2683 bool Resolved = false;
2684 auto &Section = Sections[SectionID];
2685 for (const auto &C : CodeSequences) {
2686 assert(C.ExpectedCodeSequence.size() == C.NewCodeSequence.size() &&
2687 "Old and new code sequences must have the same size");
2688
2689 if (Offset < C.TLSSequenceOffset ||
2690 (Offset - C.TLSSequenceOffset + C.NewCodeSequence.size()) >
2691 Section.getSize()) {
2692 // This can't be a matching sequence as it doesn't fit in the current
2693 // section
2694 continue;
2695 }
2696
2697 auto TLSSequenceStartOffset = Offset - C.TLSSequenceOffset;
2698 auto *TLSSequence = Section.getAddressWithOffset(TLSSequenceStartOffset);
2699 if (ArrayRef<uint8_t>(TLSSequence, C.ExpectedCodeSequence.size()) !=
2700 C.ExpectedCodeSequence) {
2701 continue;
2702 }
2703
2704 memcpy(TLSSequence, C.NewCodeSequence.data(), C.NewCodeSequence.size());
2705
2706 // The original GOTTPOFF relocation has an addend as it is PC relative,
2707 // so it needs to be corrected. The TPOFF32 relocation is used as an
2708 // absolute value (which is an offset from %fs:0), so remove the addend
2709 // again.
2710 RelocationEntry RE(SectionID,
2711 TLSSequenceStartOffset + C.TpoffRelocationOffset,
2712 ELF::R_X86_64_TPOFF32, Value.Addend - Addend);
2713
2714 if (Value.SymbolName)
2715 addRelocationForSymbol(RE, Value.SymbolName);
2716 else
2717 addRelocationForSection(RE, Value.SectionID);
2718
2719 Resolved = true;
2720 break;
2721 }
2722
2723 if (!Resolved) {
2724 // The GOTTPOFF relocation was not used in one of the sequences
2725 // described in the spec, so we can't optimize it to a TPOFF
2726 // relocation.
2727 uint64_t GOTOffset = allocateGOTEntries(1);
2728 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
2729 ELF::R_X86_64_PC32);
2730 RelocationEntry RE =
2731 computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_TPOFF64);
2732 if (Value.SymbolName)
2733 addRelocationForSymbol(RE, Value.SymbolName);
2734 else
2735 addRelocationForSection(RE, Value.SectionID);
2736 }
2737}
2738
2739void RuntimeDyldELF::processX86_64TLSRelocation(
2740 unsigned SectionID, uint64_t Offset, uint64_t RelType,
2741 RelocationValueRef Value, int64_t Addend,
2742 const RelocationRef &GetAddrRelocation) {
2743 // Since we are statically linking and have no additional DSOs, we can resolve
2744 // the relocation directly without using __tls_get_addr.
2745 // Use the approach from "x86-64 Linker Optimizations" from the TLS spec
2746 // to replace it with the Local Exec relocation variant.
2747
2748 // Find out whether the code was compiled with the large or small memory
2749 // model. For this we look at the next relocation which is the relocation
2750 // for the __tls_get_addr function. If it's a 32 bit relocation, it's the
2751 // small code model, with a 64 bit relocation it's the large code model.
2752 bool IsSmallCodeModel;
2753 // Is the relocation for the __tls_get_addr a PC-relative GOT relocation?
2754 bool IsGOTPCRel = false;
2755
2756 switch (GetAddrRelocation.getType()) {
2757 case ELF::R_X86_64_GOTPCREL:
2758 case ELF::R_X86_64_REX_GOTPCRELX:
2759 case ELF::R_X86_64_GOTPCRELX:
2760 IsGOTPCRel = true;
2761 [[fallthrough]];
2762 case ELF::R_X86_64_PLT32:
2763 IsSmallCodeModel = true;
2764 break;
2765 case ELF::R_X86_64_PLTOFF64:
2766 IsSmallCodeModel = false;
2767 break;
2768 default:
2770 "invalid TLS relocations for General/Local Dynamic TLS Model: "
2771 "expected PLT or GOT relocation for __tls_get_addr function");
2772 }
2773
2774 // The negative offset to the start of the TLS code sequence relative to
2775 // the offset of the TLSGD/TLSLD relocation
2776 uint64_t TLSSequenceOffset;
2777 // The expected start of the code sequence
2778 ArrayRef<uint8_t> ExpectedCodeSequence;
2779 // The new TLS code sequence that will replace the existing code
2780 ArrayRef<uint8_t> NewCodeSequence;
2781
2782 if (RelType == ELF::R_X86_64_TLSGD) {
2783 // The offset of the new TPOFF32 relocation (offset starting from the
2784 // beginning of the whole TLS sequence)
2785 uint64_t TpoffRelocOffset;
2786
2787 if (IsSmallCodeModel) {
2788 if (!IsGOTPCRel) {
2789 static const std::initializer_list<uint8_t> CodeSequence = {
2790 0x66, // data16 (no-op prefix)
2791 0x48, 0x8d, 0x3d, 0x00, 0x00,
2792 0x00, 0x00, // lea <disp32>(%rip), %rdi
2793 0x66, 0x66, // two data16 prefixes
2794 0x48, // rex64 (no-op prefix)
2795 0xe8, 0x00, 0x00, 0x00, 0x00 // call __tls_get_addr@plt
2796 };
2797 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2798 TLSSequenceOffset = 4;
2799 } else {
2800 // This code sequence is not described in the TLS spec but gcc
2801 // generates it sometimes.
2802 static const std::initializer_list<uint8_t> CodeSequence = {
2803 0x66, // data16 (no-op prefix)
2804 0x48, 0x8d, 0x3d, 0x00, 0x00,
2805 0x00, 0x00, // lea <disp32>(%rip), %rdi
2806 0x66, // data16 prefix (no-op prefix)
2807 0x48, // rex64 (no-op prefix)
2808 0xff, 0x15, 0x00, 0x00, 0x00,
2809 0x00 // call *__tls_get_addr@gotpcrel(%rip)
2810 };
2811 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2812 TLSSequenceOffset = 4;
2813 }
2814
2815 // The replacement code for the small code model. It's the same for
2816 // both sequences.
2817 static const std::initializer_list<uint8_t> SmallSequence = {
2818 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00,
2819 0x00, // mov %fs:0, %rax
2820 0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00 // lea x@tpoff(%rax),
2821 // %rax
2822 };
2823 NewCodeSequence = ArrayRef<uint8_t>(SmallSequence);
2824 TpoffRelocOffset = 12;
2825 } else {
2826 static const std::initializer_list<uint8_t> CodeSequence = {
2827 0x48, 0x8d, 0x3d, 0x00, 0x00, 0x00, 0x00, // lea <disp32>(%rip),
2828 // %rdi
2829 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2830 0x00, // movabs $__tls_get_addr@pltoff, %rax
2831 0x48, 0x01, 0xd8, // add %rbx, %rax
2832 0xff, 0xd0 // call *%rax
2833 };
2834 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2835 TLSSequenceOffset = 3;
2836
2837 // The replacement code for the large code model
2838 static const std::initializer_list<uint8_t> LargeSequence = {
2839 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00,
2840 0x00, // mov %fs:0, %rax
2841 0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00, // lea x@tpoff(%rax),
2842 // %rax
2843 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00 // nopw 0x0(%rax,%rax,1)
2844 };
2845 NewCodeSequence = ArrayRef<uint8_t>(LargeSequence);
2846 TpoffRelocOffset = 12;
2847 }
2848
2849 // The TLSGD/TLSLD relocations are PC-relative, so they have an addend.
2850 // The new TPOFF32 relocations is used as an absolute offset from
2851 // %fs:0, so remove the TLSGD/TLSLD addend again.
2852 RelocationEntry RE(SectionID, Offset - TLSSequenceOffset + TpoffRelocOffset,
2853 ELF::R_X86_64_TPOFF32, Value.Addend - Addend);
2854 if (Value.SymbolName)
2855 addRelocationForSymbol(RE, Value.SymbolName);
2856 else
2857 addRelocationForSection(RE, Value.SectionID);
2858 } else if (RelType == ELF::R_X86_64_TLSLD) {
2859 if (IsSmallCodeModel) {
2860 if (!IsGOTPCRel) {
2861 static const std::initializer_list<uint8_t> CodeSequence = {
2862 0x48, 0x8d, 0x3d, 0x00, 0x00, 0x00, // leaq <disp32>(%rip), %rdi
2863 0x00, 0xe8, 0x00, 0x00, 0x00, 0x00 // call __tls_get_addr@plt
2864 };
2865 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2866 TLSSequenceOffset = 3;
2867
2868 // The replacement code for the small code model
2869 static const std::initializer_list<uint8_t> SmallSequence = {
2870 0x66, 0x66, 0x66, // three data16 prefixes (no-op)
2871 0x64, 0x48, 0x8b, 0x04, 0x25,
2872 0x00, 0x00, 0x00, 0x00 // mov %fs:0, %rax
2873 };
2874 NewCodeSequence = ArrayRef<uint8_t>(SmallSequence);
2875 } else {
2876 // This code sequence is not described in the TLS spec but gcc
2877 // generates it sometimes.
2878 static const std::initializer_list<uint8_t> CodeSequence = {
2879 0x48, 0x8d, 0x3d, 0x00,
2880 0x00, 0x00, 0x00, // leaq <disp32>(%rip), %rdi
2881 0xff, 0x15, 0x00, 0x00,
2882 0x00, 0x00 // call
2883 // *__tls_get_addr@gotpcrel(%rip)
2884 };
2885 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2886 TLSSequenceOffset = 3;
2887
2888 // The replacement is code is just like above but it needs to be
2889 // one byte longer.
2890 static const std::initializer_list<uint8_t> SmallSequence = {
2891 0x0f, 0x1f, 0x40, 0x00, // 4 byte nop
2892 0x64, 0x48, 0x8b, 0x04, 0x25,
2893 0x00, 0x00, 0x00, 0x00 // mov %fs:0, %rax
2894 };
2895 NewCodeSequence = ArrayRef<uint8_t>(SmallSequence);
2896 }
2897 } else {
2898 // This is the same sequence as for the TLSGD sequence with the large
2899 // memory model above
2900 static const std::initializer_list<uint8_t> CodeSequence = {
2901 0x48, 0x8d, 0x3d, 0x00, 0x00, 0x00, 0x00, // lea <disp32>(%rip),
2902 // %rdi
2903 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2904 0x48, // movabs $__tls_get_addr@pltoff, %rax
2905 0x01, 0xd8, // add %rbx, %rax
2906 0xff, 0xd0 // call *%rax
2907 };
2908 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2909 TLSSequenceOffset = 3;
2910
2911 // The replacement code for the large code model
2912 static const std::initializer_list<uint8_t> LargeSequence = {
2913 0x66, 0x66, 0x66, // three data16 prefixes (no-op)
2914 0x66, 0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00,
2915 0x00, // 10 byte nop
2916 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00 // mov %fs:0,%rax
2917 };
2918 NewCodeSequence = ArrayRef<uint8_t>(LargeSequence);
2919 }
2920 } else {
2921 llvm_unreachable("both TLS relocations handled above");
2922 }
2923
2924 assert(ExpectedCodeSequence.size() == NewCodeSequence.size() &&
2925 "Old and new code sequences must have the same size");
2926
2927 auto &Section = Sections[SectionID];
2928 if (Offset < TLSSequenceOffset ||
2929 (Offset - TLSSequenceOffset + NewCodeSequence.size()) >
2930 Section.getSize()) {
2931 report_fatal_error("unexpected end of section in TLS sequence");
2932 }
2933
2934 auto *TLSSequence = Section.getAddressWithOffset(Offset - TLSSequenceOffset);
2935 if (ArrayRef<uint8_t>(TLSSequence, ExpectedCodeSequence.size()) !=
2936 ExpectedCodeSequence) {
2938 "invalid TLS sequence for Global/Local Dynamic TLS Model");
2939 }
2940
2941 memcpy(TLSSequence, NewCodeSequence.data(), NewCodeSequence.size());
2942}
2943
2945 // We don't use the GOT in all of these cases, but it's essentially free
2946 // to put them all here.
2947 size_t Result = 0;
2948 switch (Arch) {
2949 case Triple::x86_64:
2950 case Triple::aarch64:
2951 case Triple::aarch64_be:
2953 case Triple::ppc64:
2954 case Triple::ppc64le:
2955 case Triple::systemz:
2956 Result = sizeof(uint64_t);
2957 break;
2958 case Triple::x86:
2959 case Triple::arm:
2960 case Triple::ppc:
2961 case Triple::thumb:
2962 Result = sizeof(uint32_t);
2963 break;
2964 case Triple::hexagon:
2965 Result = sizeof(uint32_t);
2966 break;
2967 case Triple::mips:
2968 case Triple::mipsel:
2969 case Triple::mips64:
2970 case Triple::mips64el:
2972 Result = sizeof(uint32_t);
2973 else if (IsMipsN64ABI)
2974 Result = sizeof(uint64_t);
2975 else
2976 llvm_unreachable("Mips ABI not handled");
2977 break;
2978 default:
2979 llvm_unreachable("Unsupported CPU type!");
2980 }
2981 return Result;
2982}
2983
2984uint64_t RuntimeDyldELF::allocateGOTEntries(unsigned no) {
2985 if (GOTSectionID == 0) {
2986 GOTSectionID = Sections.size();
2987 // Reserve a section id. We'll allocate the section later
2988 // once we know the total size
2989 Sections.push_back(SectionEntry(".got", nullptr, 0, 0, 0));
2990 }
2991 uint64_t StartOffset = CurrentGOTIndex * getGOTEntrySize();
2992 CurrentGOTIndex += no;
2993 return StartOffset;
2994}
2995
2996uint64_t RuntimeDyldELF::findOrAllocGOTEntry(const RelocationValueRef &Value,
2997 unsigned GOTRelType) {
2998 auto E = GOTOffsetMap.insert({Value, 0});
2999 if (E.second) {
3000 uint64_t GOTOffset = allocateGOTEntries(1);
3001
3002 // Create relocation for newly created GOT entry
3003 RelocationEntry RE =
3004 computeGOTOffsetRE(GOTOffset, Value.Offset, GOTRelType);
3005 if (Value.SymbolName)
3006 addRelocationForSymbol(RE, Value.SymbolName);
3007 else
3008 addRelocationForSection(RE, Value.SectionID);
3009
3010 E.first->second = GOTOffset;
3011 }
3012
3013 return E.first->second;
3014}
3015
3016void RuntimeDyldELF::resolveGOTOffsetRelocation(unsigned SectionID,
3018 uint64_t GOTOffset,
3019 uint32_t Type) {
3020 // Fill in the relative address of the GOT Entry into the stub
3021 RelocationEntry GOTRE(SectionID, Offset, Type, GOTOffset);
3022 addRelocationForSection(GOTRE, GOTSectionID);
3023}
3024
3025RelocationEntry RuntimeDyldELF::computeGOTOffsetRE(uint64_t GOTOffset,
3026 uint64_t SymbolOffset,
3027 uint32_t Type) {
3028 return RelocationEntry(GOTSectionID, GOTOffset, Type, SymbolOffset);
3029}
3030
3031void RuntimeDyldELF::processNewSymbol(const SymbolRef &ObjSymbol, SymbolTableEntry& Symbol) {
3032 // This should never return an error as `processNewSymbol` wouldn't have been
3033 // called if getFlags() returned an error before.
3034 auto ObjSymbolFlags = cantFail(ObjSymbol.getFlags());
3035
3036 if (ObjSymbolFlags & SymbolRef::SF_Indirect) {
3037 if (IFuncStubSectionID == 0) {
3038 // Create a dummy section for the ifunc stubs. It will be actually
3039 // allocated in finalizeLoad() below.
3040 IFuncStubSectionID = Sections.size();
3041 Sections.push_back(
3042 SectionEntry(".text.__llvm_IFuncStubs", nullptr, 0, 0, 0));
3043 // First 64B are reserverd for the IFunc resolver
3044 IFuncStubOffset = 64;
3045 }
3046
3047 IFuncStubs.push_back(IFuncStub{IFuncStubOffset, Symbol});
3048 // Modify the symbol so that it points to the ifunc stub instead of to the
3049 // resolver function.
3050 Symbol = SymbolTableEntry(IFuncStubSectionID, IFuncStubOffset,
3051 Symbol.getFlags());
3052 IFuncStubOffset += getMaxIFuncStubSize();
3053 }
3054}
3055
3057 ObjSectionToIDMap &SectionMap) {
3058 if (IsMipsO32ABI)
3059 if (!PendingRelocs.empty())
3060 return make_error<RuntimeDyldError>("Can't find matching LO16 reloc");
3061
3062 // Create the IFunc stubs if necessary. This must be done before processing
3063 // the GOT entries, as the IFunc stubs may create some.
3064 if (IFuncStubSectionID != 0) {
3065 uint8_t *IFuncStubsAddr = MemMgr.allocateCodeSection(
3066 IFuncStubOffset, 1, IFuncStubSectionID, ".text.__llvm_IFuncStubs");
3067 if (!IFuncStubsAddr)
3069 "Unable to allocate memory for IFunc stubs!");
3070 Sections[IFuncStubSectionID] =
3071 SectionEntry(".text.__llvm_IFuncStubs", IFuncStubsAddr, IFuncStubOffset,
3072 IFuncStubOffset, 0);
3073
3074 createIFuncResolver(IFuncStubsAddr);
3075
3076 LLVM_DEBUG(dbgs() << "Creating IFunc stubs SectionID: "
3077 << IFuncStubSectionID << " Addr: "
3078 << Sections[IFuncStubSectionID].getAddress() << '\n');
3079 for (auto &IFuncStub : IFuncStubs) {
3080 auto &Symbol = IFuncStub.OriginalSymbol;
3081 LLVM_DEBUG(dbgs() << "\tSectionID: " << Symbol.getSectionID()
3082 << " Offset: " << format("%p", Symbol.getOffset())
3083 << " IFuncStubOffset: "
3084 << format("%p\n", IFuncStub.StubOffset));
3085 createIFuncStub(IFuncStubSectionID, 0, IFuncStub.StubOffset,
3086 Symbol.getSectionID(), Symbol.getOffset());
3087 }
3088
3089 IFuncStubSectionID = 0;
3090 IFuncStubOffset = 0;
3091 IFuncStubs.clear();
3092 }
3093
3094 // If necessary, allocate the global offset table
3095 if (GOTSectionID != 0) {
3096 // Allocate memory for the section
3097 size_t TotalSize = CurrentGOTIndex * getGOTEntrySize();
3098 uint8_t *Addr = MemMgr.allocateDataSection(TotalSize, getGOTEntrySize(),
3099 GOTSectionID, ".got", false);
3100 if (!Addr)
3101 return make_error<RuntimeDyldError>("Unable to allocate memory for GOT!");
3102
3103 Sections[GOTSectionID] =
3104 SectionEntry(".got", Addr, TotalSize, TotalSize, 0);
3105
3106 // For now, initialize all GOT entries to zero. We'll fill them in as
3107 // needed when GOT-based relocations are applied.
3108 memset(Addr, 0, TotalSize);
3109 if (IsMipsN32ABI || IsMipsN64ABI) {
3110 // To correctly resolve Mips GOT relocations, we need a mapping from
3111 // object's sections to GOTs.
3112 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
3113 SI != SE; ++SI) {
3114 if (!SI->relocations().empty()) {
3115 Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
3116 if (!RelSecOrErr)
3118 toString(RelSecOrErr.takeError()));
3119
3120 section_iterator RelocatedSection = *RelSecOrErr;
3121 ObjSectionToIDMap::iterator i = SectionMap.find(*RelocatedSection);
3122 assert(i != SectionMap.end());
3123 SectionToGOTMap[i->second] = GOTSectionID;
3124 }
3125 }
3126 GOTSymbolOffsets.clear();
3127 }
3128 }
3129
3130 // Look for and record the EH frame section.
3131 ObjSectionToIDMap::iterator i, e;
3132 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
3133 const SectionRef &Section = i->first;
3134
3135 StringRef Name;
3136 Expected<StringRef> NameOrErr = Section.getName();
3137 if (NameOrErr)
3138 Name = *NameOrErr;
3139 else
3140 consumeError(NameOrErr.takeError());
3141
3142 if (Name == ".eh_frame") {
3143 UnregisteredEHFrameSections.push_back(i->second);
3144 break;
3145 }
3146 }
3147
3148 GOTOffsetMap.clear();
3149 GOTSectionID = 0;
3150 CurrentGOTIndex = 0;
3151
3152 return Error::success();
3153}
3154
3156 return Obj.isELF();
3157}
3158
3159void RuntimeDyldELF::createIFuncResolver(uint8_t *Addr) const {
3160 if (Arch == Triple::x86_64) {
3161 // The adddres of the GOT1 entry is in %r11, the GOT2 entry is in %r11+8
3162 // (see createIFuncStub() for details)
3163 // The following code first saves all registers that contain the original
3164 // function arguments as those registers are not saved by the resolver
3165 // function. %r11 is saved as well so that the GOT2 entry can be updated
3166 // afterwards. Then it calls the actual IFunc resolver function whose
3167 // address is stored in GOT2. After the resolver function returns, all
3168 // saved registers are restored and the return value is written to GOT1.
3169 // Finally, jump to the now resolved function.
3170 // clang-format off
3171 const uint8_t StubCode[] = {
3172 0x57, // push %rdi
3173 0x56, // push %rsi
3174 0x52, // push %rdx
3175 0x51, // push %rcx
3176 0x41, 0x50, // push %r8
3177 0x41, 0x51, // push %r9
3178 0x41, 0x53, // push %r11
3179 0x41, 0xff, 0x53, 0x08, // call *0x8(%r11)
3180 0x41, 0x5b, // pop %r11
3181 0x41, 0x59, // pop %r9
3182 0x41, 0x58, // pop %r8
3183 0x59, // pop %rcx
3184 0x5a, // pop %rdx
3185 0x5e, // pop %rsi
3186 0x5f, // pop %rdi
3187 0x49, 0x89, 0x03, // mov %rax,(%r11)
3188 0xff, 0xe0 // jmp *%rax
3189 };
3190 // clang-format on
3191 static_assert(sizeof(StubCode) <= 64,
3192 "maximum size of the IFunc resolver is 64B");
3193 memcpy(Addr, StubCode, sizeof(StubCode));
3194 } else {
3196 "IFunc resolver is not supported for target architecture");
3197 }
3198}
3199
3200void RuntimeDyldELF::createIFuncStub(unsigned IFuncStubSectionID,
3201 uint64_t IFuncResolverOffset,
3202 uint64_t IFuncStubOffset,
3203 unsigned IFuncSectionID,
3204 uint64_t IFuncOffset) {
3205 auto &IFuncStubSection = Sections[IFuncStubSectionID];
3206 auto *Addr = IFuncStubSection.getAddressWithOffset(IFuncStubOffset);
3207
3208 if (Arch == Triple::x86_64) {
3209 // The first instruction loads a PC-relative address into %r11 which is a
3210 // GOT entry for this stub. This initially contains the address to the
3211 // IFunc resolver. We can use %r11 here as it's caller saved but not used
3212 // to pass any arguments. In fact, x86_64 ABI even suggests using %r11 for
3213 // code in the PLT. The IFunc resolver will use %r11 to update the GOT
3214 // entry.
3215 //
3216 // The next instruction just jumps to the address contained in the GOT
3217 // entry. As mentioned above, we do this two-step jump by first setting
3218 // %r11 so that the IFunc resolver has access to it.
3219 //
3220 // The IFunc resolver of course also needs to know the actual address of
3221 // the actual IFunc resolver function. This will be stored in a GOT entry
3222 // right next to the first one for this stub. So, the IFunc resolver will
3223 // be able to call it with %r11+8.
3224 //
3225 // In total, two adjacent GOT entries (+relocation) and one additional
3226 // relocation are required:
3227 // GOT1: Address of the IFunc resolver.
3228 // GOT2: Address of the IFunc resolver function.
3229 // IFuncStubOffset+3: 32-bit PC-relative address of GOT1.
3230 uint64_t GOT1 = allocateGOTEntries(2);
3231 uint64_t GOT2 = GOT1 + getGOTEntrySize();
3232
3233 RelocationEntry RE1(GOTSectionID, GOT1, ELF::R_X86_64_64,
3234 IFuncResolverOffset, {});
3235 addRelocationForSection(RE1, IFuncStubSectionID);
3236 RelocationEntry RE2(GOTSectionID, GOT2, ELF::R_X86_64_64, IFuncOffset, {});
3237 addRelocationForSection(RE2, IFuncSectionID);
3238
3239 const uint8_t StubCode[] = {
3240 0x4c, 0x8d, 0x1d, 0x00, 0x00, 0x00, 0x00, // leaq 0x0(%rip),%r11
3241 0x41, 0xff, 0x23 // jmpq *(%r11)
3242 };
3243 assert(sizeof(StubCode) <= getMaxIFuncStubSize() &&
3244 "IFunc stub size must not exceed getMaxIFuncStubSize()");
3245 memcpy(Addr, StubCode, sizeof(StubCode));
3246
3247 // The PC-relative value starts 4 bytes from the end of the leaq
3248 // instruction, so the addend is -4.
3249 resolveGOTOffsetRelocation(IFuncStubSectionID, IFuncStubOffset + 3,
3250 GOT1 - 4, ELF::R_X86_64_PC32);
3251 } else {
3252 report_fatal_error("IFunc stub is not supported for target architecture");
3253 }
3254}
3255
3256unsigned RuntimeDyldELF::getMaxIFuncStubSize() const {
3257 if (Arch == Triple::x86_64) {
3258 return 10;
3259 }
3260 return 0;
3261}
3262
3263bool RuntimeDyldELF::relocationNeedsGot(const RelocationRef &R) const {
3264 unsigned RelTy = R.getType();
3266 return RelTy == ELF::R_AARCH64_ADR_GOT_PAGE ||
3267 RelTy == ELF::R_AARCH64_LD64_GOT_LO12_NC;
3268
3270 return RelTy == ELF::R_LARCH_GOT_PC_HI20 ||
3271 RelTy == ELF::R_LARCH_GOT_PC_LO12 ||
3272 RelTy == ELF::R_LARCH_GOT64_PC_HI12 ||
3273 RelTy == ELF::R_LARCH_GOT64_PC_LO20;
3274
3275 if (Arch == Triple::x86_64)
3276 return RelTy == ELF::R_X86_64_GOTPCREL ||
3277 RelTy == ELF::R_X86_64_GOTPCRELX ||
3278 RelTy == ELF::R_X86_64_GOT64 ||
3279 RelTy == ELF::R_X86_64_REX_GOTPCRELX;
3280 return false;
3281}
3282
3283bool RuntimeDyldELF::relocationNeedsStub(const RelocationRef &R) const {
3284 if (Arch != Triple::x86_64)
3285 return true; // Conservative answer
3286
3287 switch (R.getType()) {
3288 default:
3289 return true; // Conservative answer
3290
3291
3292 case ELF::R_X86_64_GOTPCREL:
3293 case ELF::R_X86_64_GOTPCRELX:
3294 case ELF::R_X86_64_REX_GOTPCRELX:
3295 case ELF::R_X86_64_GOTPC64:
3296 case ELF::R_X86_64_GOT64:
3297 case ELF::R_X86_64_GOTOFF64:
3298 case ELF::R_X86_64_PC32:
3299 case ELF::R_X86_64_PC64:
3300 case ELF::R_X86_64_64:
3301 // We know that these reloation types won't need a stub function. This list
3302 // can be extended as needed.
3303 return false;
3304 }
3305}
3306
3307} // namespace llvm
#define Fail
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
uint64_t uint64_t
uint64_t Imm
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
Definition ELFTypes.h:119
LLVM_ABI bool LLVMHexagonVerifyAlignment(uint32_t RelocType, uint32_t Value)
Return true if Value satisfies the alignment required by RelocType.
LLVM_ABI uint32_t LLVMHexagonApplyRelocation(uint32_t RelocType, uint32_t Instruction, uint32_t Value)
Apply the ELF relocation RelocType with value Value to Instruction.
struct LLVMHexagonRelocInfo LLVMHexagonRelocInfo
ABI properties of a Hexagon ELF relocation type, as listed in the Hexagon ABI document.
LLVM_ABI bool LLVMHexagonVerifyRange(uint32_t RelocType, uint32_t Value)
Return true if Value fits the range the ABI specifies for RelocType.
LLVM_ABI bool LLVMHexagonGetRelocationInfo(uint32_t RelocType, LLVMHexagonRelocInfo *Info)
Fill Info with the properties of RelocType.
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define P(N)
static void or32le(void *P, int32_t V)
static void or32AArch64Imm(void *L, uint64_t Imm)
static uint64_t getBits(uint64_t Val, int Start, int End)
static void write32AArch64Addr(void *L, uint64_t Imm)
const char * Msg
#define LLVM_DEBUG(...)
Definition Debug.h:119
Expected< const Elf_Sym * > getSymbol(DataRefImpl Sym) const
static Expected< ELFObjectFile< ELFT > > create(MemoryBufferRef Object, bool InitContent=true)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
Symbol resolution interface.
Definition JITSymbol.h:373
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it.
RelocationEntry - used to represent relocations internally in the dynamic linker.
uint32_t RelType
RelType - relocation type.
uint64_t Offset
Offset - offset into the section.
int64_t Addend
Addend - the relocation addend encoded in the instruction itself.
unsigned SectionID
SectionID - the section this relocation points to.
void registerEHFrames() override
size_t getGOTEntrySize() override
~RuntimeDyldELF() override
static std::unique_ptr< RuntimeDyldELF > create(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver)
Error finalizeLoad(const ObjectFile &Obj, ObjSectionToIDMap &SectionMap) override
DenseMap< SID, SID > SectionToGOTMap
bool isCompatibleFile(const object::ObjectFile &Obj) const override
std::unique_ptr< RuntimeDyld::LoadedObjectInfo > loadObject(const object::ObjectFile &O) override
RuntimeDyldELF(RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver)
Expected< relocation_iterator > processRelocationRef(unsigned SectionID, relocation_iterator RelI, const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs) override
Parses one or more object file relocations (some object files use relocation pairs) and stores it to ...
std::map< SectionRef, unsigned > ObjSectionToIDMap
void writeInt32BE(uint8_t *Addr, uint32_t Value)
RuntimeDyldImpl(RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver)
void writeInt64BE(uint8_t *Addr, uint64_t Value)
std::map< RelocationValueRef, uintptr_t > StubMap
void writeInt16BE(uint8_t *Addr, uint16_t Value)
void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName)
JITSymbolResolver & Resolver
RuntimeDyld::MemoryManager & MemMgr
void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID)
Expected< unsigned > findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section, bool IsCode, ObjSectionToIDMap &LocalSections)
Find Section in LocalSections.
Triple::ArchType Arch
void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const
Endian-aware write.
uint8_t * createStubFunction(uint8_t *Addr, unsigned AbiVariant=0)
Emits long jump instruction to Addr.
uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const
Endian-aware read Read the least significant Size bytes from Src.
uint64_t getSectionLoadAddress(unsigned SectionID) const
virtual unsigned getMaxStubSize() const =0
RTDyldSymbolTable GlobalSymbolTable
Expected< ObjSectionToIDMap > loadObjectImpl(const object::ObjectFile &Obj)
SectionEntry - represents a section emitted into memory by the dynamic linker.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
StringMapIterBase< SymbolTableEntry, true > const_iterator
Definition StringMap.h:208
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Symbol info for RuntimeDyld.
Target - Wrapper for Target specific information.
@ UnknownArch
Definition Triple.h:51
@ loongarch64
Definition Triple.h:66
static LLVM_ABI StringRef getArchTypePrefix(ArchType Kind)
Get the "prefix" canonical name for the Kind architecture.
Definition Triple.cpp:264
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
Expected< uint32_t > getFlags() const
Get symbol flags (bitwise OR of SymbolRef::Flags)
DataRefImpl getRawDataRefImpl() const
Expected< int64_t > getAddend() const
This class is the base class for all object file types.
Definition ObjectFile.h:231
virtual section_iterator section_begin() const =0
uint64_t getType() const
Definition ObjectFile.h:633
uint64_t getOffset() const
Definition ObjectFile.h:625
symbol_iterator getSymbol() const
Definition ObjectFile.h:629
void getTypeName(SmallVectorImpl< char > &Result) const
Get a string that represents the type of this relocation.
Definition ObjectFile.h:637
This is a value type class that represents a single section in the list of sections in the object fil...
Definition ObjectFile.h:83
DataRefImpl getRawDataRefImpl() const
Definition ObjectFile.h:603
bool isText() const
Whether this section contains instructions.
Definition ObjectFile.h:555
Expected< StringRef > getName() const
Definition ObjectFile.h:522
This is a value type class that represents a single symbol in the list of symbols in the object file.
Definition ObjectFile.h:170
Expected< section_iterator > getSection() const
Get section this symbol is defined in reference to.
Definition ObjectFile.h:485
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const char SectionName[]
static int64_t decodePPC64LocalEntryOffset(unsigned Other)
Definition ELF.h:234
@ EF_PPC64_ABI
Definition ELF.h:226
@ EF_MIPS_ABI_O32
Definition ELF.h:342
@ EF_MIPS_ABI2
Definition ELF.h:334
content_iterator< SectionRef > section_iterator
Definition ObjectFile.h:49
content_iterator< RelocationRef > relocation_iterator
Definition ObjectFile.h:79
@ Resolved
Queried, materialization begun.
Definition Core.h:543
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
void write32le(void *P, uint32_t V)
Definition Endian.h:455
uint32_t read32le(const void *P)
Definition Endian.h:412
detail::packed_endian_specific_integral< int32_t, llvm::endianness::little, unaligned > little32_t
Definition Endian.h:280
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
static uint16_t applyPPChighera(uint64_t value)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
static uint16_t applyPPChi(uint64_t value)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
static void applyITypeImmRISCV(uint8_t *InstrAddr, uint32_t Imm)
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
static uint16_t applyPPChighesta(uint64_t value)
static uint16_t applyPPChighest(uint64_t value)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
static uint16_t applyPPCha(uint64_t value)
static void applyUTypeImmRISCV(uint8_t *InstrAddr, uint32_t Imm)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
static uint16_t applyPPClo(uint64_t value)
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
static uint16_t applyPPChigher(uint64_t value)
static void or32le(void *P, int32_t V)
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr int32_t SignExtend32(uint32_t X)
Sign-extend the number in the bottom B bits of X to a 32-bit integer.
Definition MathExtras.h:554
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static uint32_t extractBits(uint64_t Val, uint32_t Hi, uint32_t Lo)
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
static uint64_t getLoongArchPageDelta(uint64_t dest, uint64_t pc, uint32_t type)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746
static void write32AArch64Addr(void *T, uint64_t s, uint64_t p, int shift)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
ABI properties of a Hexagon ELF relocation type, as listed in the Hexagon ABI document.
SymInfo contains information about symbol: it's address and section index which is -1LL for absolute ...