106594e10SJim Grosbach //===-- RuntimeDyldELF.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-===//
24c647587SEli Bendersky //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64c647587SEli Bendersky //
74c647587SEli Bendersky //===----------------------------------------------------------------------===//
84c647587SEli Bendersky //
94c647587SEli Bendersky // Implementation of ELF support for the MC-JIT runtime dynamic linker.
104c647587SEli Bendersky //
114c647587SEli Bendersky //===----------------------------------------------------------------------===//
124c647587SEli Bendersky
13adc70568SAndrew Kaylor #include "RuntimeDyldELF.h"
1402628defSKeno Fischer #include "RuntimeDyldCheckerImpl.h"
15c97cfb69SSimon Dardis #include "Targets/RuntimeDyldELFMips.h"
16ed0881b2SChandler Carruth #include "llvm/ADT/STLExtras.h"
17ed0881b2SChandler Carruth #include "llvm/ADT/StringRef.h"
184c647587SEli Bendersky #include "llvm/ADT/Triple.h"
19264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
20126973baSMichael J. Spencer #include "llvm/Object/ELFObjectFile.h"
21ed0881b2SChandler Carruth #include "llvm/Object/ObjectFile.h"
22a8d2f819SAlexey Samsonov #include "llvm/Support/Endian.h"
23173c69f2SLang Hames #include "llvm/Support/MemoryBuffer.h"
24173c69f2SLang Hames
254c647587SEli Bendersky using namespace llvm;
264c647587SEli Bendersky using namespace llvm::object;
275240a305SEugene Leviant using namespace llvm::support::endian;
284c647587SEli Bendersky
29f58e376dSChandler Carruth #define DEBUG_TYPE "dyld"
30f58e376dSChandler Carruth
or32le(void * P,int32_t V)315240a305SEugene Leviant static void or32le(void *P, int32_t V) { write32le(P, read32le(P) | V); }
325240a305SEugene Leviant
or32AArch64Imm(void * L,uint64_t Imm)335240a305SEugene Leviant static void or32AArch64Imm(void *L, uint64_t Imm) {
345240a305SEugene Leviant or32le(L, (Imm & 0xFFF) << 10);
355240a305SEugene Leviant }
365240a305SEugene Leviant
write(bool isBE,void * P,T V)375240a305SEugene Leviant template <class T> static void write(bool isBE, void *P, T V) {
385240a305SEugene Leviant isBE ? write<T, support::big>(P, V) : write<T, support::little>(P, V);
395240a305SEugene Leviant }
405240a305SEugene Leviant
write32AArch64Addr(void * L,uint64_t Imm)415240a305SEugene Leviant static void write32AArch64Addr(void *L, uint64_t Imm) {
425240a305SEugene Leviant uint32_t ImmLo = (Imm & 0x3) << 29;
435240a305SEugene Leviant uint32_t ImmHi = (Imm & 0x1FFFFC) << 3;
445240a305SEugene Leviant uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3);
455240a305SEugene Leviant write32le(L, (read32le(L) & ~Mask) | ImmLo | ImmHi);
465240a305SEugene Leviant }
475240a305SEugene Leviant
485240a305SEugene Leviant // Return the bits [Start, End] from Val shifted Start bits.
495240a305SEugene Leviant // For instance, getBits(0xF0, 4, 8) returns 0xF.
getBits(uint64_t Val,int Start,int End)505240a305SEugene Leviant static uint64_t getBits(uint64_t Val, int Start, int End) {
515240a305SEugene Leviant uint64_t Mask = ((uint64_t)1 << (End + 1 - Start)) - 1;
525240a305SEugene Leviant return (Val >> Start) & Mask;
535240a305SEugene Leviant }
545240a305SEugene Leviant
55b5c7b1ffSLang Hames namespace {
56b5c7b1ffSLang Hames
577608dc04SJuergen Ributzka template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> {
58035b4165SRafael Espindola LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
59cc31af93SPreston Gurd
60fc635510SRui Ueyama typedef typename ELFT::uint addr_type;
61cc31af93SPreston Gurd
62ef421f9cSRafael Espindola DyldELFObject(ELFObjectFile<ELFT> &&Obj);
63ef421f9cSRafael Espindola
64cc31af93SPreston Gurd public:
65ef421f9cSRafael Espindola static Expected<std::unique_ptr<DyldELFObject>>
66ef421f9cSRafael Espindola create(MemoryBufferRef Wrapper);
67cc31af93SPreston Gurd
68cc31af93SPreston Gurd void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
69b5c7b1ffSLang Hames
70b5c7b1ffSLang Hames void updateSymbolAddress(const SymbolRef &SymRef, uint64_t Addr);
71cc31af93SPreston Gurd
725c01090cSAndrew Kaylor // Methods for type inquiry through isa, cast and dyn_cast
classof(const Binary * v)733d65030cSSam Clegg static bool classof(const Binary *v) {
747608dc04SJuergen Ributzka return (isa<ELFObjectFile<ELFT>>(v) &&
757608dc04SJuergen Ributzka classof(cast<ELFObjectFile<ELFT>>(v)));
76cc31af93SPreston Gurd }
classof(const ELFObjectFile<ELFT> * v)773d65030cSSam Clegg static bool classof(const ELFObjectFile<ELFT> *v) {
78cc31af93SPreston Gurd return v->isDyldType();
79cc31af93SPreston Gurd }
80cc31af93SPreston Gurd };
81cc31af93SPreston Gurd
82cc31af93SPreston Gurd
83cc31af93SPreston Gurd
84adc70568SAndrew Kaylor // The MemoryBuffer passed into this constructor is just a wrapper around the
85adc70568SAndrew Kaylor // actual memory. Ultimately, the Binary parent class will take ownership of
86adc70568SAndrew Kaylor // this MemoryBuffer object but not the underlying memory.
871a79161fSMichael J. Spencer template <class ELFT>
DyldELFObject(ELFObjectFile<ELFT> && Obj)88ef421f9cSRafael Espindola DyldELFObject<ELFT>::DyldELFObject(ELFObjectFile<ELFT> &&Obj)
89ef421f9cSRafael Espindola : ELFObjectFile<ELFT>(std::move(Obj)) {
90cc31af93SPreston Gurd this->isDyldELFObject = true;
91cc31af93SPreston Gurd }
92cc31af93SPreston Gurd
931a79161fSMichael J. Spencer template <class ELFT>
94ef421f9cSRafael Espindola Expected<std::unique_ptr<DyldELFObject<ELFT>>>
create(MemoryBufferRef Wrapper)95ef421f9cSRafael Espindola DyldELFObject<ELFT>::create(MemoryBufferRef Wrapper) {
96ef421f9cSRafael Espindola auto Obj = ELFObjectFile<ELFT>::create(Wrapper);
97ef421f9cSRafael Espindola if (auto E = Obj.takeError())
98c55cf4afSBill Wendling return std::move(E);
99ef421f9cSRafael Espindola std::unique_ptr<DyldELFObject<ELFT>> Ret(
100ef421f9cSRafael Espindola new DyldELFObject<ELFT>(std::move(*Obj)));
101c55cf4afSBill Wendling return std::move(Ret);
102ef421f9cSRafael Espindola }
103ef421f9cSRafael Espindola
104ef421f9cSRafael Espindola template <class ELFT>
updateSectionAddress(const SectionRef & Sec,uint64_t Addr)1051a79161fSMichael J. Spencer void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
1061a79161fSMichael J. Spencer uint64_t Addr) {
107cc31af93SPreston Gurd DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
1087608dc04SJuergen Ributzka Elf_Shdr *shdr =
1097608dc04SJuergen Ributzka const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
110cc31af93SPreston Gurd
111cc31af93SPreston Gurd // This assumes the address passed in matches the target address bitness
112cc31af93SPreston Gurd // The template-based type cast handles everything else.
113cc31af93SPreston Gurd shdr->sh_addr = static_cast<addr_type>(Addr);
114cc31af93SPreston Gurd }
115cc31af93SPreston Gurd
1161a79161fSMichael J. Spencer template <class ELFT>
updateSymbolAddress(const SymbolRef & SymRef,uint64_t Addr)1171a79161fSMichael J. Spencer void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
1181a79161fSMichael J. Spencer uint64_t Addr) {
119cc31af93SPreston Gurd
120cc31af93SPreston Gurd Elf_Sym *sym = const_cast<Elf_Sym *>(
1211a79161fSMichael J. Spencer ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
122cc31af93SPreston Gurd
123cc31af93SPreston Gurd // This assumes the address passed in matches the target address bitness
124cc31af93SPreston Gurd // The template-based type cast handles everything else.
125cc31af93SPreston Gurd sym->st_value = static_cast<addr_type>(Addr);
126cc31af93SPreston Gurd }
127cc31af93SPreston Gurd
1285e1ffae7SDavid Blaikie class LoadedELFObjectInfo final
12987131577SDavid Blaikie : public LoadedObjectInfoHelper<LoadedELFObjectInfo,
13087131577SDavid Blaikie RuntimeDyld::LoadedObjectInfo> {
131b5c7b1ffSLang Hames public:
LoadedELFObjectInfo(RuntimeDyldImpl & RTDyld,ObjSectionToIDMap ObjSecToIDMap)1322e88f4fcSLang Hames LoadedELFObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
1332e88f4fcSLang Hames : LoadedObjectInfoHelper(RTDyld, std::move(ObjSecToIDMap)) {}
134b5c7b1ffSLang Hames
135b5c7b1ffSLang Hames OwningBinary<ObjectFile>
136b5c7b1ffSLang Hames getObjectForDebug(const ObjectFile &Obj) const override;
137b5c7b1ffSLang Hames };
138b5c7b1ffSLang Hames
139b5c7b1ffSLang Hames template <typename ELFT>
140ff9f5f33SRafael Espindola static Expected<std::unique_ptr<DyldELFObject<ELFT>>>
createRTDyldELFObject(MemoryBufferRef Buffer,const ObjectFile & SourceObject,const LoadedELFObjectInfo & L)141563ede14SRafael Espindola createRTDyldELFObject(MemoryBufferRef Buffer, const ObjectFile &SourceObject,
142ff9f5f33SRafael Espindola const LoadedELFObjectInfo &L) {
143478d6351SRui Ueyama typedef typename ELFT::Shdr Elf_Shdr;
144fc635510SRui Ueyama typedef typename ELFT::uint addr_type;
145b5c7b1ffSLang Hames
146ef421f9cSRafael Espindola Expected<std::unique_ptr<DyldELFObject<ELFT>>> ObjOrErr =
147ef421f9cSRafael Espindola DyldELFObject<ELFT>::create(Buffer);
148ef421f9cSRafael Espindola if (Error E = ObjOrErr.takeError())
149c55cf4afSBill Wendling return std::move(E);
150ef421f9cSRafael Espindola
151ef421f9cSRafael Espindola std::unique_ptr<DyldELFObject<ELFT>> Obj = std::move(*ObjOrErr);
152b5c7b1ffSLang Hames
153b5c7b1ffSLang Hames // Iterate over all sections in the object.
1542e88f4fcSLang Hames auto SI = SourceObject.section_begin();
155b5c7b1ffSLang Hames for (const auto &Sec : Obj->sections()) {
156bcc00e1aSGeorge Rimar Expected<StringRef> NameOrErr = Sec.getName();
157bcc00e1aSGeorge Rimar if (!NameOrErr) {
158bcc00e1aSGeorge Rimar consumeError(NameOrErr.takeError());
159bcc00e1aSGeorge Rimar continue;
160bcc00e1aSGeorge Rimar }
161bcc00e1aSGeorge Rimar
162bcc00e1aSGeorge Rimar if (*NameOrErr != "") {
163b5c7b1ffSLang Hames DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
164b5c7b1ffSLang Hames Elf_Shdr *shdr = const_cast<Elf_Shdr *>(
165b5c7b1ffSLang Hames reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
166b5c7b1ffSLang Hames
1672e88f4fcSLang Hames if (uint64_t SecLoadAddr = L.getSectionLoadAddress(*SI)) {
168b5c7b1ffSLang Hames // This assumes that the address passed in matches the target address
169b5c7b1ffSLang Hames // bitness. The template-based type cast handles everything else.
170b5c7b1ffSLang Hames shdr->sh_addr = static_cast<addr_type>(SecLoadAddr);
171b5c7b1ffSLang Hames }
172b5c7b1ffSLang Hames }
1732e88f4fcSLang Hames ++SI;
174b5c7b1ffSLang Hames }
175b5c7b1ffSLang Hames
176c55cf4afSBill Wendling return std::move(Obj);
177b5c7b1ffSLang Hames }
178b5c7b1ffSLang Hames
179563ede14SRafael Espindola static OwningBinary<ObjectFile>
createELFDebugObject(const ObjectFile & Obj,const LoadedELFObjectInfo & L)180563ede14SRafael Espindola createELFDebugObject(const ObjectFile &Obj, const LoadedELFObjectInfo &L) {
181b5c7b1ffSLang Hames assert(Obj.isELF() && "Not an ELF object file.");
182b5c7b1ffSLang Hames
183b5c7b1ffSLang Hames std::unique_ptr<MemoryBuffer> Buffer =
184b5c7b1ffSLang Hames MemoryBuffer::getMemBufferCopy(Obj.getData(), Obj.getFileName());
185b5c7b1ffSLang Hames
186ff9f5f33SRafael Espindola Expected<std::unique_ptr<ObjectFile>> DebugObj(nullptr);
187ff9f5f33SRafael Espindola handleAllErrors(DebugObj.takeError());
188563ede14SRafael Espindola if (Obj.getBytesInAddress() == 4 && Obj.isLittleEndian())
189ff9f5f33SRafael Espindola DebugObj =
190ff9f5f33SRafael Espindola createRTDyldELFObject<ELF32LE>(Buffer->getMemBufferRef(), Obj, L);
191563ede14SRafael Espindola else if (Obj.getBytesInAddress() == 4 && !Obj.isLittleEndian())
192ff9f5f33SRafael Espindola DebugObj =
193ff9f5f33SRafael Espindola createRTDyldELFObject<ELF32BE>(Buffer->getMemBufferRef(), Obj, L);
194563ede14SRafael Espindola else if (Obj.getBytesInAddress() == 8 && !Obj.isLittleEndian())
195ff9f5f33SRafael Espindola DebugObj =
196ff9f5f33SRafael Espindola createRTDyldELFObject<ELF64BE>(Buffer->getMemBufferRef(), Obj, L);
197563ede14SRafael Espindola else if (Obj.getBytesInAddress() == 8 && Obj.isLittleEndian())
198ff9f5f33SRafael Espindola DebugObj =
199ff9f5f33SRafael Espindola createRTDyldELFObject<ELF64LE>(Buffer->getMemBufferRef(), Obj, L);
200563ede14SRafael Espindola else
201b5c7b1ffSLang Hames llvm_unreachable("Unexpected ELF format");
202b5c7b1ffSLang Hames
203ff9f5f33SRafael Espindola handleAllErrors(DebugObj.takeError());
204ff9f5f33SRafael Espindola return OwningBinary<ObjectFile>(std::move(*DebugObj), std::move(Buffer));
205b5c7b1ffSLang Hames }
206b5c7b1ffSLang Hames
207b5c7b1ffSLang Hames OwningBinary<ObjectFile>
getObjectForDebug(const ObjectFile & Obj) const208b5c7b1ffSLang Hames LoadedELFObjectInfo::getObjectForDebug(const ObjectFile &Obj) const {
209b5c7b1ffSLang Hames return createELFDebugObject(Obj, *this);
210b5c7b1ffSLang Hames }
211b5c7b1ffSLang Hames
212083ca9bbSHans Wennborg } // anonymous namespace
213cc31af93SPreston Gurd
2144c647587SEli Bendersky namespace llvm {
2154c647587SEli Bendersky
RuntimeDyldELF(RuntimeDyld::MemoryManager & MemMgr,JITSymbolResolver & Resolver)216633fe146SLang Hames RuntimeDyldELF::RuntimeDyldELF(RuntimeDyld::MemoryManager &MemMgr,
217ad4a911fSLang Hames JITSymbolResolver &Resolver)
21802628defSKeno Fischer : RuntimeDyldImpl(MemMgr, Resolver), GOTSectionID(0), CurrentGOTIndex(0) {}
2193a3cb929SKazu Hirata RuntimeDyldELF::~RuntimeDyldELF() = default;
220b5c7b1ffSLang Hames
registerEHFrames()2217bb1344cSAndrew Kaylor void RuntimeDyldELF::registerEHFrames() {
2227bb1344cSAndrew Kaylor for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
2237bb1344cSAndrew Kaylor SID EHFrameSID = UnregisteredEHFrameSections[i];
224277776a5SSanjoy Das uint8_t *EHFrameAddr = Sections[EHFrameSID].getAddress();
225277776a5SSanjoy Das uint64_t EHFrameLoadAddr = Sections[EHFrameSID].getLoadAddress();
226277776a5SSanjoy Das size_t EHFrameSize = Sections[EHFrameSID].getSize();
227633fe146SLang Hames MemMgr.registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
228fa5942bcSRafael Espindola }
2297bb1344cSAndrew Kaylor UnregisteredEHFrameSections.clear();
230fa5942bcSRafael Espindola }
231fa5942bcSRafael Espindola
232c97cfb69SSimon Dardis std::unique_ptr<RuntimeDyldELF>
create(Triple::ArchType Arch,RuntimeDyld::MemoryManager & MemMgr,JITSymbolResolver & Resolver)233c97cfb69SSimon Dardis llvm::RuntimeDyldELF::create(Triple::ArchType Arch,
234c97cfb69SSimon Dardis RuntimeDyld::MemoryManager &MemMgr,
235c97cfb69SSimon Dardis JITSymbolResolver &Resolver) {
236c97cfb69SSimon Dardis switch (Arch) {
237c97cfb69SSimon Dardis default:
2380eaee545SJonas Devlieghere return std::make_unique<RuntimeDyldELF>(MemMgr, Resolver);
239c97cfb69SSimon Dardis case Triple::mips:
240c97cfb69SSimon Dardis case Triple::mipsel:
241c97cfb69SSimon Dardis case Triple::mips64:
242c97cfb69SSimon Dardis case Triple::mips64el:
2430eaee545SJonas Devlieghere return std::make_unique<RuntimeDyldELFMips>(MemMgr, Resolver);
244c97cfb69SSimon Dardis }
245c97cfb69SSimon Dardis }
246c97cfb69SSimon Dardis
247b5c7b1ffSLang Hames std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
loadObject(const object::ObjectFile & O)248b5c7b1ffSLang Hames RuntimeDyldELF::loadObject(const object::ObjectFile &O) {
2498959531cSLang Hames if (auto ObjSectionToIDOrErr = loadObjectImpl(O))
2500eaee545SJonas Devlieghere return std::make_unique<LoadedELFObjectInfo>(*this, *ObjSectionToIDOrErr);
2518959531cSLang Hames else {
2528959531cSLang Hames HasError = true;
2538959531cSLang Hames raw_string_ostream ErrStream(ErrorStr);
25445eb84f3SJonas Devlieghere logAllUnhandledErrors(ObjSectionToIDOrErr.takeError(), ErrStream);
2558959531cSLang Hames return nullptr;
2568959531cSLang Hames }
257173c69f2SLang Hames }
258173c69f2SLang Hames
resolveX86_64Relocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend,uint64_t SymOffset)259fb05a50fSAndrew Kaylor void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
2607608dc04SJuergen Ributzka uint64_t Offset, uint64_t Value,
2617608dc04SJuergen Ributzka uint32_t Type, int64_t Addend,
2624612fed9SAndrew Kaylor uint64_t SymOffset) {
26370d22ccbSDanil Malyshev switch (Type) {
26470d22ccbSDanil Malyshev default:
2656a3b07a4SHans Wennborg report_fatal_error("Relocation type not implemented yet!");
26670d22ccbSDanil Malyshev break;
267f47d26acSWill Dietz case ELF::R_X86_64_NONE:
268f47d26acSWill Dietz break;
269e4b40616SRafael Auler case ELF::R_X86_64_8: {
270e4b40616SRafael Auler Value += Addend;
271e4b40616SRafael Auler assert((int64_t)Value <= INT8_MAX && (int64_t)Value >= INT8_MIN);
272e4b40616SRafael Auler uint8_t TruncatedAddr = (Value & 0xFF);
273e4b40616SRafael Auler *Section.getAddressWithOffset(Offset) = TruncatedAddr;
274e4b40616SRafael Auler LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
275e4b40616SRafael Auler << format("%p\n", Section.getAddressWithOffset(Offset)));
276e4b40616SRafael Auler break;
277e4b40616SRafael Auler }
278e4b40616SRafael Auler case ELF::R_X86_64_16: {
279e4b40616SRafael Auler Value += Addend;
280e4b40616SRafael Auler assert((int64_t)Value <= INT16_MAX && (int64_t)Value >= INT16_MIN);
281e4b40616SRafael Auler uint16_t TruncatedAddr = (Value & 0xFFFF);
282e4b40616SRafael Auler support::ulittle16_t::ref(Section.getAddressWithOffset(Offset)) =
283e4b40616SRafael Auler TruncatedAddr;
284e4b40616SRafael Auler LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
285e4b40616SRafael Auler << format("%p\n", Section.getAddressWithOffset(Offset)));
286e4b40616SRafael Auler break;
287e4b40616SRafael Auler }
2884c647587SEli Bendersky case ELF::R_X86_64_64: {
289277776a5SSanjoy Das support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
290277776a5SSanjoy Das Value + Addend;
291d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
292277776a5SSanjoy Das << format("%p\n", Section.getAddressWithOffset(Offset)));
2934c647587SEli Bendersky break;
2944c647587SEli Bendersky }
2954c647587SEli Bendersky case ELF::R_X86_64_32:
2964c647587SEli Bendersky case ELF::R_X86_64_32S: {
29770d22ccbSDanil Malyshev Value += Addend;
2988e87a75bSAndrew Kaylor assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
29970d22ccbSDanil Malyshev (Type == ELF::R_X86_64_32S &&
3008e87a75bSAndrew Kaylor ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
3014c647587SEli Bendersky uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
302277776a5SSanjoy Das support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
303277776a5SSanjoy Das TruncatedAddr;
304d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
305277776a5SSanjoy Das << format("%p\n", Section.getAddressWithOffset(Offset)));
3064c647587SEli Bendersky break;
3074c647587SEli Bendersky }
30887ef5714SMaksim Panchenko case ELF::R_X86_64_PC8: {
309277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
31087ef5714SMaksim Panchenko int64_t RealOffset = Value + Addend - FinalAddress;
31187ef5714SMaksim Panchenko assert(isInt<8>(RealOffset));
31287ef5714SMaksim Panchenko int8_t TruncOffset = (RealOffset & 0xFF);
313277776a5SSanjoy Das Section.getAddress()[Offset] = TruncOffset;
31487ef5714SMaksim Panchenko break;
31587ef5714SMaksim Panchenko }
3164c647587SEli Bendersky case ELF::R_X86_64_PC32: {
317277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
31802628defSKeno Fischer int64_t RealOffset = Value + Addend - FinalAddress;
319dd9eafb6SDavid Majnemer assert(isInt<32>(RealOffset));
32070d22ccbSDanil Malyshev int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
321277776a5SSanjoy Das support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
322277776a5SSanjoy Das TruncOffset;
3234c647587SEli Bendersky break;
3244c647587SEli Bendersky }
3254612fed9SAndrew Kaylor case ELF::R_X86_64_PC64: {
326277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
32702628defSKeno Fischer int64_t RealOffset = Value + Addend - FinalAddress;
328277776a5SSanjoy Das support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
329277776a5SSanjoy Das RealOffset;
330330f65b3SReid Kleckner LLVM_DEBUG(dbgs() << "Writing " << format("%p", RealOffset) << " at "
331330f65b3SReid Kleckner << format("%p\n", FinalAddress));
332330f65b3SReid Kleckner break;
333330f65b3SReid Kleckner }
334330f65b3SReid Kleckner case ELF::R_X86_64_GOTOFF64: {
335330f65b3SReid Kleckner // Compute Value - GOTBase.
336330f65b3SReid Kleckner uint64_t GOTBase = 0;
337330f65b3SReid Kleckner for (const auto &Section : Sections) {
338330f65b3SReid Kleckner if (Section.getName() == ".got") {
339330f65b3SReid Kleckner GOTBase = Section.getLoadAddressWithOffset(0);
340330f65b3SReid Kleckner break;
341330f65b3SReid Kleckner }
342330f65b3SReid Kleckner }
343330f65b3SReid Kleckner assert(GOTBase != 0 && "missing GOT");
344330f65b3SReid Kleckner int64_t GOTOffset = Value - GOTBase + Addend;
345330f65b3SReid Kleckner support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) = GOTOffset;
3464612fed9SAndrew Kaylor break;
3474612fed9SAndrew Kaylor }
348a0a59644SMoritz Sichert case ELF::R_X86_64_DTPMOD64: {
349a0a59644SMoritz Sichert // We only have one DSO, so the module id is always 1.
350a0a59644SMoritz Sichert support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) = 1;
351a0a59644SMoritz Sichert break;
352a0a59644SMoritz Sichert }
353a0a59644SMoritz Sichert case ELF::R_X86_64_DTPOFF64:
354a0a59644SMoritz Sichert case ELF::R_X86_64_TPOFF64: {
355a0a59644SMoritz Sichert // DTPOFF64 should resolve to the offset in the TLS block, TPOFF64 to the
356a0a59644SMoritz Sichert // offset in the *initial* TLS block. Since we are statically linking, all
357a0a59644SMoritz Sichert // TLS blocks already exist in the initial block, so resolve both
358a0a59644SMoritz Sichert // relocations equally.
359a0a59644SMoritz Sichert support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
360a0a59644SMoritz Sichert Value + Addend;
361a0a59644SMoritz Sichert break;
362a0a59644SMoritz Sichert }
363a0a59644SMoritz Sichert case ELF::R_X86_64_DTPOFF32:
364a0a59644SMoritz Sichert case ELF::R_X86_64_TPOFF32: {
365a0a59644SMoritz Sichert // As for the (D)TPOFF64 relocations above, both DTPOFF32 and TPOFF32 can
366a0a59644SMoritz Sichert // be resolved equally.
367a0a59644SMoritz Sichert int64_t RealValue = Value + Addend;
368a0a59644SMoritz Sichert assert(RealValue >= INT32_MIN && RealValue <= INT32_MAX);
369a0a59644SMoritz Sichert int32_t TruncValue = RealValue;
370a0a59644SMoritz Sichert support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
371a0a59644SMoritz Sichert TruncValue;
372a0a59644SMoritz Sichert break;
373a0a59644SMoritz Sichert }
3744c647587SEli Bendersky }
3754c647587SEli Bendersky }
3764c647587SEli Bendersky
resolveX86Relocation(const SectionEntry & Section,uint64_t Offset,uint32_t Value,uint32_t Type,int32_t Addend)377fb05a50fSAndrew Kaylor void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
3787608dc04SJuergen Ributzka uint64_t Offset, uint32_t Value,
3797608dc04SJuergen Ributzka uint32_t Type, int32_t Addend) {
38070d22ccbSDanil Malyshev switch (Type) {
3814c647587SEli Bendersky case ELF::R_386_32: {
382277776a5SSanjoy Das support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
383277776a5SSanjoy Das Value + Addend;
3844c647587SEli Bendersky break;
3854c647587SEli Bendersky }
386fc16f76eSRafael Espindola // Handle R_386_PLT32 like R_386_PC32 since it should be able to
387fc16f76eSRafael Espindola // reach any 32 bit address.
388fc16f76eSRafael Espindola case ELF::R_386_PLT32:
3894c647587SEli Bendersky case ELF::R_386_PC32: {
390277776a5SSanjoy Das uint32_t FinalAddress =
391277776a5SSanjoy Das Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
392e6892c81SKeno Fischer uint32_t RealOffset = Value + Addend - FinalAddress;
393277776a5SSanjoy Das support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
394277776a5SSanjoy Das RealOffset;
3954c647587SEli Bendersky break;
3964c647587SEli Bendersky }
3974c647587SEli Bendersky default:
3984c647587SEli Bendersky // There are other relocation types, but it appears these are the
3994c647587SEli Bendersky // only ones currently used by the LLVM ELF object writer
4006a3b07a4SHans Wennborg report_fatal_error("Relocation type not implemented yet!");
40170d22ccbSDanil Malyshev break;
4024c647587SEli Bendersky }
4034c647587SEli Bendersky }
4044c647587SEli Bendersky
resolveAArch64Relocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)405fa1b2f85STim Northover void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
4067608dc04SJuergen Ributzka uint64_t Offset, uint64_t Value,
4077608dc04SJuergen Ributzka uint32_t Type, int64_t Addend) {
408277776a5SSanjoy Das uint32_t *TargetPtr =
409277776a5SSanjoy Das reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
410277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
4118f8cdd00SYichao Yu // Data should use target endian. Code should always use little endian.
4128f8cdd00SYichao Yu bool isBE = Arch == Triple::aarch64_be;
413fa1b2f85STim Northover
414d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
415277776a5SSanjoy Das << format("%llx", Section.getAddressWithOffset(Offset))
416fa1b2f85STim Northover << " FinalAddress: 0x" << format("%llx", FinalAddress)
4177608dc04SJuergen Ributzka << " Value: 0x" << format("%llx", Value) << " Type: 0x"
418d34e60caSNicola Zaghen << format("%x", Type) << " Addend: 0x"
419d34e60caSNicola Zaghen << format("%llx", Addend) << "\n");
420fa1b2f85STim Northover
421fa1b2f85STim Northover switch (Type) {
422fa1b2f85STim Northover default:
4236a3b07a4SHans Wennborg report_fatal_error("Relocation type not implemented yet!");
424fa1b2f85STim Northover break;
4256b22c370SVladislav Khmelevsky case ELF::R_AARCH64_NONE:
4266b22c370SVladislav Khmelevsky break;
427562630a1SSaleem Abdulrasool case ELF::R_AARCH64_ABS16: {
428562630a1SSaleem Abdulrasool uint64_t Result = Value + Addend;
429562630a1SSaleem Abdulrasool assert(static_cast<int64_t>(Result) >= INT16_MIN && Result < UINT16_MAX);
430562630a1SSaleem Abdulrasool write(isBE, TargetPtr, static_cast<uint16_t>(Result & 0xffffU));
431562630a1SSaleem Abdulrasool break;
432562630a1SSaleem Abdulrasool }
433562630a1SSaleem Abdulrasool case ELF::R_AARCH64_ABS32: {
434562630a1SSaleem Abdulrasool uint64_t Result = Value + Addend;
435562630a1SSaleem Abdulrasool assert(static_cast<int64_t>(Result) >= INT32_MIN && Result < UINT32_MAX);
436562630a1SSaleem Abdulrasool write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
437562630a1SSaleem Abdulrasool break;
438562630a1SSaleem Abdulrasool }
4395240a305SEugene Leviant case ELF::R_AARCH64_ABS64:
4405240a305SEugene Leviant write(isBE, TargetPtr, Value + Addend);
441b23d8dbbSTim Northover break;
4426adc664bSLeonard Chan case ELF::R_AARCH64_PLT32: {
4436adc664bSLeonard Chan uint64_t Result = Value + Addend - FinalAddress;
4446adc664bSLeonard Chan assert(static_cast<int64_t>(Result) >= INT32_MIN &&
4456adc664bSLeonard Chan static_cast<int64_t>(Result) <= INT32_MAX);
4466adc664bSLeonard Chan write(isBE, TargetPtr, static_cast<uint32_t>(Result));
4476adc664bSLeonard Chan break;
4486adc664bSLeonard Chan }
44948e894a5SAlexey Moksyakov case ELF::R_AARCH64_PREL16: {
45048e894a5SAlexey Moksyakov uint64_t Result = Value + Addend - FinalAddress;
45148e894a5SAlexey Moksyakov assert(static_cast<int64_t>(Result) >= INT16_MIN &&
45248e894a5SAlexey Moksyakov static_cast<int64_t>(Result) <= UINT16_MAX);
45348e894a5SAlexey Moksyakov write(isBE, TargetPtr, static_cast<uint16_t>(Result & 0xffffU));
45448e894a5SAlexey Moksyakov break;
45548e894a5SAlexey Moksyakov }
4565959ea39STim Northover case ELF::R_AARCH64_PREL32: {
457fa1b2f85STim Northover uint64_t Result = Value + Addend - FinalAddress;
458fa1b2f85STim Northover assert(static_cast<int64_t>(Result) >= INT32_MIN &&
459fa1b2f85STim Northover static_cast<int64_t>(Result) <= UINT32_MAX);
4605240a305SEugene Leviant write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
461fa1b2f85STim Northover break;
462fa1b2f85STim Northover }
4638e32aebeSEugene Leviant case ELF::R_AARCH64_PREL64:
4648e32aebeSEugene Leviant write(isBE, TargetPtr, Value + Addend - FinalAddress);
4658e32aebeSEugene Leviant break;
466e4b40616SRafael Auler case ELF::R_AARCH64_CONDBR19: {
467e4b40616SRafael Auler uint64_t BranchImm = Value + Addend - FinalAddress;
468e4b40616SRafael Auler
469e4b40616SRafael Auler assert(isInt<21>(BranchImm));
470e4b40616SRafael Auler *TargetPtr &= 0xff00001fU;
471e4b40616SRafael Auler // Immediate:20:2 goes in bits 23:5 of Bcc, CBZ, CBNZ
472e4b40616SRafael Auler or32le(TargetPtr, (BranchImm & 0x001FFFFC) << 3);
473e4b40616SRafael Auler break;
474e4b40616SRafael Auler }
475e4b40616SRafael Auler case ELF::R_AARCH64_TSTBR14: {
476e4b40616SRafael Auler uint64_t BranchImm = Value + Addend - FinalAddress;
477e4b40616SRafael Auler
478e4b40616SRafael Auler assert(isInt<16>(BranchImm));
479e4b40616SRafael Auler
480e4b40616SRafael Auler *TargetPtr &= 0xfff8001fU;
481e4b40616SRafael Auler // Immediate:15:2 goes in bits 18:5 of TBZ, TBNZ
482*b27d6ffeSVladislav Khmelevsky or32le(TargetPtr, (BranchImm & 0x0000FFFC) << 3);
483e4b40616SRafael Auler break;
484e4b40616SRafael Auler }
48537cde975STim Northover case ELF::R_AARCH64_CALL26: // fallthrough
48637cde975STim Northover case ELF::R_AARCH64_JUMP26: {
48737cde975STim Northover // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
48837cde975STim Northover // calculation.
48937cde975STim Northover uint64_t BranchImm = Value + Addend - FinalAddress;
49037cde975STim Northover
49137cde975STim Northover // "Check that -2^27 <= result < 2^27".
492dd9eafb6SDavid Majnemer assert(isInt<28>(BranchImm));
4935240a305SEugene Leviant or32le(TargetPtr, (BranchImm & 0x0FFFFFFC) >> 2);
49437cde975STim Northover break;
49537cde975STim Northover }
4965240a305SEugene Leviant case ELF::R_AARCH64_MOVW_UABS_G3:
4975240a305SEugene Leviant or32le(TargetPtr, ((Value + Addend) & 0xFFFF000000000000) >> 43);
4984d01c1e0STim Northover break;
4995240a305SEugene Leviant case ELF::R_AARCH64_MOVW_UABS_G2_NC:
5005240a305SEugene Leviant or32le(TargetPtr, ((Value + Addend) & 0xFFFF00000000) >> 27);
5014d01c1e0STim Northover break;
5025240a305SEugene Leviant case ELF::R_AARCH64_MOVW_UABS_G1_NC:
5035240a305SEugene Leviant or32le(TargetPtr, ((Value + Addend) & 0xFFFF0000) >> 11);
5044d01c1e0STim Northover break;
5055240a305SEugene Leviant case ELF::R_AARCH64_MOVW_UABS_G0_NC:
5065240a305SEugene Leviant or32le(TargetPtr, ((Value + Addend) & 0xFFFF) << 5);
5074d01c1e0STim Northover break;
5089d808497SBradley Smith case ELF::R_AARCH64_ADR_PREL_PG_HI21: {
5099d808497SBradley Smith // Operation: Page(S+A) - Page(P)
5107608dc04SJuergen Ributzka uint64_t Result =
5117608dc04SJuergen Ributzka ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL);
5129d808497SBradley Smith
5139d808497SBradley Smith // Check that -2^32 <= X < 2^32
514dd9eafb6SDavid Majnemer assert(isInt<33>(Result) && "overflow check failed for relocation");
5159d808497SBradley Smith
5169d808497SBradley Smith // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken
5179d808497SBradley Smith // from bits 32:12 of X.
5185240a305SEugene Leviant write32AArch64Addr(TargetPtr, Result >> 12);
5199d808497SBradley Smith break;
5209d808497SBradley Smith }
5215240a305SEugene Leviant case ELF::R_AARCH64_ADD_ABS_LO12_NC:
52292090835SEugene Leviant // Operation: S + A
52392090835SEugene Leviant // Immediate goes in bits 21:10 of LD/ST instruction, taken
52492090835SEugene Leviant // from bits 11:0 of X
5255240a305SEugene Leviant or32AArch64Imm(TargetPtr, Value + Addend);
52692090835SEugene Leviant break;
527e33d2ce8SEugene Leviant case ELF::R_AARCH64_LDST8_ABS_LO12_NC:
528e33d2ce8SEugene Leviant // Operation: S + A
529e33d2ce8SEugene Leviant // Immediate goes in bits 21:10 of LD/ST instruction, taken
530e33d2ce8SEugene Leviant // from bits 11:0 of X
531e33d2ce8SEugene Leviant or32AArch64Imm(TargetPtr, getBits(Value + Addend, 0, 11));
532e33d2ce8SEugene Leviant break;
533e33d2ce8SEugene Leviant case ELF::R_AARCH64_LDST16_ABS_LO12_NC:
534e33d2ce8SEugene Leviant // Operation: S + A
535e33d2ce8SEugene Leviant // Immediate goes in bits 21:10 of LD/ST instruction, taken
536e33d2ce8SEugene Leviant // from bits 11:1 of X
537e33d2ce8SEugene Leviant or32AArch64Imm(TargetPtr, getBits(Value + Addend, 1, 11));
538e33d2ce8SEugene Leviant break;
5395240a305SEugene Leviant case ELF::R_AARCH64_LDST32_ABS_LO12_NC:
5409d808497SBradley Smith // Operation: S + A
5419d808497SBradley Smith // Immediate goes in bits 21:10 of LD/ST instruction, taken
5429d808497SBradley Smith // from bits 11:2 of X
5435240a305SEugene Leviant or32AArch64Imm(TargetPtr, getBits(Value + Addend, 2, 11));
5449d808497SBradley Smith break;
5455240a305SEugene Leviant case ELF::R_AARCH64_LDST64_ABS_LO12_NC:
5469d808497SBradley Smith // Operation: S + A
5479d808497SBradley Smith // Immediate goes in bits 21:10 of LD/ST instruction, taken
5489d808497SBradley Smith // from bits 11:3 of X
5495240a305SEugene Leviant or32AArch64Imm(TargetPtr, getBits(Value + Addend, 3, 11));
5509d808497SBradley Smith break;
551beb17cc8SEugene Leviant case ELF::R_AARCH64_LDST128_ABS_LO12_NC:
552beb17cc8SEugene Leviant // Operation: S + A
553beb17cc8SEugene Leviant // Immediate goes in bits 21:10 of LD/ST instruction, taken
554beb17cc8SEugene Leviant // from bits 11:4 of X
555beb17cc8SEugene Leviant or32AArch64Imm(TargetPtr, getBits(Value + Addend, 4, 11));
556beb17cc8SEugene Leviant break;
557e4b40616SRafael Auler case ELF::R_AARCH64_LD_PREL_LO19: {
558e4b40616SRafael Auler // Operation: S + A - P
559e4b40616SRafael Auler uint64_t Result = Value + Addend - FinalAddress;
560e4b40616SRafael Auler
561e4b40616SRafael Auler // "Check that -2^20 <= result < 2^20".
562e4b40616SRafael Auler assert(isInt<21>(Result));
563e4b40616SRafael Auler
564e4b40616SRafael Auler *TargetPtr &= 0xff00001fU;
565e4b40616SRafael Auler // Immediate goes in bits 23:5 of LD imm instruction, taken
566e4b40616SRafael Auler // from bits 20:2 of X
567e4b40616SRafael Auler *TargetPtr |= ((Result & 0xffc) << (5 - 2));
568e4b40616SRafael Auler break;
569e4b40616SRafael Auler }
570e4b40616SRafael Auler case ELF::R_AARCH64_ADR_PREL_LO21: {
571e4b40616SRafael Auler // Operation: S + A - P
572e4b40616SRafael Auler uint64_t Result = Value + Addend - FinalAddress;
573e4b40616SRafael Auler
574e4b40616SRafael Auler // "Check that -2^20 <= result < 2^20".
575e4b40616SRafael Auler assert(isInt<21>(Result));
576e4b40616SRafael Auler
577e4b40616SRafael Auler *TargetPtr &= 0x9f00001fU;
578e4b40616SRafael Auler // Immediate goes in bits 23:5, 30:29 of ADR imm instruction, taken
579e4b40616SRafael Auler // from bits 20:0 of X
580e4b40616SRafael Auler *TargetPtr |= ((Result & 0xffc) << (5 - 2));
581e4b40616SRafael Auler *TargetPtr |= (Result & 0x3) << 29;
582e4b40616SRafael Auler break;
583e4b40616SRafael Auler }
5849d808497SBradley Smith }
585fa1b2f85STim Northover }
586fa1b2f85STim Northover
resolveARMRelocation(const SectionEntry & Section,uint64_t Offset,uint32_t Value,uint32_t Type,int32_t Addend)587fb05a50fSAndrew Kaylor void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
5887608dc04SJuergen Ributzka uint64_t Offset, uint32_t Value,
5897608dc04SJuergen Ributzka uint32_t Type, int32_t Addend) {
59070d22ccbSDanil Malyshev // TODO: Add Thumb relocations.
591277776a5SSanjoy Das uint32_t *TargetPtr =
592277776a5SSanjoy Das reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
593277776a5SSanjoy Das uint32_t FinalAddress = Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
59470d22ccbSDanil Malyshev Value += Addend;
59570d22ccbSDanil Malyshev
596d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
597277776a5SSanjoy Das << Section.getAddressWithOffset(Offset)
598d34e60caSNicola Zaghen << " FinalAddress: " << format("%p", FinalAddress)
599d34e60caSNicola Zaghen << " Value: " << format("%x", Value)
600d34e60caSNicola Zaghen << " Type: " << format("%x", Type)
6017608dc04SJuergen Ributzka << " Addend: " << format("%x", Addend) << "\n");
60270d22ccbSDanil Malyshev
60370d22ccbSDanil Malyshev switch (Type) {
60470d22ccbSDanil Malyshev default:
60570d22ccbSDanil Malyshev llvm_unreachable("Not implemented relocation type!");
60670d22ccbSDanil Malyshev
6078cea6e8fSRenato Golin case ELF::R_ARM_NONE:
6088cea6e8fSRenato Golin break;
609c32ffe39SKeno Fischer // Write a 31bit signed offset
6108cea6e8fSRenato Golin case ELF::R_ARM_PREL31:
611b04df8eaSKeno Fischer support::ulittle32_t::ref{TargetPtr} =
612b04df8eaSKeno Fischer (support::ulittle32_t::ref{TargetPtr} & 0x80000000) |
613b04df8eaSKeno Fischer ((Value - FinalAddress) & ~0x80000000);
614c32ffe39SKeno Fischer break;
615c958bf30SAmara Emerson case ELF::R_ARM_TARGET1:
61670d22ccbSDanil Malyshev case ELF::R_ARM_ABS32:
617b04df8eaSKeno Fischer support::ulittle32_t::ref{TargetPtr} = Value;
61870d22ccbSDanil Malyshev break;
61970d22ccbSDanil Malyshev // Write first 16 bit of 32 bit value to the mov instruction.
62070d22ccbSDanil Malyshev // Last 4 bit should be shifted.
62170d22ccbSDanil Malyshev case ELF::R_ARM_MOVW_ABS_NC:
6223b8f3ad7SPavel Labath case ELF::R_ARM_MOVT_ABS:
623e6892c81SKeno Fischer if (Type == ELF::R_ARM_MOVW_ABS_NC)
624e6892c81SKeno Fischer Value = Value & 0xFFFF;
625e6892c81SKeno Fischer else if (Type == ELF::R_ARM_MOVT_ABS)
62670d22ccbSDanil Malyshev Value = (Value >> 16) & 0xFFFF;
627b04df8eaSKeno Fischer support::ulittle32_t::ref{TargetPtr} =
628b04df8eaSKeno Fischer (support::ulittle32_t::ref{TargetPtr} & ~0x000F0FFF) | (Value & 0xFFF) |
629b04df8eaSKeno Fischer (((Value >> 12) & 0xF) << 16);
63070d22ccbSDanil Malyshev break;
63170d22ccbSDanil Malyshev // Write 24 bit relative value to the branch instruction.
63270d22ccbSDanil Malyshev case ELF::R_ARM_PC24: // Fall through.
63370d22ccbSDanil Malyshev case ELF::R_ARM_CALL: // Fall through.
634e6892c81SKeno Fischer case ELF::R_ARM_JUMP24:
63570d22ccbSDanil Malyshev int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
63670d22ccbSDanil Malyshev RelValue = (RelValue & 0x03FFFFFC) >> 2;
637b04df8eaSKeno Fischer assert((support::ulittle32_t::ref{TargetPtr} & 0xFFFFFF) == 0xFFFFFE);
638b04df8eaSKeno Fischer support::ulittle32_t::ref{TargetPtr} =
639b04df8eaSKeno Fischer (support::ulittle32_t::ref{TargetPtr} & 0xFF000000) | RelValue;
64070d22ccbSDanil Malyshev break;
64170d22ccbSDanil Malyshev }
6424c647587SEli Bendersky }
6434c647587SEli Bendersky
setMipsABI(const ObjectFile & Obj)6449720283eSPetar Jovanovic void RuntimeDyldELF::setMipsABI(const ObjectFile &Obj) {
645a38e1982SAlexei Starovoitov if (Arch == Triple::UnknownArch ||
646a38e1982SAlexei Starovoitov !StringRef(Triple::getArchTypePrefix(Arch)).equals("mips")) {
6479720283eSPetar Jovanovic IsMipsO32ABI = false;
648226752c1SSimon Dardis IsMipsN32ABI = false;
6499720283eSPetar Jovanovic IsMipsN64ABI = false;
6509720283eSPetar Jovanovic return;
6519720283eSPetar Jovanovic }
652d5f76ad3SRafael Espindola if (auto *E = dyn_cast<ELFObjectFileBase>(&Obj)) {
653d5f76ad3SRafael Espindola unsigned AbiVariant = E->getPlatformFlags();
6549720283eSPetar Jovanovic IsMipsO32ABI = AbiVariant & ELF::EF_MIPS_ABI_O32;
655226752c1SSimon Dardis IsMipsN32ABI = AbiVariant & ELF::EF_MIPS_ABI2;
656d5f76ad3SRafael Espindola }
657536ba637SFangrui Song IsMipsN64ABI = Obj.getFileFormatName().equals("elf64-mips");
6589720283eSPetar Jovanovic }
6599720283eSPetar Jovanovic
6608f1f87c7SUlrich Weigand // Return the .TOC. section and offset.
findPPC64TOCSection(const ELFObjectFileBase & Obj,ObjSectionToIDMap & LocalSections,RelocationValueRef & Rel)6618959531cSLang Hames Error RuntimeDyldELF::findPPC64TOCSection(const ELFObjectFileBase &Obj,
6628f1f87c7SUlrich Weigand ObjSectionToIDMap &LocalSections,
6638f1f87c7SUlrich Weigand RelocationValueRef &Rel) {
6648f1f87c7SUlrich Weigand // Set a default SectionID in case we do not find a TOC section below.
6658f1f87c7SUlrich Weigand // This may happen for references to TOC base base (sym@toc, .odp
6668f1f87c7SUlrich Weigand // relocation) without a .toc directive. In this case just use the
6678f1f87c7SUlrich Weigand // first section (which is usually the .odp) since the code won't
6688f1f87c7SUlrich Weigand // reference the .toc base directly.
669083ca9bbSHans Wennborg Rel.SymbolName = nullptr;
6708f1f87c7SUlrich Weigand Rel.SectionID = 0;
6718f1f87c7SUlrich Weigand
6725fc11b35SAdhemerval Zanella // The TOC consists of sections .got, .toc, .tocbss, .plt in that
6735fc11b35SAdhemerval Zanella // order. The TOC starts where the first of these sections starts.
6742e9df17aSDavide Italiano for (auto &Section : Obj.sections()) {
675bcc00e1aSGeorge Rimar Expected<StringRef> NameOrErr = Section.getName();
676bcc00e1aSGeorge Rimar if (!NameOrErr)
677bcc00e1aSGeorge Rimar return NameOrErr.takeError();
678bcc00e1aSGeorge Rimar StringRef SectionName = *NameOrErr;
6798f1f87c7SUlrich Weigand
6808f1f87c7SUlrich Weigand if (SectionName == ".got"
6818f1f87c7SUlrich Weigand || SectionName == ".toc"
6828f1f87c7SUlrich Weigand || SectionName == ".tocbss"
6838f1f87c7SUlrich Weigand || SectionName == ".plt") {
6848959531cSLang Hames if (auto SectionIDOrErr =
6858959531cSLang Hames findOrEmitSection(Obj, Section, false, LocalSections))
6868959531cSLang Hames Rel.SectionID = *SectionIDOrErr;
6878959531cSLang Hames else
6888959531cSLang Hames return SectionIDOrErr.takeError();
6895fc11b35SAdhemerval Zanella break;
6905fc11b35SAdhemerval Zanella }
6915fc11b35SAdhemerval Zanella }
6928f1f87c7SUlrich Weigand
6935fc11b35SAdhemerval Zanella // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
6945fc11b35SAdhemerval Zanella // thus permitting a full 64 Kbytes segment.
6958f1f87c7SUlrich Weigand Rel.Addend = 0x8000;
6968959531cSLang Hames
6978959531cSLang Hames return Error::success();
6985fc11b35SAdhemerval Zanella }
6995fc11b35SAdhemerval Zanella
7005fc11b35SAdhemerval Zanella // Returns the sections and offset associated with the ODP entry referenced
7015fc11b35SAdhemerval Zanella // by Symbol.
findOPDEntrySection(const ELFObjectFileBase & Obj,ObjSectionToIDMap & LocalSections,RelocationValueRef & Rel)7028959531cSLang Hames Error RuntimeDyldELF::findOPDEntrySection(const ELFObjectFileBase &Obj,
7035fc11b35SAdhemerval Zanella ObjSectionToIDMap &LocalSections,
7045fc11b35SAdhemerval Zanella RelocationValueRef &Rel) {
7055fc11b35SAdhemerval Zanella // Get the ELF symbol value (st_value) to compare with Relocation offset in
7065fc11b35SAdhemerval Zanella // .opd entries
707b5c7b1ffSLang Hames for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
7085e812afaSRafael Espindola si != se; ++si) {
7092bf01dcbSGeorge Rimar
7102bf01dcbSGeorge Rimar Expected<section_iterator> RelSecOrErr = si->getRelocatedSection();
7112bf01dcbSGeorge Rimar if (!RelSecOrErr)
71221661607SSimon Pilgrim report_fatal_error(Twine(toString(RelSecOrErr.takeError())));
7132bf01dcbSGeorge Rimar
7142bf01dcbSGeorge Rimar section_iterator RelSecI = *RelSecOrErr;
715b5c7b1ffSLang Hames if (RelSecI == Obj.section_end())
716a61f1e97SRafael Espindola continue;
717a61f1e97SRafael Espindola
718bcc00e1aSGeorge Rimar Expected<StringRef> NameOrErr = RelSecI->getName();
719bcc00e1aSGeorge Rimar if (!NameOrErr)
720bcc00e1aSGeorge Rimar return NameOrErr.takeError();
721bcc00e1aSGeorge Rimar StringRef RelSectionName = *NameOrErr;
7228959531cSLang Hames
723a61f1e97SRafael Espindola if (RelSectionName != ".opd")
7245fc11b35SAdhemerval Zanella continue;
7255fc11b35SAdhemerval Zanella
72671784d61SRafael Espindola for (elf_relocation_iterator i = si->relocation_begin(),
7277608dc04SJuergen Ributzka e = si->relocation_end();
7287608dc04SJuergen Ributzka i != e;) {
7295fc11b35SAdhemerval Zanella // The R_PPC64_ADDR64 relocation indicates the first field
7305fc11b35SAdhemerval Zanella // of a .opd entry
73199c041b7SRafael Espindola uint64_t TypeFunc = i->getType();
7325fc11b35SAdhemerval Zanella if (TypeFunc != ELF::R_PPC64_ADDR64) {
7335e812afaSRafael Espindola ++i;
7345fc11b35SAdhemerval Zanella continue;
7355fc11b35SAdhemerval Zanella }
7365fc11b35SAdhemerval Zanella
73796d071cdSRafael Espindola uint64_t TargetSymbolOffset = i->getOffset();
738806f0064SRafael Espindola symbol_iterator TargetSymbol = i->getSymbol();
7398959531cSLang Hames int64_t Addend;
7408959531cSLang Hames if (auto AddendOrErr = i->getAddend())
7418959531cSLang Hames Addend = *AddendOrErr;
7428959531cSLang Hames else
7431a0e5a19SRafael Espindola return AddendOrErr.takeError();
7445fc11b35SAdhemerval Zanella
7455e812afaSRafael Espindola ++i;
7465fc11b35SAdhemerval Zanella if (i == e)
7475fc11b35SAdhemerval Zanella break;
7485fc11b35SAdhemerval Zanella
7495fc11b35SAdhemerval Zanella // Just check if following relocation is a R_PPC64_TOC
75099c041b7SRafael Espindola uint64_t TypeTOC = i->getType();
7515fc11b35SAdhemerval Zanella if (TypeTOC != ELF::R_PPC64_TOC)
7525fc11b35SAdhemerval Zanella continue;
7535fc11b35SAdhemerval Zanella
7545fc11b35SAdhemerval Zanella // Finally compares the Symbol value and the target symbol offset
7555fc11b35SAdhemerval Zanella // to check if this .opd entry refers to the symbol the relocation
7565fc11b35SAdhemerval Zanella // points to.
7574612fed9SAndrew Kaylor if (Rel.Addend != (int64_t)TargetSymbolOffset)
7585fc11b35SAdhemerval Zanella continue;
7595fc11b35SAdhemerval Zanella
7608959531cSLang Hames section_iterator TSI = Obj.section_end();
7618959531cSLang Hames if (auto TSIOrErr = TargetSymbol->getSection())
7628959531cSLang Hames TSI = *TSIOrErr;
7638959531cSLang Hames else
7647bd8d994SKevin Enderby return TSIOrErr.takeError();
7658959531cSLang Hames assert(TSI != Obj.section_end() && "TSI should refer to a valid section");
7668959531cSLang Hames
7678959531cSLang Hames bool IsCode = TSI->isText();
7688959531cSLang Hames if (auto SectionIDOrErr = findOrEmitSection(Obj, *TSI, IsCode,
7698959531cSLang Hames LocalSections))
7708959531cSLang Hames Rel.SectionID = *SectionIDOrErr;
7718959531cSLang Hames else
7728959531cSLang Hames return SectionIDOrErr.takeError();
7730d15f731SRafael Espindola Rel.Addend = (intptr_t)Addend;
7748959531cSLang Hames return Error::success();
7755fc11b35SAdhemerval Zanella }
7765fc11b35SAdhemerval Zanella }
7775fc11b35SAdhemerval Zanella llvm_unreachable("Attempting to get address of ODP entry!");
7785fc11b35SAdhemerval Zanella }
7795fc11b35SAdhemerval Zanella
780dbc8e1aeSUlrich Weigand // Relocation masks following the #lo(value), #hi(value), #ha(value),
781dbc8e1aeSUlrich Weigand // #higher(value), #highera(value), #highest(value), and #highesta(value)
782dbc8e1aeSUlrich Weigand // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
783dbc8e1aeSUlrich Weigand // document.
784dbc8e1aeSUlrich Weigand
applyPPClo(uint64_t value)7857608dc04SJuergen Ributzka static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
7865fc11b35SAdhemerval Zanella
applyPPChi(uint64_t value)7877608dc04SJuergen Ributzka static inline uint16_t applyPPChi(uint64_t value) {
7885fc11b35SAdhemerval Zanella return (value >> 16) & 0xffff;
7895fc11b35SAdhemerval Zanella }
7905fc11b35SAdhemerval Zanella
applyPPCha(uint64_t value)791dbc8e1aeSUlrich Weigand static inline uint16_t applyPPCha (uint64_t value) {
792dbc8e1aeSUlrich Weigand return ((value + 0x8000) >> 16) & 0xffff;
793dbc8e1aeSUlrich Weigand }
794dbc8e1aeSUlrich Weigand
applyPPChigher(uint64_t value)7957608dc04SJuergen Ributzka static inline uint16_t applyPPChigher(uint64_t value) {
7965fc11b35SAdhemerval Zanella return (value >> 32) & 0xffff;
7975fc11b35SAdhemerval Zanella }
7985fc11b35SAdhemerval Zanella
applyPPChighera(uint64_t value)799dbc8e1aeSUlrich Weigand static inline uint16_t applyPPChighera (uint64_t value) {
800dbc8e1aeSUlrich Weigand return ((value + 0x8000) >> 32) & 0xffff;
801dbc8e1aeSUlrich Weigand }
802dbc8e1aeSUlrich Weigand
applyPPChighest(uint64_t value)8037608dc04SJuergen Ributzka static inline uint16_t applyPPChighest(uint64_t value) {
8045fc11b35SAdhemerval Zanella return (value >> 48) & 0xffff;
8055fc11b35SAdhemerval Zanella }
8065fc11b35SAdhemerval Zanella
applyPPChighesta(uint64_t value)807dbc8e1aeSUlrich Weigand static inline uint16_t applyPPChighesta (uint64_t value) {
808dbc8e1aeSUlrich Weigand return ((value + 0x8000) >> 48) & 0xffff;
809dbc8e1aeSUlrich Weigand }
810dbc8e1aeSUlrich Weigand
resolvePPC32Relocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)81123cdeeeaSHal Finkel void RuntimeDyldELF::resolvePPC32Relocation(const SectionEntry &Section,
81223cdeeeaSHal Finkel uint64_t Offset, uint64_t Value,
81323cdeeeaSHal Finkel uint32_t Type, int64_t Addend) {
814277776a5SSanjoy Das uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
81523cdeeeaSHal Finkel switch (Type) {
81623cdeeeaSHal Finkel default:
8176a3b07a4SHans Wennborg report_fatal_error("Relocation type not implemented yet!");
81823cdeeeaSHal Finkel break;
81923cdeeeaSHal Finkel case ELF::R_PPC_ADDR16_LO:
82023cdeeeaSHal Finkel writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
82123cdeeeaSHal Finkel break;
82223cdeeeaSHal Finkel case ELF::R_PPC_ADDR16_HI:
82323cdeeeaSHal Finkel writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
82423cdeeeaSHal Finkel break;
82523cdeeeaSHal Finkel case ELF::R_PPC_ADDR16_HA:
82623cdeeeaSHal Finkel writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
82723cdeeeaSHal Finkel break;
82823cdeeeaSHal Finkel }
82923cdeeeaSHal Finkel }
83023cdeeeaSHal Finkel
resolvePPC64Relocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)831fb05a50fSAndrew Kaylor void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
8327608dc04SJuergen Ributzka uint64_t Offset, uint64_t Value,
8337608dc04SJuergen Ributzka uint32_t Type, int64_t Addend) {
834277776a5SSanjoy Das uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
8355fc11b35SAdhemerval Zanella switch (Type) {
8365fc11b35SAdhemerval Zanella default:
8376a3b07a4SHans Wennborg report_fatal_error("Relocation type not implemented yet!");
8385fc11b35SAdhemerval Zanella break;
839dbc8e1aeSUlrich Weigand case ELF::R_PPC64_ADDR16:
840dbc8e1aeSUlrich Weigand writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
841dbc8e1aeSUlrich Weigand break;
842dbc8e1aeSUlrich Weigand case ELF::R_PPC64_ADDR16_DS:
843dbc8e1aeSUlrich Weigand writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
844dbc8e1aeSUlrich Weigand break;
8455fc11b35SAdhemerval Zanella case ELF::R_PPC64_ADDR16_LO:
8465fc11b35SAdhemerval Zanella writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
8475fc11b35SAdhemerval Zanella break;
848dbc8e1aeSUlrich Weigand case ELF::R_PPC64_ADDR16_LO_DS:
849dbc8e1aeSUlrich Weigand writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
850dbc8e1aeSUlrich Weigand break;
8515fc11b35SAdhemerval Zanella case ELF::R_PPC64_ADDR16_HI:
85280b8f82fSSean Fertile case ELF::R_PPC64_ADDR16_HIGH:
8535fc11b35SAdhemerval Zanella writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
8545fc11b35SAdhemerval Zanella break;
855dbc8e1aeSUlrich Weigand case ELF::R_PPC64_ADDR16_HA:
85680b8f82fSSean Fertile case ELF::R_PPC64_ADDR16_HIGHA:
857dbc8e1aeSUlrich Weigand writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
858dbc8e1aeSUlrich Weigand break;
8595fc11b35SAdhemerval Zanella case ELF::R_PPC64_ADDR16_HIGHER:
8605fc11b35SAdhemerval Zanella writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
8615fc11b35SAdhemerval Zanella break;
862dbc8e1aeSUlrich Weigand case ELF::R_PPC64_ADDR16_HIGHERA:
863dbc8e1aeSUlrich Weigand writeInt16BE(LocalAddress, applyPPChighera(Value + Addend));
864dbc8e1aeSUlrich Weigand break;
8655fc11b35SAdhemerval Zanella case ELF::R_PPC64_ADDR16_HIGHEST:
8665fc11b35SAdhemerval Zanella writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
8675fc11b35SAdhemerval Zanella break;
868dbc8e1aeSUlrich Weigand case ELF::R_PPC64_ADDR16_HIGHESTA:
869dbc8e1aeSUlrich Weigand writeInt16BE(LocalAddress, applyPPChighesta(Value + Addend));
870dbc8e1aeSUlrich Weigand break;
8715fc11b35SAdhemerval Zanella case ELF::R_PPC64_ADDR14: {
8725fc11b35SAdhemerval Zanella assert(((Value + Addend) & 3) == 0);
8735fc11b35SAdhemerval Zanella // Preserve the AA/LK bits in the branch instruction
8745fc11b35SAdhemerval Zanella uint8_t aalk = *(LocalAddress + 3);
8755fc11b35SAdhemerval Zanella writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
8765fc11b35SAdhemerval Zanella } break;
877dbc8e1aeSUlrich Weigand case ELF::R_PPC64_REL16_LO: {
878277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
879dbc8e1aeSUlrich Weigand uint64_t Delta = Value - FinalAddress + Addend;
880dbc8e1aeSUlrich Weigand writeInt16BE(LocalAddress, applyPPClo(Delta));
881dbc8e1aeSUlrich Weigand } break;
882dbc8e1aeSUlrich Weigand case ELF::R_PPC64_REL16_HI: {
883277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
884dbc8e1aeSUlrich Weigand uint64_t Delta = Value - FinalAddress + Addend;
885dbc8e1aeSUlrich Weigand writeInt16BE(LocalAddress, applyPPChi(Delta));
886dbc8e1aeSUlrich Weigand } break;
887dbc8e1aeSUlrich Weigand case ELF::R_PPC64_REL16_HA: {
888277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
889dbc8e1aeSUlrich Weigand uint64_t Delta = Value - FinalAddress + Addend;
890dbc8e1aeSUlrich Weigand writeInt16BE(LocalAddress, applyPPCha(Delta));
891dbc8e1aeSUlrich Weigand } break;
8929b0b7813SAdhemerval Zanella case ELF::R_PPC64_ADDR32: {
893b6d40cceSUlrich Weigand int64_t Result = static_cast<int64_t>(Value + Addend);
894b6d40cceSUlrich Weigand if (SignExtend64<32>(Result) != Result)
8951ae2248eSAdhemerval Zanella llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
8969b0b7813SAdhemerval Zanella writeInt32BE(LocalAddress, Result);
8979b0b7813SAdhemerval Zanella } break;
8985fc11b35SAdhemerval Zanella case ELF::R_PPC64_REL24: {
899277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
900b6d40cceSUlrich Weigand int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
901b6d40cceSUlrich Weigand if (SignExtend64<26>(delta) != delta)
9025fc11b35SAdhemerval Zanella llvm_unreachable("Relocation R_PPC64_REL24 overflow");
9033872c6c6SHiroshi Inoue // We preserve bits other than LI field, i.e. PO and AA/LK fields.
9043872c6c6SHiroshi Inoue uint32_t Inst = readBytesUnaligned(LocalAddress, 4);
9053872c6c6SHiroshi Inoue writeInt32BE(LocalAddress, (Inst & 0xFC000003) | (delta & 0x03FFFFFC));
9065fc11b35SAdhemerval Zanella } break;
9071ae2248eSAdhemerval Zanella case ELF::R_PPC64_REL32: {
908277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
909b6d40cceSUlrich Weigand int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
910b6d40cceSUlrich Weigand if (SignExtend64<32>(delta) != delta)
9111ae2248eSAdhemerval Zanella llvm_unreachable("Relocation R_PPC64_REL32 overflow");
9121ae2248eSAdhemerval Zanella writeInt32BE(LocalAddress, delta);
9131ae2248eSAdhemerval Zanella } break;
914e8bd03daSAdhemerval Zanella case ELF::R_PPC64_REL64: {
915277776a5SSanjoy Das uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
916e8bd03daSAdhemerval Zanella uint64_t Delta = Value - FinalAddress + Addend;
917e8bd03daSAdhemerval Zanella writeInt64BE(LocalAddress, Delta);
918e8bd03daSAdhemerval Zanella } break;
9195fc11b35SAdhemerval Zanella case ELF::R_PPC64_ADDR64:
9205fc11b35SAdhemerval Zanella writeInt64BE(LocalAddress, Value + Addend);
9215fc11b35SAdhemerval Zanella break;
9225fc11b35SAdhemerval Zanella }
9235fc11b35SAdhemerval Zanella }
9245fc11b35SAdhemerval Zanella
resolveSystemZRelocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)925ca044082SRichard Sandiford void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
9267608dc04SJuergen Ributzka uint64_t Offset, uint64_t Value,
9277608dc04SJuergen Ributzka uint32_t Type, int64_t Addend) {
928277776a5SSanjoy Das uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
929ca044082SRichard Sandiford switch (Type) {
930ca044082SRichard Sandiford default:
9316a3b07a4SHans Wennborg report_fatal_error("Relocation type not implemented yet!");
932ca044082SRichard Sandiford break;
933ca044082SRichard Sandiford case ELF::R_390_PC16DBL:
934ca044082SRichard Sandiford case ELF::R_390_PLT16DBL: {
935277776a5SSanjoy Das int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
936ca044082SRichard Sandiford assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
937ca044082SRichard Sandiford writeInt16BE(LocalAddress, Delta / 2);
938ca044082SRichard Sandiford break;
939ca044082SRichard Sandiford }
940ca044082SRichard Sandiford case ELF::R_390_PC32DBL:
941ca044082SRichard Sandiford case ELF::R_390_PLT32DBL: {
942277776a5SSanjoy Das int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
943ca044082SRichard Sandiford assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
944ca044082SRichard Sandiford writeInt32BE(LocalAddress, Delta / 2);
945ca044082SRichard Sandiford break;
946ca044082SRichard Sandiford }
947d94e6d9aSUlrich Weigand case ELF::R_390_PC16: {
948d94e6d9aSUlrich Weigand int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
949d94e6d9aSUlrich Weigand assert(int16_t(Delta) == Delta && "R_390_PC16 overflow");
950d94e6d9aSUlrich Weigand writeInt16BE(LocalAddress, Delta);
951d94e6d9aSUlrich Weigand break;
952d94e6d9aSUlrich Weigand }
953ca044082SRichard Sandiford case ELF::R_390_PC32: {
954277776a5SSanjoy Das int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
955ca044082SRichard Sandiford assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
956ca044082SRichard Sandiford writeInt32BE(LocalAddress, Delta);
957ca044082SRichard Sandiford break;
958ca044082SRichard Sandiford }
959d1145ad2SBryan Chan case ELF::R_390_PC64: {
960d1145ad2SBryan Chan int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
961d1145ad2SBryan Chan writeInt64BE(LocalAddress, Delta);
962d1145ad2SBryan Chan break;
963d1145ad2SBryan Chan }
964d94e6d9aSUlrich Weigand case ELF::R_390_8:
965d94e6d9aSUlrich Weigand *LocalAddress = (uint8_t)(Value + Addend);
966d94e6d9aSUlrich Weigand break;
967d94e6d9aSUlrich Weigand case ELF::R_390_16:
968d94e6d9aSUlrich Weigand writeInt16BE(LocalAddress, Value + Addend);
969d94e6d9aSUlrich Weigand break;
970d94e6d9aSUlrich Weigand case ELF::R_390_32:
971d94e6d9aSUlrich Weigand writeInt32BE(LocalAddress, Value + Addend);
972d94e6d9aSUlrich Weigand break;
973d94e6d9aSUlrich Weigand case ELF::R_390_64:
974d94e6d9aSUlrich Weigand writeInt64BE(LocalAddress, Value + Addend);
975d94e6d9aSUlrich Weigand break;
976ca044082SRichard Sandiford }
977ca044082SRichard Sandiford }
978ca044082SRichard Sandiford
resolveBPFRelocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend)9794198f2a7SAlexei Starovoitov void RuntimeDyldELF::resolveBPFRelocation(const SectionEntry &Section,
9804198f2a7SAlexei Starovoitov uint64_t Offset, uint64_t Value,
9814198f2a7SAlexei Starovoitov uint32_t Type, int64_t Addend) {
9824198f2a7SAlexei Starovoitov bool isBE = Arch == Triple::bpfeb;
9834198f2a7SAlexei Starovoitov
9844198f2a7SAlexei Starovoitov switch (Type) {
9854198f2a7SAlexei Starovoitov default:
9866a3b07a4SHans Wennborg report_fatal_error("Relocation type not implemented yet!");
9874198f2a7SAlexei Starovoitov break;
9884198f2a7SAlexei Starovoitov case ELF::R_BPF_NONE:
9896a2ea846SYonghong Song case ELF::R_BPF_64_64:
9906a2ea846SYonghong Song case ELF::R_BPF_64_32:
9916a2ea846SYonghong Song case ELF::R_BPF_64_NODYLD32:
9924198f2a7SAlexei Starovoitov break;
9936a2ea846SYonghong Song case ELF::R_BPF_64_ABS64: {
9944198f2a7SAlexei Starovoitov write(isBE, Section.getAddressWithOffset(Offset), Value + Addend);
995d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
9964198f2a7SAlexei Starovoitov << format("%p\n", Section.getAddressWithOffset(Offset)));
9974198f2a7SAlexei Starovoitov break;
9984198f2a7SAlexei Starovoitov }
9996a2ea846SYonghong Song case ELF::R_BPF_64_ABS32: {
10004198f2a7SAlexei Starovoitov Value += Addend;
10014198f2a7SAlexei Starovoitov assert(Value <= UINT32_MAX);
10024198f2a7SAlexei Starovoitov write(isBE, Section.getAddressWithOffset(Offset), static_cast<uint32_t>(Value));
1003d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Writing " << format("%p", Value) << " at "
10044198f2a7SAlexei Starovoitov << format("%p\n", Section.getAddressWithOffset(Offset)));
10054198f2a7SAlexei Starovoitov break;
10064198f2a7SAlexei Starovoitov }
10074198f2a7SAlexei Starovoitov }
10084198f2a7SAlexei Starovoitov }
10094198f2a7SAlexei Starovoitov
10105f3a9989SAndrew Kaylor // The target location for the relocation is described by RE.SectionID and
10115f3a9989SAndrew Kaylor // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
10125f3a9989SAndrew Kaylor // SectionEntry has three members describing its location.
10135f3a9989SAndrew Kaylor // SectionEntry::Address is the address at which the section has been loaded
10145f3a9989SAndrew Kaylor // into memory in the current (host) process. SectionEntry::LoadAddress is the
10155f3a9989SAndrew Kaylor // address that the section will have in the target process.
10165f3a9989SAndrew Kaylor // SectionEntry::ObjAddress is the address of the bits for this section in the
10175f3a9989SAndrew Kaylor // original emitted object image (also in the current address space).
10185f3a9989SAndrew Kaylor //
10195f3a9989SAndrew Kaylor // Relocations will be applied as if the section were loaded at
10205f3a9989SAndrew Kaylor // SectionEntry::LoadAddress, but they will be applied at an address based
10215f3a9989SAndrew Kaylor // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
10225f3a9989SAndrew Kaylor // Target memory contents if they are required for value calculations.
10235f3a9989SAndrew Kaylor //
10245f3a9989SAndrew Kaylor // The Value parameter here is the load address of the symbol for the
10255f3a9989SAndrew Kaylor // relocation to be applied. For relocations which refer to symbols in the
10265f3a9989SAndrew Kaylor // current object Value will be the LoadAddress of the section in which
10275f3a9989SAndrew Kaylor // the symbol resides (RE.Addend provides additional information about the
10285f3a9989SAndrew Kaylor // symbol location). For external symbols, Value will be the address of the
10295f3a9989SAndrew Kaylor // symbol in the target address space.
resolveRelocation(const RelocationEntry & RE,uint64_t Value)1030f1f1c626SRafael Espindola void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
1031f1f1c626SRafael Espindola uint64_t Value) {
1032f1f1c626SRafael Espindola const SectionEntry &Section = Sections[RE.SectionID];
10334612fed9SAndrew Kaylor return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
10349720283eSPetar Jovanovic RE.SymOffset, RE.SectionID);
1035f1f1c626SRafael Espindola }
1036f1f1c626SRafael Espindola
resolveRelocation(const SectionEntry & Section,uint64_t Offset,uint64_t Value,uint32_t Type,int64_t Addend,uint64_t SymOffset,SID SectionID)1037fb05a50fSAndrew Kaylor void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
10387608dc04SJuergen Ributzka uint64_t Offset, uint64_t Value,
10397608dc04SJuergen Ributzka uint32_t Type, int64_t Addend,
10409720283eSPetar Jovanovic uint64_t SymOffset, SID SectionID) {
10414c647587SEli Bendersky switch (Arch) {
10424c647587SEli Bendersky case Triple::x86_64:
10434612fed9SAndrew Kaylor resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
10444c647587SEli Bendersky break;
10454c647587SEli Bendersky case Triple::x86:
10467608dc04SJuergen Ributzka resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
104770d22ccbSDanil Malyshev (uint32_t)(Addend & 0xffffffffL));
10484c647587SEli Bendersky break;
1049fa1b2f85STim Northover case Triple::aarch64:
105099974c72SChristian Pirker case Triple::aarch64_be:
1051fa1b2f85STim Northover resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
1052fa1b2f85STim Northover break;
105370d22ccbSDanil Malyshev case Triple::arm: // Fall through.
10542a111609SChristian Pirker case Triple::armeb:
105570d22ccbSDanil Malyshev case Triple::thumb:
10562a111609SChristian Pirker case Triple::thumbeb:
10577608dc04SJuergen Ributzka resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
105870d22ccbSDanil Malyshev (uint32_t)(Addend & 0xffffffffL));
10594c647587SEli Bendersky break;
10608f004471SBrandon Bergren case Triple::ppc: // Fall through.
10618f004471SBrandon Bergren case Triple::ppcle:
106223cdeeeaSHal Finkel resolvePPC32Relocation(Section, Offset, Value, Type, Addend);
106323cdeeeaSHal Finkel break;
10640a9170d9SBill Schmidt case Triple::ppc64: // Fall through.
10650a9170d9SBill Schmidt case Triple::ppc64le:
1066fb05a50fSAndrew Kaylor resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
10675fc11b35SAdhemerval Zanella break;
1068ca044082SRichard Sandiford case Triple::systemz:
1069ca044082SRichard Sandiford resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
1070ca044082SRichard Sandiford break;
10714198f2a7SAlexei Starovoitov case Triple::bpfel:
10724198f2a7SAlexei Starovoitov case Triple::bpfeb:
10734198f2a7SAlexei Starovoitov resolveBPFRelocation(Section, Offset, Value, Type, Addend);
10744198f2a7SAlexei Starovoitov break;
10757608dc04SJuergen Ributzka default:
10767608dc04SJuergen Ributzka llvm_unreachable("Unsupported CPU type!");
10774c647587SEli Bendersky }
10784c647587SEli Bendersky }
10794c647587SEli Bendersky
computePlaceholderAddress(unsigned SectionID,uint64_t Offset) const1080e6892c81SKeno Fischer void *RuntimeDyldELF::computePlaceholderAddress(unsigned SectionID, uint64_t Offset) const {
1081277776a5SSanjoy Das return (void *)(Sections[SectionID].getObjAddress() + Offset);
1082e6892c81SKeno Fischer }
1083e6892c81SKeno Fischer
processSimpleRelocation(unsigned SectionID,uint64_t Offset,unsigned RelType,RelocationValueRef Value)1084e6892c81SKeno Fischer void RuntimeDyldELF::processSimpleRelocation(unsigned SectionID, uint64_t Offset, unsigned RelType, RelocationValueRef Value) {
1085e6892c81SKeno Fischer RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1086e6892c81SKeno Fischer if (Value.SymbolName)
1087e6892c81SKeno Fischer addRelocationForSymbol(RE, Value.SymbolName);
1088e6892c81SKeno Fischer else
1089e6892c81SKeno Fischer addRelocationForSection(RE, Value.SectionID);
1090e6892c81SKeno Fischer }
1091e6892c81SKeno Fischer
getMatchingLoRelocation(uint32_t RelType,bool IsLocal) const1092d22164dcSPetar Jovanovic uint32_t RuntimeDyldELF::getMatchingLoRelocation(uint32_t RelType,
1093d22164dcSPetar Jovanovic bool IsLocal) const {
1094d22164dcSPetar Jovanovic switch (RelType) {
1095d22164dcSPetar Jovanovic case ELF::R_MICROMIPS_GOT16:
1096d22164dcSPetar Jovanovic if (IsLocal)
1097d22164dcSPetar Jovanovic return ELF::R_MICROMIPS_LO16;
1098d22164dcSPetar Jovanovic break;
1099d22164dcSPetar Jovanovic case ELF::R_MICROMIPS_HI16:
1100d22164dcSPetar Jovanovic return ELF::R_MICROMIPS_LO16;
1101d22164dcSPetar Jovanovic case ELF::R_MIPS_GOT16:
1102d22164dcSPetar Jovanovic if (IsLocal)
1103d22164dcSPetar Jovanovic return ELF::R_MIPS_LO16;
1104d22164dcSPetar Jovanovic break;
1105d22164dcSPetar Jovanovic case ELF::R_MIPS_HI16:
1106d22164dcSPetar Jovanovic return ELF::R_MIPS_LO16;
1107d22164dcSPetar Jovanovic case ELF::R_MIPS_PCHI16:
1108d22164dcSPetar Jovanovic return ELF::R_MIPS_PCLO16;
1109d22164dcSPetar Jovanovic default:
1110d22164dcSPetar Jovanovic break;
1111d22164dcSPetar Jovanovic }
1112d22164dcSPetar Jovanovic return ELF::R_MIPS_NONE;
1113d22164dcSPetar Jovanovic }
1114d22164dcSPetar Jovanovic
1115be2d68f7SEugene Leviant // Sometimes we don't need to create thunk for a branch.
1116be2d68f7SEugene Leviant // This typically happens when branch target is located
1117be2d68f7SEugene Leviant // in the same object file. In such case target is either
1118be2d68f7SEugene Leviant // a weak symbol or symbol in a different executable section.
1119be2d68f7SEugene Leviant // This function checks if branch target is located in the
1120be2d68f7SEugene Leviant // same object file and if distance between source and target
1121be2d68f7SEugene Leviant // fits R_AARCH64_CALL26 relocation. If both conditions are
1122be2d68f7SEugene Leviant // met, it emits direct jump to the target and returns true.
1123be2d68f7SEugene Leviant // Otherwise false is returned and thunk is created.
resolveAArch64ShortBranch(unsigned SectionID,relocation_iterator RelI,const RelocationValueRef & Value)1124be2d68f7SEugene Leviant bool RuntimeDyldELF::resolveAArch64ShortBranch(
1125be2d68f7SEugene Leviant unsigned SectionID, relocation_iterator RelI,
1126be2d68f7SEugene Leviant const RelocationValueRef &Value) {
1127be2d68f7SEugene Leviant uint64_t Address;
1128be2d68f7SEugene Leviant if (Value.SymbolName) {
1129be2d68f7SEugene Leviant auto Loc = GlobalSymbolTable.find(Value.SymbolName);
1130be2d68f7SEugene Leviant
1131be2d68f7SEugene Leviant // Don't create direct branch for external symbols.
1132be2d68f7SEugene Leviant if (Loc == GlobalSymbolTable.end())
1133be2d68f7SEugene Leviant return false;
1134be2d68f7SEugene Leviant
1135be2d68f7SEugene Leviant const auto &SymInfo = Loc->second;
1136d3383810SPavel Labath Address =
1137d3383810SPavel Labath uint64_t(Sections[SymInfo.getSectionID()].getLoadAddressWithOffset(
1138be2d68f7SEugene Leviant SymInfo.getOffset()));
1139be2d68f7SEugene Leviant } else {
1140d3383810SPavel Labath Address = uint64_t(Sections[Value.SectionID].getLoadAddress());
1141be2d68f7SEugene Leviant }
1142be2d68f7SEugene Leviant uint64_t Offset = RelI->getOffset();
1143be2d68f7SEugene Leviant uint64_t SourceAddress = Sections[SectionID].getLoadAddressWithOffset(Offset);
1144be2d68f7SEugene Leviant
1145be2d68f7SEugene Leviant // R_AARCH64_CALL26 requires immediate to be in range -2^27 <= imm < 2^27
1146be2d68f7SEugene Leviant // If distance between source and target is out of range then we should
1147be2d68f7SEugene Leviant // create thunk.
1148be2d68f7SEugene Leviant if (!isInt<28>(Address + Value.Addend - SourceAddress))
1149be2d68f7SEugene Leviant return false;
1150be2d68f7SEugene Leviant
1151be2d68f7SEugene Leviant resolveRelocation(Sections[SectionID], Offset, Address, RelI->getType(),
1152be2d68f7SEugene Leviant Value.Addend);
1153be2d68f7SEugene Leviant
1154be2d68f7SEugene Leviant return true;
1155be2d68f7SEugene Leviant }
1156be2d68f7SEugene Leviant
resolveAArch64Branch(unsigned SectionID,const RelocationValueRef & Value,relocation_iterator RelI,StubMap & Stubs)11573e582c88SEugene Leviant void RuntimeDyldELF::resolveAArch64Branch(unsigned SectionID,
11583e582c88SEugene Leviant const RelocationValueRef &Value,
11593e582c88SEugene Leviant relocation_iterator RelI,
11603e582c88SEugene Leviant StubMap &Stubs) {
11613e582c88SEugene Leviant
1162d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
11633e582c88SEugene Leviant SectionEntry &Section = Sections[SectionID];
11643e582c88SEugene Leviant
11653e582c88SEugene Leviant uint64_t Offset = RelI->getOffset();
11663e582c88SEugene Leviant unsigned RelType = RelI->getType();
11673e582c88SEugene Leviant // Look for an existing stub.
11683e582c88SEugene Leviant StubMap::const_iterator i = Stubs.find(Value);
11693e582c88SEugene Leviant if (i != Stubs.end()) {
11703e582c88SEugene Leviant resolveRelocation(Section, Offset,
11713e582c88SEugene Leviant (uint64_t)Section.getAddressWithOffset(i->second),
11723e582c88SEugene Leviant RelType, 0);
1173d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Stub function found\n");
11743e582c88SEugene Leviant } else if (!resolveAArch64ShortBranch(SectionID, RelI, Value)) {
11753e582c88SEugene Leviant // Create a new stub function.
1176d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Create a new stub function\n");
11773e582c88SEugene Leviant Stubs[Value] = Section.getStubOffset();
11783e582c88SEugene Leviant uint8_t *StubTargetAddr = createStubFunction(
11793e582c88SEugene Leviant Section.getAddressWithOffset(Section.getStubOffset()));
11803e582c88SEugene Leviant
11813e582c88SEugene Leviant RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.getAddress(),
11823e582c88SEugene Leviant ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
11833e582c88SEugene Leviant RelocationEntry REmovk_g2(SectionID,
11843e582c88SEugene Leviant StubTargetAddr - Section.getAddress() + 4,
11853e582c88SEugene Leviant ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
11863e582c88SEugene Leviant RelocationEntry REmovk_g1(SectionID,
11873e582c88SEugene Leviant StubTargetAddr - Section.getAddress() + 8,
11883e582c88SEugene Leviant ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
11893e582c88SEugene Leviant RelocationEntry REmovk_g0(SectionID,
11903e582c88SEugene Leviant StubTargetAddr - Section.getAddress() + 12,
11913e582c88SEugene Leviant ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
11923e582c88SEugene Leviant
11933e582c88SEugene Leviant if (Value.SymbolName) {
11943e582c88SEugene Leviant addRelocationForSymbol(REmovz_g3, Value.SymbolName);
11953e582c88SEugene Leviant addRelocationForSymbol(REmovk_g2, Value.SymbolName);
11963e582c88SEugene Leviant addRelocationForSymbol(REmovk_g1, Value.SymbolName);
11973e582c88SEugene Leviant addRelocationForSymbol(REmovk_g0, Value.SymbolName);
11983e582c88SEugene Leviant } else {
11993e582c88SEugene Leviant addRelocationForSection(REmovz_g3, Value.SectionID);
12003e582c88SEugene Leviant addRelocationForSection(REmovk_g2, Value.SectionID);
12013e582c88SEugene Leviant addRelocationForSection(REmovk_g1, Value.SectionID);
12023e582c88SEugene Leviant addRelocationForSection(REmovk_g0, Value.SectionID);
12033e582c88SEugene Leviant }
12043e582c88SEugene Leviant resolveRelocation(Section, Offset,
12053e582c88SEugene Leviant reinterpret_cast<uint64_t>(Section.getAddressWithOffset(
12063e582c88SEugene Leviant Section.getStubOffset())),
12073e582c88SEugene Leviant RelType, 0);
12083e582c88SEugene Leviant Section.advanceStubOffset(getMaxStubSize());
12093e582c88SEugene Leviant }
12103e582c88SEugene Leviant }
12113e582c88SEugene Leviant
12128959531cSLang Hames Expected<relocation_iterator>
processRelocationRef(unsigned SectionID,relocation_iterator RelI,const ObjectFile & O,ObjSectionToIDMap & ObjSectionToID,StubMap & Stubs)12138959531cSLang Hames RuntimeDyldELF::processRelocationRef(
12143dc0d05bSRafael Espindola unsigned SectionID, relocation_iterator RelI, const ObjectFile &O,
12153dc0d05bSRafael Espindola ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs) {
12163dc0d05bSRafael Espindola const auto &Obj = cast<ELFObjectFileBase>(O);
121799c041b7SRafael Espindola uint64_t RelType = RelI->getType();
12181a0e5a19SRafael Espindola int64_t Addend = 0;
12191a0e5a19SRafael Espindola if (Expected<int64_t> AddendOrErr = ELFRelocationRef(*RelI).getAddend())
12201a0e5a19SRafael Espindola Addend = *AddendOrErr;
12211a0e5a19SRafael Espindola else
12221a0e5a19SRafael Espindola consumeError(AddendOrErr.takeError());
1223eef7ffe2SRafael Espindola elf_symbol_iterator Symbol = RelI->getSymbol();
1224667b879eSEli Bendersky
1225667b879eSEli Bendersky // Obtain the symbol name which is referenced in the relocation
1226667b879eSEli Bendersky StringRef TargetName;
12275d0c2ffaSRafael Espindola if (Symbol != Obj.symbol_end()) {
12288959531cSLang Hames if (auto TargetNameOrErr = Symbol->getName())
12295d0c2ffaSRafael Espindola TargetName = *TargetNameOrErr;
12308959531cSLang Hames else
12318959531cSLang Hames return TargetNameOrErr.takeError();
12325d0c2ffaSRafael Espindola }
1233d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
12347608dc04SJuergen Ributzka << " TargetName: " << TargetName << "\n");
1235667b879eSEli Bendersky RelocationValueRef Value;
1236667b879eSEli Bendersky // First search for the symbol in the local symbol table
12377595447bSRafael Espindola SymbolRef::Type SymType = SymbolRef::ST_Unknown;
1238a5cd950cSLang Hames
1239667b879eSEli Bendersky // Search for the symbol in the global symbol table
12406bfd3980SLang Hames RTDyldSymbolTable::const_iterator gsi = GlobalSymbolTable.end();
1241a5cd950cSLang Hames if (Symbol != Obj.symbol_end()) {
12427595447bSRafael Espindola gsi = GlobalSymbolTable.find(TargetName.data());
12437bd8d994SKevin Enderby Expected<SymbolRef::Type> SymTypeOrErr = Symbol->getType();
12447bd8d994SKevin Enderby if (!SymTypeOrErr) {
12457bd8d994SKevin Enderby std::string Buf;
12467bd8d994SKevin Enderby raw_string_ostream OS(Buf);
124745eb84f3SJonas Devlieghere logAllUnhandledErrors(SymTypeOrErr.takeError(), OS);
12482e5daac2SSimon Pilgrim report_fatal_error(Twine(OS.str()));
12497bd8d994SKevin Enderby }
12505afbc1cdSKevin Enderby SymType = *SymTypeOrErr;
1251a5cd950cSLang Hames }
1252fc079081SEli Bendersky if (gsi != GlobalSymbolTable.end()) {
12536bfd3980SLang Hames const auto &SymInfo = gsi->second;
12546bfd3980SLang Hames Value.SectionID = SymInfo.getSectionID();
12556bfd3980SLang Hames Value.Offset = SymInfo.getOffset();
12566bfd3980SLang Hames Value.Addend = SymInfo.getOffset() + Addend;
125770d22ccbSDanil Malyshev } else {
125870d22ccbSDanil Malyshev switch (SymType) {
125970d22ccbSDanil Malyshev case SymbolRef::ST_Debug: {
126070d22ccbSDanil Malyshev // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
126170d22ccbSDanil Malyshev // and can be changed by another developers. Maybe best way is add
126270d22ccbSDanil Malyshev // a new symbol type ST_Section to SymbolRef and use it.
12637bd8d994SKevin Enderby auto SectionOrErr = Symbol->getSection();
12647bd8d994SKevin Enderby if (!SectionOrErr) {
12657bd8d994SKevin Enderby std::string Buf;
12667bd8d994SKevin Enderby raw_string_ostream OS(Buf);
126745eb84f3SJonas Devlieghere logAllUnhandledErrors(SectionOrErr.takeError(), OS);
12682e5daac2SSimon Pilgrim report_fatal_error(Twine(OS.str()));
12697bd8d994SKevin Enderby }
12707bd8d994SKevin Enderby section_iterator si = *SectionOrErr;
1271b5c7b1ffSLang Hames if (si == Obj.section_end())
127270d22ccbSDanil Malyshev llvm_unreachable("Symbol section not found, bad object file format!");
1273d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\t\tThis is section symbol\n");
127480291274SRafael Espindola bool isCode = si->isText();
12758959531cSLang Hames if (auto SectionIDOrErr = findOrEmitSection(Obj, (*si), isCode,
12768959531cSLang Hames ObjSectionToID))
12778959531cSLang Hames Value.SectionID = *SectionIDOrErr;
12788959531cSLang Hames else
12798959531cSLang Hames return SectionIDOrErr.takeError();
128070d22ccbSDanil Malyshev Value.Addend = Addend;
128170d22ccbSDanil Malyshev break;
128270d22ccbSDanil Malyshev }
12834612fed9SAndrew Kaylor case SymbolRef::ST_Data:
1284bb9431acSLang Hames case SymbolRef::ST_Function:
128570d22ccbSDanil Malyshev case SymbolRef::ST_Unknown: {
128670d22ccbSDanil Malyshev Value.SymbolName = TargetName.data();
128770d22ccbSDanil Malyshev Value.Addend = Addend;
1288ad6d349fSRichard Mitton
1289ad6d349fSRichard Mitton // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
1290ad6d349fSRichard Mitton // will manifest here as a NULL symbol name.
1291ad6d349fSRichard Mitton // We can set this as a valid (but empty) symbol name, and rely
1292ad6d349fSRichard Mitton // on addRelocationForSymbol to handle this.
1293ad6d349fSRichard Mitton if (!Value.SymbolName)
1294ad6d349fSRichard Mitton Value.SymbolName = "";
129570d22ccbSDanil Malyshev break;
129670d22ccbSDanil Malyshev }
129770d22ccbSDanil Malyshev default:
129870d22ccbSDanil Malyshev llvm_unreachable("Unresolved symbol type!");
129970d22ccbSDanil Malyshev break;
13004c647587SEli Bendersky }
13014c647587SEli Bendersky }
1302a5cd950cSLang Hames
130396d071cdSRafael Espindola uint64_t Offset = RelI->getOffset();
13044d4a48d9SRafael Espindola
1305d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
130670d22ccbSDanil Malyshev << "\n");
13073e582c88SEugene Leviant if ((Arch == Triple::aarch64 || Arch == Triple::aarch64_be)) {
1308a33687ecSRafael Auler if ((RelType == ELF::R_AARCH64_CALL26 ||
1309a33687ecSRafael Auler RelType == ELF::R_AARCH64_JUMP26) &&
1310a33687ecSRafael Auler MemMgr.allowStubAllocation()) {
13113e582c88SEugene Leviant resolveAArch64Branch(SectionID, Value, RelI, Stubs);
13123e582c88SEugene Leviant } else if (RelType == ELF::R_AARCH64_ADR_GOT_PAGE) {
1313d96f92ffSZhuo Zhang // Create new GOT entry or find existing one. If GOT entry is
13143e582c88SEugene Leviant // to be created, then we also emit ABS64 relocation for it.
13153e582c88SEugene Leviant uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
13163e582c88SEugene Leviant resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
13173e582c88SEugene Leviant ELF::R_AARCH64_ADR_PREL_PG_HI21);
131837cde975STim Northover
13193e582c88SEugene Leviant } else if (RelType == ELF::R_AARCH64_LD64_GOT_LO12_NC) {
13203e582c88SEugene Leviant uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
13213e582c88SEugene Leviant resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
13223e582c88SEugene Leviant ELF::R_AARCH64_LDST64_ABS_LO12_NC);
132337cde975STim Northover } else {
13243e582c88SEugene Leviant processSimpleRelocation(SectionID, Offset, RelType, Value);
132537cde975STim Northover }
1326e6892c81SKeno Fischer } else if (Arch == Triple::arm) {
1327e6892c81SKeno Fischer if (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
1328e6892c81SKeno Fischer RelType == ELF::R_ARM_JUMP24) {
132970d22ccbSDanil Malyshev // This is an ARM branch relocation, need to use a stub function.
1330d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.\n");
13314d4a48d9SRafael Espindola SectionEntry &Section = Sections[SectionID];
13324c647587SEli Bendersky
1333c33f622cSEric Christopher // Look for an existing stub.
133470d22ccbSDanil Malyshev StubMap::const_iterator i = Stubs.find(Value);
133570d22ccbSDanil Malyshev if (i != Stubs.end()) {
1336277776a5SSanjoy Das resolveRelocation(
1337277776a5SSanjoy Das Section, Offset,
1338277776a5SSanjoy Das reinterpret_cast<uint64_t>(Section.getAddressWithOffset(i->second)),
13397608dc04SJuergen Ributzka RelType, 0);
1340d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Stub function found\n");
134170d22ccbSDanil Malyshev } else {
134270d22ccbSDanil Malyshev // Create a new stub function.
1343d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1344277776a5SSanjoy Das Stubs[Value] = Section.getStubOffset();
1345277776a5SSanjoy Das uint8_t *StubTargetAddr = createStubFunction(
1346277776a5SSanjoy Das Section.getAddressWithOffset(Section.getStubOffset()));
1347277776a5SSanjoy Das RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
1348e6892c81SKeno Fischer ELF::R_ARM_ABS32, Value.Addend);
1349667b879eSEli Bendersky if (Value.SymbolName)
1350667b879eSEli Bendersky addRelocationForSymbol(RE, Value.SymbolName);
1351667b879eSEli Bendersky else
1352667b879eSEli Bendersky addRelocationForSection(RE, Value.SectionID);
1353667b879eSEli Bendersky
1354277776a5SSanjoy Das resolveRelocation(Section, Offset, reinterpret_cast<uint64_t>(
1355277776a5SSanjoy Das Section.getAddressWithOffset(
1356277776a5SSanjoy Das Section.getStubOffset())),
1357277776a5SSanjoy Das RelType, 0);
1358277776a5SSanjoy Das Section.advanceStubOffset(getMaxStubSize());
135970d22ccbSDanil Malyshev }
1360e6892c81SKeno Fischer } else {
1361e6892c81SKeno Fischer uint32_t *Placeholder =
1362e6892c81SKeno Fischer reinterpret_cast<uint32_t*>(computePlaceholderAddress(SectionID, Offset));
1363e6892c81SKeno Fischer if (RelType == ELF::R_ARM_PREL31 || RelType == ELF::R_ARM_TARGET1 ||
1364e6892c81SKeno Fischer RelType == ELF::R_ARM_ABS32) {
1365e6892c81SKeno Fischer Value.Addend += *Placeholder;
1366e6892c81SKeno Fischer } else if (RelType == ELF::R_ARM_MOVW_ABS_NC || RelType == ELF::R_ARM_MOVT_ABS) {
1367e6892c81SKeno Fischer // See ELF for ARM documentation
1368e6892c81SKeno Fischer Value.Addend += (int16_t)((*Placeholder & 0xFFF) | (((*Placeholder >> 16) & 0xF) << 12));
1369e6892c81SKeno Fischer }
1370e6892c81SKeno Fischer processSimpleRelocation(SectionID, Offset, RelType, Value);
1371e6892c81SKeno Fischer }
13729720283eSPetar Jovanovic } else if (IsMipsO32ABI) {
13738b2354deSDaniel Sanders uint8_t *Placeholder = reinterpret_cast<uint8_t *>(
13748b2354deSDaniel Sanders computePlaceholderAddress(SectionID, Offset));
13758b2354deSDaniel Sanders uint32_t Opcode = readBytesUnaligned(Placeholder, 4);
1376e6892c81SKeno Fischer if (RelType == ELF::R_MIPS_26) {
1377111174beSAkira Hatanaka // This is an Mips branch relocation, need to use a stub function.
1378d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
13794d4a48d9SRafael Espindola SectionEntry &Section = Sections[SectionID];
1380111174beSAkira Hatanaka
1381111174beSAkira Hatanaka // Extract the addend from the instruction.
1382e6892c81SKeno Fischer // We shift up by two since the Value will be down shifted again
1383e6892c81SKeno Fischer // when applying the relocation.
13848b2354deSDaniel Sanders uint32_t Addend = (Opcode & 0x03ffffff) << 2;
1385111174beSAkira Hatanaka
1386111174beSAkira Hatanaka Value.Addend += Addend;
1387111174beSAkira Hatanaka
1388111174beSAkira Hatanaka // Look up for existing stub.
1389111174beSAkira Hatanaka StubMap::const_iterator i = Stubs.find(Value);
1390111174beSAkira Hatanaka if (i != Stubs.end()) {
139145115f87SPetar Jovanovic RelocationEntry RE(SectionID, Offset, RelType, i->second);
139245115f87SPetar Jovanovic addRelocationForSection(RE, SectionID);
1393d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Stub function found\n");
1394111174beSAkira Hatanaka } else {
1395111174beSAkira Hatanaka // Create a new stub function.
1396d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1397277776a5SSanjoy Das Stubs[Value] = Section.getStubOffset();
13987481e40eSNitesh Jain
1399d5f76ad3SRafael Espindola unsigned AbiVariant = Obj.getPlatformFlags();
14007481e40eSNitesh Jain
1401277776a5SSanjoy Das uint8_t *StubTargetAddr = createStubFunction(
14027481e40eSNitesh Jain Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
1403111174beSAkira Hatanaka
1404111174beSAkira Hatanaka // Creating Hi and Lo relocations for the filled stub instructions.
1405277776a5SSanjoy Das RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
1406e6892c81SKeno Fischer ELF::R_MIPS_HI16, Value.Addend);
1407277776a5SSanjoy Das RelocationEntry RELo(SectionID,
1408990914d6SSanjoy Das StubTargetAddr - Section.getAddress() + 4,
1409e6892c81SKeno Fischer ELF::R_MIPS_LO16, Value.Addend);
1410111174beSAkira Hatanaka
1411111174beSAkira Hatanaka if (Value.SymbolName) {
1412111174beSAkira Hatanaka addRelocationForSymbol(REHi, Value.SymbolName);
1413111174beSAkira Hatanaka addRelocationForSymbol(RELo, Value.SymbolName);
1414757f74c2SNitesh Jain } else {
1415111174beSAkira Hatanaka addRelocationForSection(REHi, Value.SectionID);
1416111174beSAkira Hatanaka addRelocationForSection(RELo, Value.SectionID);
1417111174beSAkira Hatanaka }
1418111174beSAkira Hatanaka
1419277776a5SSanjoy Das RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
142045115f87SPetar Jovanovic addRelocationForSection(RE, SectionID);
1421277776a5SSanjoy Das Section.advanceStubOffset(getMaxStubSize());
1422111174beSAkira Hatanaka }
1423d22164dcSPetar Jovanovic } else if (RelType == ELF::R_MIPS_HI16 || RelType == ELF::R_MIPS_PCHI16) {
1424d22164dcSPetar Jovanovic int64_t Addend = (Opcode & 0x0000ffff) << 16;
1425d22164dcSPetar Jovanovic RelocationEntry RE(SectionID, Offset, RelType, Addend);
1426d22164dcSPetar Jovanovic PendingRelocs.push_back(std::make_pair(Value, RE));
1427d22164dcSPetar Jovanovic } else if (RelType == ELF::R_MIPS_LO16 || RelType == ELF::R_MIPS_PCLO16) {
1428d22164dcSPetar Jovanovic int64_t Addend = Value.Addend + SignExtend32<16>(Opcode & 0x0000ffff);
1429d22164dcSPetar Jovanovic for (auto I = PendingRelocs.begin(); I != PendingRelocs.end();) {
1430d22164dcSPetar Jovanovic const RelocationValueRef &MatchingValue = I->first;
1431d22164dcSPetar Jovanovic RelocationEntry &Reloc = I->second;
1432d22164dcSPetar Jovanovic if (MatchingValue == Value &&
1433d22164dcSPetar Jovanovic RelType == getMatchingLoRelocation(Reloc.RelType) &&
1434d22164dcSPetar Jovanovic SectionID == Reloc.SectionID) {
1435d22164dcSPetar Jovanovic Reloc.Addend += Addend;
1436d22164dcSPetar Jovanovic if (Value.SymbolName)
1437d22164dcSPetar Jovanovic addRelocationForSymbol(Reloc, Value.SymbolName);
1438d22164dcSPetar Jovanovic else
1439d22164dcSPetar Jovanovic addRelocationForSection(Reloc, Value.SectionID);
1440d22164dcSPetar Jovanovic I = PendingRelocs.erase(I);
1441d22164dcSPetar Jovanovic } else
1442d22164dcSPetar Jovanovic ++I;
1443d22164dcSPetar Jovanovic }
1444d22164dcSPetar Jovanovic RelocationEntry RE(SectionID, Offset, RelType, Addend);
1445d22164dcSPetar Jovanovic if (Value.SymbolName)
1446d22164dcSPetar Jovanovic addRelocationForSymbol(RE, Value.SymbolName);
1447d22164dcSPetar Jovanovic else
1448d22164dcSPetar Jovanovic addRelocationForSection(RE, Value.SectionID);
1449e6892c81SKeno Fischer } else {
1450d22164dcSPetar Jovanovic if (RelType == ELF::R_MIPS_32)
14518b2354deSDaniel Sanders Value.Addend += Opcode;
14520326a06cSPetar Jovanovic else if (RelType == ELF::R_MIPS_PC16)
14530326a06cSPetar Jovanovic Value.Addend += SignExtend32<18>((Opcode & 0x0000ffff) << 2);
14540326a06cSPetar Jovanovic else if (RelType == ELF::R_MIPS_PC19_S2)
14550326a06cSPetar Jovanovic Value.Addend += SignExtend32<21>((Opcode & 0x0007ffff) << 2);
14560326a06cSPetar Jovanovic else if (RelType == ELF::R_MIPS_PC21_S2)
14570326a06cSPetar Jovanovic Value.Addend += SignExtend32<23>((Opcode & 0x001fffff) << 2);
14580326a06cSPetar Jovanovic else if (RelType == ELF::R_MIPS_PC26_S2)
14590326a06cSPetar Jovanovic Value.Addend += SignExtend32<28>((Opcode & 0x03ffffff) << 2);
1460e6892c81SKeno Fischer processSimpleRelocation(SectionID, Offset, RelType, Value);
1461e6892c81SKeno Fischer }
1462226752c1SSimon Dardis } else if (IsMipsN32ABI || IsMipsN64ABI) {
14639720283eSPetar Jovanovic uint32_t r_type = RelType & 0xff;
14649720283eSPetar Jovanovic RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
146515126308SSagar Thakur if (r_type == ELF::R_MIPS_CALL16 || r_type == ELF::R_MIPS_GOT_PAGE
146615126308SSagar Thakur || r_type == ELF::R_MIPS_GOT_DISP) {
14679720283eSPetar Jovanovic StringMap<uint64_t>::iterator i = GOTSymbolOffsets.find(TargetName);
14689720283eSPetar Jovanovic if (i != GOTSymbolOffsets.end())
14699720283eSPetar Jovanovic RE.SymOffset = i->second;
14709720283eSPetar Jovanovic else {
14713e582c88SEugene Leviant RE.SymOffset = allocateGOTEntries(1);
14729720283eSPetar Jovanovic GOTSymbolOffsets[TargetName] = RE.SymOffset;
14739720283eSPetar Jovanovic }
14749720283eSPetar Jovanovic if (Value.SymbolName)
14759720283eSPetar Jovanovic addRelocationForSymbol(RE, Value.SymbolName);
14769720283eSPetar Jovanovic else
14779720283eSPetar Jovanovic addRelocationForSection(RE, Value.SectionID);
1478757f74c2SNitesh Jain } else if (RelType == ELF::R_MIPS_26) {
1479757f74c2SNitesh Jain // This is an Mips branch relocation, need to use a stub function.
1480d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1481757f74c2SNitesh Jain SectionEntry &Section = Sections[SectionID];
1482757f74c2SNitesh Jain
1483757f74c2SNitesh Jain // Look up for existing stub.
1484757f74c2SNitesh Jain StubMap::const_iterator i = Stubs.find(Value);
1485757f74c2SNitesh Jain if (i != Stubs.end()) {
1486757f74c2SNitesh Jain RelocationEntry RE(SectionID, Offset, RelType, i->second);
1487757f74c2SNitesh Jain addRelocationForSection(RE, SectionID);
1488d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Stub function found\n");
1489757f74c2SNitesh Jain } else {
1490757f74c2SNitesh Jain // Create a new stub function.
1491d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1492757f74c2SNitesh Jain Stubs[Value] = Section.getStubOffset();
1493757f74c2SNitesh Jain
1494d5f76ad3SRafael Espindola unsigned AbiVariant = Obj.getPlatformFlags();
1495757f74c2SNitesh Jain
1496757f74c2SNitesh Jain uint8_t *StubTargetAddr = createStubFunction(
1497757f74c2SNitesh Jain Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
1498757f74c2SNitesh Jain
1499757f74c2SNitesh Jain if (IsMipsN32ABI) {
1500757f74c2SNitesh Jain // Creating Hi and Lo relocations for the filled stub instructions.
1501757f74c2SNitesh Jain RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
1502757f74c2SNitesh Jain ELF::R_MIPS_HI16, Value.Addend);
1503757f74c2SNitesh Jain RelocationEntry RELo(SectionID,
1504757f74c2SNitesh Jain StubTargetAddr - Section.getAddress() + 4,
1505757f74c2SNitesh Jain ELF::R_MIPS_LO16, Value.Addend);
1506757f74c2SNitesh Jain if (Value.SymbolName) {
1507757f74c2SNitesh Jain addRelocationForSymbol(REHi, Value.SymbolName);
1508757f74c2SNitesh Jain addRelocationForSymbol(RELo, Value.SymbolName);
1509757f74c2SNitesh Jain } else {
1510757f74c2SNitesh Jain addRelocationForSection(REHi, Value.SectionID);
1511757f74c2SNitesh Jain addRelocationForSection(RELo, Value.SectionID);
1512757f74c2SNitesh Jain }
1513757f74c2SNitesh Jain } else {
1514757f74c2SNitesh Jain // Creating Highest, Higher, Hi and Lo relocations for the filled stub
1515757f74c2SNitesh Jain // instructions.
1516757f74c2SNitesh Jain RelocationEntry REHighest(SectionID,
1517757f74c2SNitesh Jain StubTargetAddr - Section.getAddress(),
1518757f74c2SNitesh Jain ELF::R_MIPS_HIGHEST, Value.Addend);
1519757f74c2SNitesh Jain RelocationEntry REHigher(SectionID,
1520757f74c2SNitesh Jain StubTargetAddr - Section.getAddress() + 4,
1521757f74c2SNitesh Jain ELF::R_MIPS_HIGHER, Value.Addend);
1522757f74c2SNitesh Jain RelocationEntry REHi(SectionID,
1523757f74c2SNitesh Jain StubTargetAddr - Section.getAddress() + 12,
1524757f74c2SNitesh Jain ELF::R_MIPS_HI16, Value.Addend);
1525757f74c2SNitesh Jain RelocationEntry RELo(SectionID,
1526757f74c2SNitesh Jain StubTargetAddr - Section.getAddress() + 20,
1527757f74c2SNitesh Jain ELF::R_MIPS_LO16, Value.Addend);
1528757f74c2SNitesh Jain if (Value.SymbolName) {
1529757f74c2SNitesh Jain addRelocationForSymbol(REHighest, Value.SymbolName);
1530757f74c2SNitesh Jain addRelocationForSymbol(REHigher, Value.SymbolName);
1531757f74c2SNitesh Jain addRelocationForSymbol(REHi, Value.SymbolName);
1532757f74c2SNitesh Jain addRelocationForSymbol(RELo, Value.SymbolName);
1533757f74c2SNitesh Jain } else {
1534757f74c2SNitesh Jain addRelocationForSection(REHighest, Value.SectionID);
1535757f74c2SNitesh Jain addRelocationForSection(REHigher, Value.SectionID);
1536757f74c2SNitesh Jain addRelocationForSection(REHi, Value.SectionID);
1537757f74c2SNitesh Jain addRelocationForSection(RELo, Value.SectionID);
1538757f74c2SNitesh Jain }
1539757f74c2SNitesh Jain }
1540757f74c2SNitesh Jain RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
1541757f74c2SNitesh Jain addRelocationForSection(RE, SectionID);
1542757f74c2SNitesh Jain Section.advanceStubOffset(getMaxStubSize());
1543757f74c2SNitesh Jain }
1544757f74c2SNitesh Jain } else {
1545757f74c2SNitesh Jain processSimpleRelocation(SectionID, Offset, RelType, Value);
1546757f74c2SNitesh Jain }
1547757f74c2SNitesh Jain
15480a9170d9SBill Schmidt } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
15495fc11b35SAdhemerval Zanella if (RelType == ELF::R_PPC64_REL24) {
1550752b5c9eSUlrich Weigand // Determine ABI variant in use for this object.
1551d5f76ad3SRafael Espindola unsigned AbiVariant = Obj.getPlatformFlags();
1552752b5c9eSUlrich Weigand AbiVariant &= ELF::EF_PPC64_ABI;
15535fc11b35SAdhemerval Zanella // A PPC branch relocation will need a stub function if the target is
1554fe9fcb8aSUlrich Weigand // an external symbol (either Value.SymbolName is set, or SymType is
1555fe9fcb8aSUlrich Weigand // Symbol::ST_Unknown) or if the target address is not within the
1556fe9fcb8aSUlrich Weigand // signed 24-bits branch address.
15574d4a48d9SRafael Espindola SectionEntry &Section = Sections[SectionID];
1558277776a5SSanjoy Das uint8_t *Target = Section.getAddressWithOffset(Offset);
15595fc11b35SAdhemerval Zanella bool RangeOverflow = false;
15607a598477SLang Hames bool IsExtern = Value.SymbolName || SymType == SymbolRef::ST_Unknown;
15617a598477SLang Hames if (!IsExtern) {
1562752b5c9eSUlrich Weigand if (AbiVariant != 2) {
1563752b5c9eSUlrich Weigand // In the ELFv1 ABI, a function call may point to the .opd entry,
1564752b5c9eSUlrich Weigand // so the final symbol value is calculated based on the relocation
1565752b5c9eSUlrich Weigand // values in the .opd section.
1566f88174ddSLang Hames if (auto Err = findOPDEntrySection(Obj, ObjSectionToID, Value))
1567c55cf4afSBill Wendling return std::move(Err);
1568752b5c9eSUlrich Weigand } else {
1569752b5c9eSUlrich Weigand // In the ELFv2 ABI, a function symbol may provide a local entry
1570752b5c9eSUlrich Weigand // point, which must be used for direct calls.
15717a598477SLang Hames if (Value.SectionID == SectionID){
1572eef7ffe2SRafael Espindola uint8_t SymOther = Symbol->getOther();
1573752b5c9eSUlrich Weigand Value.Addend += ELF::decodePPC64LocalEntryOffset(SymOther);
1574752b5c9eSUlrich Weigand }
15757a598477SLang Hames }
1576277776a5SSanjoy Das uint8_t *RelocTarget =
1577277776a5SSanjoy Das Sections[Value.SectionID].getAddressWithOffset(Value.Addend);
1578b6d40cceSUlrich Weigand int64_t delta = static_cast<int64_t>(Target - RelocTarget);
157936b8626bSUlrich Weigand // If it is within 26-bits branch range, just set the branch target
15807a598477SLang Hames if (SignExtend64<26>(delta) != delta) {
15817a598477SLang Hames RangeOverflow = true;
15827a598477SLang Hames } else if ((AbiVariant != 2) ||
15837a598477SLang Hames (AbiVariant == 2 && Value.SectionID == SectionID)) {
15844d4a48d9SRafael Espindola RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
15855fc11b35SAdhemerval Zanella addRelocationForSection(RE, Value.SectionID);
15865fc11b35SAdhemerval Zanella }
15875fc11b35SAdhemerval Zanella }
15887a598477SLang Hames if (IsExtern || (AbiVariant == 2 && Value.SectionID != SectionID) ||
1589fe9fcb8aSUlrich Weigand RangeOverflow) {
1590fe9fcb8aSUlrich Weigand // It is an external symbol (either Value.SymbolName is set, or
1591fe9fcb8aSUlrich Weigand // SymType is SymbolRef::ST_Unknown) or out of range.
15925fc11b35SAdhemerval Zanella StubMap::const_iterator i = Stubs.find(Value);
15935fc11b35SAdhemerval Zanella if (i != Stubs.end()) {
15945fc11b35SAdhemerval Zanella // Symbol function stub already created, just relocate to it
15954d4a48d9SRafael Espindola resolveRelocation(Section, Offset,
1596277776a5SSanjoy Das reinterpret_cast<uint64_t>(
1597277776a5SSanjoy Das Section.getAddressWithOffset(i->second)),
1598277776a5SSanjoy Das RelType, 0);
1599d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Stub function found\n");
16005fc11b35SAdhemerval Zanella } else {
16015fc11b35SAdhemerval Zanella // Create a new stub function.
1602d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1603277776a5SSanjoy Das Stubs[Value] = Section.getStubOffset();
1604277776a5SSanjoy Das uint8_t *StubTargetAddr = createStubFunction(
1605277776a5SSanjoy Das Section.getAddressWithOffset(Section.getStubOffset()),
1606752b5c9eSUlrich Weigand AbiVariant);
1607277776a5SSanjoy Das RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
16085fc11b35SAdhemerval Zanella ELF::R_PPC64_ADDR64, Value.Addend);
16095fc11b35SAdhemerval Zanella
16105fc11b35SAdhemerval Zanella // Generates the 64-bits address loads as exemplified in section
161132626014SUlrich Weigand // 4.5.1 in PPC64 ELF ABI. Note that the relocations need to
161232626014SUlrich Weigand // apply to the low part of the instructions, so we have to update
161332626014SUlrich Weigand // the offset according to the target endianness.
1614277776a5SSanjoy Das uint64_t StubRelocOffset = StubTargetAddr - Section.getAddress();
161532626014SUlrich Weigand if (!IsTargetLittleEndian)
161632626014SUlrich Weigand StubRelocOffset += 2;
161732626014SUlrich Weigand
161832626014SUlrich Weigand RelocationEntry REhst(SectionID, StubRelocOffset + 0,
16195fc11b35SAdhemerval Zanella ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
162032626014SUlrich Weigand RelocationEntry REhr(SectionID, StubRelocOffset + 4,
16215fc11b35SAdhemerval Zanella ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
162232626014SUlrich Weigand RelocationEntry REh(SectionID, StubRelocOffset + 12,
16235fc11b35SAdhemerval Zanella ELF::R_PPC64_ADDR16_HI, Value.Addend);
162432626014SUlrich Weigand RelocationEntry REl(SectionID, StubRelocOffset + 16,
16255fc11b35SAdhemerval Zanella ELF::R_PPC64_ADDR16_LO, Value.Addend);
16265fc11b35SAdhemerval Zanella
16275fc11b35SAdhemerval Zanella if (Value.SymbolName) {
16285fc11b35SAdhemerval Zanella addRelocationForSymbol(REhst, Value.SymbolName);
16295fc11b35SAdhemerval Zanella addRelocationForSymbol(REhr, Value.SymbolName);
16305fc11b35SAdhemerval Zanella addRelocationForSymbol(REh, Value.SymbolName);
16315fc11b35SAdhemerval Zanella addRelocationForSymbol(REl, Value.SymbolName);
16325fc11b35SAdhemerval Zanella } else {
16335fc11b35SAdhemerval Zanella addRelocationForSection(REhst, Value.SectionID);
16345fc11b35SAdhemerval Zanella addRelocationForSection(REhr, Value.SectionID);
16355fc11b35SAdhemerval Zanella addRelocationForSection(REh, Value.SectionID);
16365fc11b35SAdhemerval Zanella addRelocationForSection(REl, Value.SectionID);
16375fc11b35SAdhemerval Zanella }
16385fc11b35SAdhemerval Zanella
1639277776a5SSanjoy Das resolveRelocation(Section, Offset, reinterpret_cast<uint64_t>(
1640277776a5SSanjoy Das Section.getAddressWithOffset(
1641277776a5SSanjoy Das Section.getStubOffset())),
1642fb05a50fSAndrew Kaylor RelType, 0);
1643277776a5SSanjoy Das Section.advanceStubOffset(getMaxStubSize());
1644fa84ac9dSUlrich Weigand }
16457a598477SLang Hames if (IsExtern || (AbiVariant == 2 && Value.SectionID != SectionID)) {
16465fc11b35SAdhemerval Zanella // Restore the TOC for external calls
1647752b5c9eSUlrich Weigand if (AbiVariant == 2)
16487a598477SLang Hames writeInt32BE(Target + 4, 0xE8410018); // ld r2,24(r1)
1649752b5c9eSUlrich Weigand else
16505fc11b35SAdhemerval Zanella writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
16515fc11b35SAdhemerval Zanella }
1652752b5c9eSUlrich Weigand }
16538f1f87c7SUlrich Weigand } else if (RelType == ELF::R_PPC64_TOC16 ||
16548f1f87c7SUlrich Weigand RelType == ELF::R_PPC64_TOC16_DS ||
16558f1f87c7SUlrich Weigand RelType == ELF::R_PPC64_TOC16_LO ||
16568f1f87c7SUlrich Weigand RelType == ELF::R_PPC64_TOC16_LO_DS ||
16578f1f87c7SUlrich Weigand RelType == ELF::R_PPC64_TOC16_HI ||
16588f1f87c7SUlrich Weigand RelType == ELF::R_PPC64_TOC16_HA) {
16598f1f87c7SUlrich Weigand // These relocations are supposed to subtract the TOC address from
16608f1f87c7SUlrich Weigand // the final value. This does not fit cleanly into the RuntimeDyld
16618f1f87c7SUlrich Weigand // scheme, since there may be *two* sections involved in determining
1662df005cbeSBenjamin Kramer // the relocation value (the section of the symbol referred to by the
16638f1f87c7SUlrich Weigand // relocation, and the TOC section associated with the current module).
16648f1f87c7SUlrich Weigand //
16658f1f87c7SUlrich Weigand // Fortunately, these relocations are currently only ever generated
1666df005cbeSBenjamin Kramer // referring to symbols that themselves reside in the TOC, which means
16678f1f87c7SUlrich Weigand // that the two sections are actually the same. Thus they cancel out
16688f1f87c7SUlrich Weigand // and we can immediately resolve the relocation right now.
16698f1f87c7SUlrich Weigand switch (RelType) {
16708f1f87c7SUlrich Weigand case ELF::R_PPC64_TOC16: RelType = ELF::R_PPC64_ADDR16; break;
16718f1f87c7SUlrich Weigand case ELF::R_PPC64_TOC16_DS: RelType = ELF::R_PPC64_ADDR16_DS; break;
16728f1f87c7SUlrich Weigand case ELF::R_PPC64_TOC16_LO: RelType = ELF::R_PPC64_ADDR16_LO; break;
16738f1f87c7SUlrich Weigand case ELF::R_PPC64_TOC16_LO_DS: RelType = ELF::R_PPC64_ADDR16_LO_DS; break;
16748f1f87c7SUlrich Weigand case ELF::R_PPC64_TOC16_HI: RelType = ELF::R_PPC64_ADDR16_HI; break;
16758f1f87c7SUlrich Weigand case ELF::R_PPC64_TOC16_HA: RelType = ELF::R_PPC64_ADDR16_HA; break;
16768f1f87c7SUlrich Weigand default: llvm_unreachable("Wrong relocation type.");
16778f1f87c7SUlrich Weigand }
16788f1f87c7SUlrich Weigand
16798f1f87c7SUlrich Weigand RelocationValueRef TOCValue;
168009a74c46SLang Hames if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, TOCValue))
1681c55cf4afSBill Wendling return std::move(Err);
16828f1f87c7SUlrich Weigand if (Value.SymbolName || Value.SectionID != TOCValue.SectionID)
16838f1f87c7SUlrich Weigand llvm_unreachable("Unsupported TOC relocation.");
16848f1f87c7SUlrich Weigand Value.Addend -= TOCValue.Addend;
16858f1f87c7SUlrich Weigand resolveRelocation(Sections[SectionID], Offset, Value.Addend, RelType, 0);
16865fc11b35SAdhemerval Zanella } else {
16878f1f87c7SUlrich Weigand // There are two ways to refer to the TOC address directly: either
16888f1f87c7SUlrich Weigand // via a ELF::R_PPC64_TOC relocation (where both symbol and addend are
16898f1f87c7SUlrich Weigand // ignored), or via any relocation that refers to the magic ".TOC."
16908f1f87c7SUlrich Weigand // symbols (in which case the addend is respected).
16918f1f87c7SUlrich Weigand if (RelType == ELF::R_PPC64_TOC) {
16928f1f87c7SUlrich Weigand RelType = ELF::R_PPC64_ADDR64;
169309a74c46SLang Hames if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
1694c55cf4afSBill Wendling return std::move(Err);
16958f1f87c7SUlrich Weigand } else if (TargetName == ".TOC.") {
169609a74c46SLang Hames if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
1697c55cf4afSBill Wendling return std::move(Err);
16988f1f87c7SUlrich Weigand Value.Addend += Addend;
16998f1f87c7SUlrich Weigand }
17008f1f87c7SUlrich Weigand
17014d4a48d9SRafael Espindola RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1702ad6d349fSRichard Mitton
1703ad6d349fSRichard Mitton if (Value.SymbolName)
17045fc11b35SAdhemerval Zanella addRelocationForSymbol(RE, Value.SymbolName);
17055fc11b35SAdhemerval Zanella else
17065fc11b35SAdhemerval Zanella addRelocationForSection(RE, Value.SectionID);
17075fc11b35SAdhemerval Zanella }
1708ca044082SRichard Sandiford } else if (Arch == Triple::systemz &&
17097608dc04SJuergen Ributzka (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
1710ca044082SRichard Sandiford // Create function stubs for both PLT and GOT references, regardless of
1711ca044082SRichard Sandiford // whether the GOT reference is to data or code. The stub contains the
1712ca044082SRichard Sandiford // full address of the symbol, as needed by GOT references, and the
1713ca044082SRichard Sandiford // executable part only adds an overhead of 8 bytes.
1714ca044082SRichard Sandiford //
1715ca044082SRichard Sandiford // We could try to conserve space by allocating the code and data
1716ca044082SRichard Sandiford // parts of the stub separately. However, as things stand, we allocate
1717ca044082SRichard Sandiford // a stub for every relocation, so using a GOT in JIT code should be
1718ca044082SRichard Sandiford // no less space efficient than using an explicit constant pool.
1719d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1720ca044082SRichard Sandiford SectionEntry &Section = Sections[SectionID];
1721ca044082SRichard Sandiford
1722ca044082SRichard Sandiford // Look for an existing stub.
1723ca044082SRichard Sandiford StubMap::const_iterator i = Stubs.find(Value);
1724ca044082SRichard Sandiford uintptr_t StubAddress;
1725ca044082SRichard Sandiford if (i != Stubs.end()) {
1726277776a5SSanjoy Das StubAddress = uintptr_t(Section.getAddressWithOffset(i->second));
1727d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Stub function found\n");
1728ca044082SRichard Sandiford } else {
1729ca044082SRichard Sandiford // Create a new stub function.
1730d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1731ca044082SRichard Sandiford
1732277776a5SSanjoy Das uintptr_t BaseAddress = uintptr_t(Section.getAddress());
1733ca044082SRichard Sandiford uintptr_t StubAlignment = getStubAlignment();
1734277776a5SSanjoy Das StubAddress =
1735277776a5SSanjoy Das (BaseAddress + Section.getStubOffset() + StubAlignment - 1) &
17367608dc04SJuergen Ributzka -StubAlignment;
1737ca044082SRichard Sandiford unsigned StubOffset = StubAddress - BaseAddress;
1738ca044082SRichard Sandiford
1739ca044082SRichard Sandiford Stubs[Value] = StubOffset;
1740ca044082SRichard Sandiford createStubFunction((uint8_t *)StubAddress);
17417608dc04SJuergen Ributzka RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
174240e200ebSLang Hames Value.Offset);
1743ca044082SRichard Sandiford if (Value.SymbolName)
1744ca044082SRichard Sandiford addRelocationForSymbol(RE, Value.SymbolName);
1745ca044082SRichard Sandiford else
1746ca044082SRichard Sandiford addRelocationForSection(RE, Value.SectionID);
1747277776a5SSanjoy Das Section.advanceStubOffset(getMaxStubSize());
1748ca044082SRichard Sandiford }
1749ca044082SRichard Sandiford
1750ca044082SRichard Sandiford if (RelType == ELF::R_390_GOTENT)
17517608dc04SJuergen Ributzka resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
17527608dc04SJuergen Ributzka Addend);
1753ca044082SRichard Sandiford else
1754ca044082SRichard Sandiford resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1755e6892c81SKeno Fischer } else if (Arch == Triple::x86_64) {
1756e6892c81SKeno Fischer if (RelType == ELF::R_X86_64_PLT32) {
17577608dc04SJuergen Ributzka // The way the PLT relocations normally work is that the linker allocates
17587608dc04SJuergen Ributzka // the
17594612fed9SAndrew Kaylor // PLT and this relocation makes a PC-relative call into the PLT. The PLT
17607608dc04SJuergen Ributzka // entry will then jump to an address provided by the GOT. On first call,
17617608dc04SJuergen Ributzka // the
17624612fed9SAndrew Kaylor // GOT address will point back into PLT code that resolves the symbol. After
17634612fed9SAndrew Kaylor // the first call, the GOT entry points to the actual function.
17644612fed9SAndrew Kaylor //
17654612fed9SAndrew Kaylor // For local functions we're ignoring all of that here and just replacing
17664612fed9SAndrew Kaylor // the PLT32 relocation type with PC32, which will translate the relocation
17674612fed9SAndrew Kaylor // into a PC-relative call directly to the function. For external symbols we
17684612fed9SAndrew Kaylor // can't be sure the function will be within 2^32 bytes of the call site, so
17694612fed9SAndrew Kaylor // we need to create a stub, which calls into the GOT. This case is
17704612fed9SAndrew Kaylor // equivalent to the usual PLT implementation except that we use the stub
17714612fed9SAndrew Kaylor // mechanism in RuntimeDyld (which puts stubs at the end of the section)
17724612fed9SAndrew Kaylor // rather than allocating a PLT section.
1773a33687ecSRafael Auler if (Value.SymbolName && MemMgr.allowStubAllocation()) {
17744612fed9SAndrew Kaylor // This is a call to an external function.
17754612fed9SAndrew Kaylor // Look for an existing stub.
1776a554cd6aSLang Hames SectionEntry *Section = &Sections[SectionID];
17774612fed9SAndrew Kaylor StubMap::const_iterator i = Stubs.find(Value);
17784612fed9SAndrew Kaylor uintptr_t StubAddress;
17794612fed9SAndrew Kaylor if (i != Stubs.end()) {
1780a554cd6aSLang Hames StubAddress = uintptr_t(Section->getAddress()) + i->second;
1781d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Stub function found\n");
1782667b879eSEli Bendersky } else {
17834612fed9SAndrew Kaylor // Create a new stub function (equivalent to a PLT entry).
1784d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Create a new stub function\n");
17854612fed9SAndrew Kaylor
1786a554cd6aSLang Hames uintptr_t BaseAddress = uintptr_t(Section->getAddress());
17874612fed9SAndrew Kaylor uintptr_t StubAlignment = getStubAlignment();
1788277776a5SSanjoy Das StubAddress =
1789a554cd6aSLang Hames (BaseAddress + Section->getStubOffset() + StubAlignment - 1) &
17907608dc04SJuergen Ributzka -StubAlignment;
17914612fed9SAndrew Kaylor unsigned StubOffset = StubAddress - BaseAddress;
17924612fed9SAndrew Kaylor Stubs[Value] = StubOffset;
17934612fed9SAndrew Kaylor createStubFunction((uint8_t *)StubAddress);
17944612fed9SAndrew Kaylor
17954612fed9SAndrew Kaylor // Bump our stub offset counter
1796a554cd6aSLang Hames Section->advanceStubOffset(getMaxStubSize());
179702628defSKeno Fischer
179802628defSKeno Fischer // Allocate a GOT Entry
17993e582c88SEugene Leviant uint64_t GOTOffset = allocateGOTEntries(1);
1800a554cd6aSLang Hames // This potentially creates a new Section which potentially
1801a554cd6aSLang Hames // invalidates the Section pointer, so reload it.
1802a554cd6aSLang Hames Section = &Sections[SectionID];
180302628defSKeno Fischer
180402628defSKeno Fischer // The load of the GOT address has an addend of -4
18053e582c88SEugene Leviant resolveGOTOffsetRelocation(SectionID, StubOffset + 2, GOTOffset - 4,
18063e582c88SEugene Leviant ELF::R_X86_64_PC32);
180702628defSKeno Fischer
180802628defSKeno Fischer // Fill in the value of the symbol we're targeting into the GOT
180906f9a27aSSanjoy Das addRelocationForSymbol(
18103e582c88SEugene Leviant computeGOTOffsetRE(GOTOffset, 0, ELF::R_X86_64_64),
181102628defSKeno Fischer Value.SymbolName);
18124612fed9SAndrew Kaylor }
18134612fed9SAndrew Kaylor
18144612fed9SAndrew Kaylor // Make the target call a call into the stub table.
1815a554cd6aSLang Hames resolveRelocation(*Section, Offset, StubAddress, ELF::R_X86_64_PC32,
18167608dc04SJuergen Ributzka Addend);
18174612fed9SAndrew Kaylor } else {
1818a33687ecSRafael Auler Value.Addend += support::ulittle32_t::ref(
1819a33687ecSRafael Auler computePlaceholderAddress(SectionID, Offset));
1820a33687ecSRafael Auler processSimpleRelocation(SectionID, Offset, ELF::R_X86_64_PC32, Value);
18214612fed9SAndrew Kaylor }
1822cefdf238SDavide Italiano } else if (RelType == ELF::R_X86_64_GOTPCREL ||
1823cefdf238SDavide Italiano RelType == ELF::R_X86_64_GOTPCRELX ||
1824cefdf238SDavide Italiano RelType == ELF::R_X86_64_REX_GOTPCRELX) {
18253e582c88SEugene Leviant uint64_t GOTOffset = allocateGOTEntries(1);
18263e582c88SEugene Leviant resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
18273e582c88SEugene Leviant ELF::R_X86_64_PC32);
182802628defSKeno Fischer
182902628defSKeno Fischer // Fill in the value of the symbol we're targeting into the GOT
18303e582c88SEugene Leviant RelocationEntry RE =
18313e582c88SEugene Leviant computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_64);
183202628defSKeno Fischer if (Value.SymbolName)
183302628defSKeno Fischer addRelocationForSymbol(RE, Value.SymbolName);
183402628defSKeno Fischer else
183502628defSKeno Fischer addRelocationForSection(RE, Value.SectionID);
1836330f65b3SReid Kleckner } else if (RelType == ELF::R_X86_64_GOT64) {
1837330f65b3SReid Kleckner // Fill in a 64-bit GOT offset.
1838330f65b3SReid Kleckner uint64_t GOTOffset = allocateGOTEntries(1);
1839330f65b3SReid Kleckner resolveRelocation(Sections[SectionID], Offset, GOTOffset,
1840330f65b3SReid Kleckner ELF::R_X86_64_64, 0);
1841330f65b3SReid Kleckner
1842330f65b3SReid Kleckner // Fill in the value of the symbol we're targeting into the GOT
1843330f65b3SReid Kleckner RelocationEntry RE =
1844330f65b3SReid Kleckner computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_64);
1845330f65b3SReid Kleckner if (Value.SymbolName)
1846330f65b3SReid Kleckner addRelocationForSymbol(RE, Value.SymbolName);
1847330f65b3SReid Kleckner else
1848330f65b3SReid Kleckner addRelocationForSection(RE, Value.SectionID);
1849f6873786SMoritz Sichert } else if (RelType == ELF::R_X86_64_GOTPC32) {
1850330f65b3SReid Kleckner // Materialize the address of the base of the GOT relative to the PC.
1851330f65b3SReid Kleckner // This doesn't create a GOT entry, but it does mean we need a GOT
1852330f65b3SReid Kleckner // section.
1853330f65b3SReid Kleckner (void)allocateGOTEntries(0);
1854f6873786SMoritz Sichert resolveGOTOffsetRelocation(SectionID, Offset, Addend, ELF::R_X86_64_PC32);
1855f6873786SMoritz Sichert } else if (RelType == ELF::R_X86_64_GOTPC64) {
1856f6873786SMoritz Sichert (void)allocateGOTEntries(0);
1857330f65b3SReid Kleckner resolveGOTOffsetRelocation(SectionID, Offset, Addend, ELF::R_X86_64_PC64);
1858330f65b3SReid Kleckner } else if (RelType == ELF::R_X86_64_GOTOFF64) {
1859330f65b3SReid Kleckner // GOTOFF relocations ultimately require a section difference relocation.
1860330f65b3SReid Kleckner (void)allocateGOTEntries(0);
1861330f65b3SReid Kleckner processSimpleRelocation(SectionID, Offset, RelType, Value);
1862e6892c81SKeno Fischer } else if (RelType == ELF::R_X86_64_PC32) {
1863e6892c81SKeno Fischer Value.Addend += support::ulittle32_t::ref(computePlaceholderAddress(SectionID, Offset));
1864e6892c81SKeno Fischer processSimpleRelocation(SectionID, Offset, RelType, Value);
1865e6892c81SKeno Fischer } else if (RelType == ELF::R_X86_64_PC64) {
1866e6892c81SKeno Fischer Value.Addend += support::ulittle64_t::ref(computePlaceholderAddress(SectionID, Offset));
1867e6892c81SKeno Fischer processSimpleRelocation(SectionID, Offset, RelType, Value);
1868a0a59644SMoritz Sichert } else if (RelType == ELF::R_X86_64_GOTTPOFF) {
1869a0a59644SMoritz Sichert processX86_64GOTTPOFFRelocation(SectionID, Offset, Value, Addend);
1870a0a59644SMoritz Sichert } else if (RelType == ELF::R_X86_64_TLSGD ||
1871a0a59644SMoritz Sichert RelType == ELF::R_X86_64_TLSLD) {
1872a0a59644SMoritz Sichert // The next relocation must be the relocation for __tls_get_addr.
1873a0a59644SMoritz Sichert ++RelI;
1874a0a59644SMoritz Sichert auto &GetAddrRelocation = *RelI;
1875a0a59644SMoritz Sichert processX86_64TLSRelocation(SectionID, Offset, RelType, Value, Addend,
1876a0a59644SMoritz Sichert GetAddrRelocation);
18774612fed9SAndrew Kaylor } else {
1878e6892c81SKeno Fischer processSimpleRelocation(SectionID, Offset, RelType, Value);
1879e6892c81SKeno Fischer }
1880e6892c81SKeno Fischer } else {
1881e6892c81SKeno Fischer if (Arch == Triple::x86) {
1882e6892c81SKeno Fischer Value.Addend += support::ulittle32_t::ref(computePlaceholderAddress(SectionID, Offset));
1883e6892c81SKeno Fischer }
1884e6892c81SKeno Fischer processSimpleRelocation(SectionID, Offset, RelType, Value);
1885667b879eSEli Bendersky }
1886046709f0SJuergen Ributzka return ++RelI;
1887eff0a40dSJim Grosbach }
1888eff0a40dSJim Grosbach
processX86_64GOTTPOFFRelocation(unsigned SectionID,uint64_t Offset,RelocationValueRef Value,int64_t Addend)1889a0a59644SMoritz Sichert void RuntimeDyldELF::processX86_64GOTTPOFFRelocation(unsigned SectionID,
1890a0a59644SMoritz Sichert uint64_t Offset,
1891a0a59644SMoritz Sichert RelocationValueRef Value,
1892a0a59644SMoritz Sichert int64_t Addend) {
1893a0a59644SMoritz Sichert // Use the approach from "x86-64 Linker Optimizations" from the TLS spec
1894a0a59644SMoritz Sichert // to replace the GOTTPOFF relocation with a TPOFF relocation. The spec
1895a0a59644SMoritz Sichert // only mentions one optimization even though there are two different
1896a0a59644SMoritz Sichert // code sequences for the Initial Exec TLS Model. We match the code to
1897a0a59644SMoritz Sichert // find out which one was used.
1898a0a59644SMoritz Sichert
1899a0a59644SMoritz Sichert // A possible TLS code sequence and its replacement
1900a0a59644SMoritz Sichert struct CodeSequence {
1901a0a59644SMoritz Sichert // The expected code sequence
1902a0a59644SMoritz Sichert ArrayRef<uint8_t> ExpectedCodeSequence;
1903a0a59644SMoritz Sichert // The negative offset of the GOTTPOFF relocation to the beginning of
1904a0a59644SMoritz Sichert // the sequence
1905a0a59644SMoritz Sichert uint64_t TLSSequenceOffset;
1906a0a59644SMoritz Sichert // The new code sequence
1907a0a59644SMoritz Sichert ArrayRef<uint8_t> NewCodeSequence;
1908a0a59644SMoritz Sichert // The offset of the new TPOFF relocation
1909a0a59644SMoritz Sichert uint64_t TpoffRelocationOffset;
1910a0a59644SMoritz Sichert };
1911a0a59644SMoritz Sichert
1912a0a59644SMoritz Sichert std::array<CodeSequence, 2> CodeSequences;
1913a0a59644SMoritz Sichert
1914a0a59644SMoritz Sichert // Initial Exec Code Model Sequence
1915a0a59644SMoritz Sichert {
1916a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> ExpectedCodeSequenceList = {
1917a0a59644SMoritz Sichert 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00,
1918a0a59644SMoritz Sichert 0x00, // mov %fs:0, %rax
1919a0a59644SMoritz Sichert 0x48, 0x03, 0x05, 0x00, 0x00, 0x00, 0x00 // add x@gotpoff(%rip),
1920a0a59644SMoritz Sichert // %rax
1921a0a59644SMoritz Sichert };
1922a0a59644SMoritz Sichert CodeSequences[0].ExpectedCodeSequence =
1923a0a59644SMoritz Sichert ArrayRef<uint8_t>(ExpectedCodeSequenceList);
1924a0a59644SMoritz Sichert CodeSequences[0].TLSSequenceOffset = 12;
1925a0a59644SMoritz Sichert
1926a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> NewCodeSequenceList = {
1927a0a59644SMoritz Sichert 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:0, %rax
1928a0a59644SMoritz Sichert 0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00 // lea x@tpoff(%rax), %rax
1929a0a59644SMoritz Sichert };
1930a0a59644SMoritz Sichert CodeSequences[0].NewCodeSequence = ArrayRef<uint8_t>(NewCodeSequenceList);
1931a0a59644SMoritz Sichert CodeSequences[0].TpoffRelocationOffset = 12;
1932a0a59644SMoritz Sichert }
1933a0a59644SMoritz Sichert
1934a0a59644SMoritz Sichert // Initial Exec Code Model Sequence, II
1935a0a59644SMoritz Sichert {
1936a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> ExpectedCodeSequenceList = {
1937a0a59644SMoritz Sichert 0x48, 0x8b, 0x05, 0x00, 0x00, 0x00, 0x00, // mov x@gotpoff(%rip), %rax
1938a0a59644SMoritz Sichert 0x64, 0x48, 0x8b, 0x00, 0x00, 0x00, 0x00 // mov %fs:(%rax), %rax
1939a0a59644SMoritz Sichert };
1940a0a59644SMoritz Sichert CodeSequences[1].ExpectedCodeSequence =
1941a0a59644SMoritz Sichert ArrayRef<uint8_t>(ExpectedCodeSequenceList);
1942a0a59644SMoritz Sichert CodeSequences[1].TLSSequenceOffset = 3;
1943a0a59644SMoritz Sichert
1944a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> NewCodeSequenceList = {
1945a0a59644SMoritz Sichert 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00, // 6 byte nop
1946a0a59644SMoritz Sichert 0x64, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:x@tpoff, %rax
1947a0a59644SMoritz Sichert };
1948a0a59644SMoritz Sichert CodeSequences[1].NewCodeSequence = ArrayRef<uint8_t>(NewCodeSequenceList);
1949a0a59644SMoritz Sichert CodeSequences[1].TpoffRelocationOffset = 10;
1950a0a59644SMoritz Sichert }
1951a0a59644SMoritz Sichert
1952a0a59644SMoritz Sichert bool Resolved = false;
1953a0a59644SMoritz Sichert auto &Section = Sections[SectionID];
1954a0a59644SMoritz Sichert for (const auto &C : CodeSequences) {
1955a0a59644SMoritz Sichert assert(C.ExpectedCodeSequence.size() == C.NewCodeSequence.size() &&
1956a0a59644SMoritz Sichert "Old and new code sequences must have the same size");
1957a0a59644SMoritz Sichert
1958a0a59644SMoritz Sichert if (Offset < C.TLSSequenceOffset ||
1959a0a59644SMoritz Sichert (Offset - C.TLSSequenceOffset + C.NewCodeSequence.size()) >
1960a0a59644SMoritz Sichert Section.getSize()) {
1961a0a59644SMoritz Sichert // This can't be a matching sequence as it doesn't fit in the current
1962a0a59644SMoritz Sichert // section
1963a0a59644SMoritz Sichert continue;
1964a0a59644SMoritz Sichert }
1965a0a59644SMoritz Sichert
1966a0a59644SMoritz Sichert auto TLSSequenceStartOffset = Offset - C.TLSSequenceOffset;
1967a0a59644SMoritz Sichert auto *TLSSequence = Section.getAddressWithOffset(TLSSequenceStartOffset);
1968a0a59644SMoritz Sichert if (ArrayRef<uint8_t>(TLSSequence, C.ExpectedCodeSequence.size()) !=
1969a0a59644SMoritz Sichert C.ExpectedCodeSequence) {
1970a0a59644SMoritz Sichert continue;
1971a0a59644SMoritz Sichert }
1972a0a59644SMoritz Sichert
1973a0a59644SMoritz Sichert memcpy(TLSSequence, C.NewCodeSequence.data(), C.NewCodeSequence.size());
1974a0a59644SMoritz Sichert
1975a0a59644SMoritz Sichert // The original GOTTPOFF relocation has an addend as it is PC relative,
1976a0a59644SMoritz Sichert // so it needs to be corrected. The TPOFF32 relocation is used as an
1977a0a59644SMoritz Sichert // absolute value (which is an offset from %fs:0), so remove the addend
1978a0a59644SMoritz Sichert // again.
1979a0a59644SMoritz Sichert RelocationEntry RE(SectionID,
1980a0a59644SMoritz Sichert TLSSequenceStartOffset + C.TpoffRelocationOffset,
1981a0a59644SMoritz Sichert ELF::R_X86_64_TPOFF32, Value.Addend - Addend);
1982a0a59644SMoritz Sichert
1983a0a59644SMoritz Sichert if (Value.SymbolName)
1984a0a59644SMoritz Sichert addRelocationForSymbol(RE, Value.SymbolName);
1985a0a59644SMoritz Sichert else
1986a0a59644SMoritz Sichert addRelocationForSection(RE, Value.SectionID);
1987a0a59644SMoritz Sichert
1988a0a59644SMoritz Sichert Resolved = true;
1989a0a59644SMoritz Sichert break;
1990a0a59644SMoritz Sichert }
1991a0a59644SMoritz Sichert
1992a0a59644SMoritz Sichert if (!Resolved) {
1993a0a59644SMoritz Sichert // The GOTTPOFF relocation was not used in one of the sequences
1994a0a59644SMoritz Sichert // described in the spec, so we can't optimize it to a TPOFF
1995a0a59644SMoritz Sichert // relocation.
1996a0a59644SMoritz Sichert uint64_t GOTOffset = allocateGOTEntries(1);
1997a0a59644SMoritz Sichert resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1998a0a59644SMoritz Sichert ELF::R_X86_64_PC32);
1999a0a59644SMoritz Sichert RelocationEntry RE =
2000a0a59644SMoritz Sichert computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_TPOFF64);
2001a0a59644SMoritz Sichert if (Value.SymbolName)
2002a0a59644SMoritz Sichert addRelocationForSymbol(RE, Value.SymbolName);
2003a0a59644SMoritz Sichert else
2004a0a59644SMoritz Sichert addRelocationForSection(RE, Value.SectionID);
2005a0a59644SMoritz Sichert }
2006a0a59644SMoritz Sichert }
2007a0a59644SMoritz Sichert
processX86_64TLSRelocation(unsigned SectionID,uint64_t Offset,uint64_t RelType,RelocationValueRef Value,int64_t Addend,const RelocationRef & GetAddrRelocation)2008a0a59644SMoritz Sichert void RuntimeDyldELF::processX86_64TLSRelocation(
2009a0a59644SMoritz Sichert unsigned SectionID, uint64_t Offset, uint64_t RelType,
2010a0a59644SMoritz Sichert RelocationValueRef Value, int64_t Addend,
2011a0a59644SMoritz Sichert const RelocationRef &GetAddrRelocation) {
2012a0a59644SMoritz Sichert // Since we are statically linking and have no additional DSOs, we can resolve
2013a0a59644SMoritz Sichert // the relocation directly without using __tls_get_addr.
2014a0a59644SMoritz Sichert // Use the approach from "x86-64 Linker Optimizations" from the TLS spec
2015a0a59644SMoritz Sichert // to replace it with the Local Exec relocation variant.
2016a0a59644SMoritz Sichert
2017a0a59644SMoritz Sichert // Find out whether the code was compiled with the large or small memory
2018a0a59644SMoritz Sichert // model. For this we look at the next relocation which is the relocation
2019a0a59644SMoritz Sichert // for the __tls_get_addr function. If it's a 32 bit relocation, it's the
2020a0a59644SMoritz Sichert // small code model, with a 64 bit relocation it's the large code model.
2021a0a59644SMoritz Sichert bool IsSmallCodeModel;
2022a0a59644SMoritz Sichert // Is the relocation for the __tls_get_addr a PC-relative GOT relocation?
2023a0a59644SMoritz Sichert bool IsGOTPCRel = false;
2024a0a59644SMoritz Sichert
2025a0a59644SMoritz Sichert switch (GetAddrRelocation.getType()) {
2026a0a59644SMoritz Sichert case ELF::R_X86_64_GOTPCREL:
2027a0a59644SMoritz Sichert case ELF::R_X86_64_REX_GOTPCRELX:
2028a0a59644SMoritz Sichert case ELF::R_X86_64_GOTPCRELX:
2029a0a59644SMoritz Sichert IsGOTPCRel = true;
2030a0a59644SMoritz Sichert LLVM_FALLTHROUGH;
2031a0a59644SMoritz Sichert case ELF::R_X86_64_PLT32:
2032a0a59644SMoritz Sichert IsSmallCodeModel = true;
2033a0a59644SMoritz Sichert break;
2034a0a59644SMoritz Sichert case ELF::R_X86_64_PLTOFF64:
2035a0a59644SMoritz Sichert IsSmallCodeModel = false;
2036a0a59644SMoritz Sichert break;
2037a0a59644SMoritz Sichert default:
2038a0a59644SMoritz Sichert report_fatal_error(
2039a0a59644SMoritz Sichert "invalid TLS relocations for General/Local Dynamic TLS Model: "
2040a0a59644SMoritz Sichert "expected PLT or GOT relocation for __tls_get_addr function");
2041a0a59644SMoritz Sichert }
2042a0a59644SMoritz Sichert
2043a0a59644SMoritz Sichert // The negative offset to the start of the TLS code sequence relative to
2044a0a59644SMoritz Sichert // the offset of the TLSGD/TLSLD relocation
2045a0a59644SMoritz Sichert uint64_t TLSSequenceOffset;
2046a0a59644SMoritz Sichert // The expected start of the code sequence
2047a0a59644SMoritz Sichert ArrayRef<uint8_t> ExpectedCodeSequence;
2048a0a59644SMoritz Sichert // The new TLS code sequence that will replace the existing code
2049a0a59644SMoritz Sichert ArrayRef<uint8_t> NewCodeSequence;
2050a0a59644SMoritz Sichert
2051a0a59644SMoritz Sichert if (RelType == ELF::R_X86_64_TLSGD) {
2052a0a59644SMoritz Sichert // The offset of the new TPOFF32 relocation (offset starting from the
2053a0a59644SMoritz Sichert // beginning of the whole TLS sequence)
2054a0a59644SMoritz Sichert uint64_t TpoffRelocOffset;
2055a0a59644SMoritz Sichert
2056a0a59644SMoritz Sichert if (IsSmallCodeModel) {
2057a0a59644SMoritz Sichert if (!IsGOTPCRel) {
2058a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> CodeSequence = {
2059a0a59644SMoritz Sichert 0x66, // data16 (no-op prefix)
2060a0a59644SMoritz Sichert 0x48, 0x8d, 0x3d, 0x00, 0x00,
2061a0a59644SMoritz Sichert 0x00, 0x00, // lea <disp32>(%rip), %rdi
2062a0a59644SMoritz Sichert 0x66, 0x66, // two data16 prefixes
2063a0a59644SMoritz Sichert 0x48, // rex64 (no-op prefix)
2064a0a59644SMoritz Sichert 0xe8, 0x00, 0x00, 0x00, 0x00 // call __tls_get_addr@plt
2065a0a59644SMoritz Sichert };
2066a0a59644SMoritz Sichert ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2067a0a59644SMoritz Sichert TLSSequenceOffset = 4;
2068a0a59644SMoritz Sichert } else {
2069a0a59644SMoritz Sichert // This code sequence is not described in the TLS spec but gcc
2070a0a59644SMoritz Sichert // generates it sometimes.
2071a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> CodeSequence = {
2072a0a59644SMoritz Sichert 0x66, // data16 (no-op prefix)
2073a0a59644SMoritz Sichert 0x48, 0x8d, 0x3d, 0x00, 0x00,
2074a0a59644SMoritz Sichert 0x00, 0x00, // lea <disp32>(%rip), %rdi
2075a0a59644SMoritz Sichert 0x66, // data16 prefix (no-op prefix)
2076a0a59644SMoritz Sichert 0x48, // rex64 (no-op prefix)
2077a0a59644SMoritz Sichert 0xff, 0x15, 0x00, 0x00, 0x00,
2078a0a59644SMoritz Sichert 0x00 // call *__tls_get_addr@gotpcrel(%rip)
2079a0a59644SMoritz Sichert };
2080a0a59644SMoritz Sichert ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2081a0a59644SMoritz Sichert TLSSequenceOffset = 4;
2082a0a59644SMoritz Sichert }
2083a0a59644SMoritz Sichert
2084a0a59644SMoritz Sichert // The replacement code for the small code model. It's the same for
2085a0a59644SMoritz Sichert // both sequences.
2086a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> SmallSequence = {
2087a0a59644SMoritz Sichert 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00,
2088a0a59644SMoritz Sichert 0x00, // mov %fs:0, %rax
2089a0a59644SMoritz Sichert 0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00 // lea x@tpoff(%rax),
2090a0a59644SMoritz Sichert // %rax
2091a0a59644SMoritz Sichert };
2092a0a59644SMoritz Sichert NewCodeSequence = ArrayRef<uint8_t>(SmallSequence);
2093a0a59644SMoritz Sichert TpoffRelocOffset = 12;
2094a0a59644SMoritz Sichert } else {
2095a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> CodeSequence = {
2096a0a59644SMoritz Sichert 0x48, 0x8d, 0x3d, 0x00, 0x00, 0x00, 0x00, // lea <disp32>(%rip),
2097a0a59644SMoritz Sichert // %rdi
2098a0a59644SMoritz Sichert 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2099a0a59644SMoritz Sichert 0x00, // movabs $__tls_get_addr@pltoff, %rax
2100a0a59644SMoritz Sichert 0x48, 0x01, 0xd8, // add %rbx, %rax
2101a0a59644SMoritz Sichert 0xff, 0xd0 // call *%rax
2102a0a59644SMoritz Sichert };
2103a0a59644SMoritz Sichert ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2104a0a59644SMoritz Sichert TLSSequenceOffset = 3;
2105a0a59644SMoritz Sichert
2106a0a59644SMoritz Sichert // The replacement code for the large code model
2107a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> LargeSequence = {
2108a0a59644SMoritz Sichert 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00,
2109a0a59644SMoritz Sichert 0x00, // mov %fs:0, %rax
2110a0a59644SMoritz Sichert 0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00, // lea x@tpoff(%rax),
2111a0a59644SMoritz Sichert // %rax
2112a0a59644SMoritz Sichert 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00 // nopw 0x0(%rax,%rax,1)
2113a0a59644SMoritz Sichert };
2114a0a59644SMoritz Sichert NewCodeSequence = ArrayRef<uint8_t>(LargeSequence);
2115a0a59644SMoritz Sichert TpoffRelocOffset = 12;
2116a0a59644SMoritz Sichert }
2117a0a59644SMoritz Sichert
2118a0a59644SMoritz Sichert // The TLSGD/TLSLD relocations are PC-relative, so they have an addend.
2119a0a59644SMoritz Sichert // The new TPOFF32 relocations is used as an absolute offset from
2120a0a59644SMoritz Sichert // %fs:0, so remove the TLSGD/TLSLD addend again.
2121a0a59644SMoritz Sichert RelocationEntry RE(SectionID, Offset - TLSSequenceOffset + TpoffRelocOffset,
2122a0a59644SMoritz Sichert ELF::R_X86_64_TPOFF32, Value.Addend - Addend);
2123a0a59644SMoritz Sichert if (Value.SymbolName)
2124a0a59644SMoritz Sichert addRelocationForSymbol(RE, Value.SymbolName);
2125a0a59644SMoritz Sichert else
2126a0a59644SMoritz Sichert addRelocationForSection(RE, Value.SectionID);
2127a0a59644SMoritz Sichert } else if (RelType == ELF::R_X86_64_TLSLD) {
2128a0a59644SMoritz Sichert if (IsSmallCodeModel) {
2129a0a59644SMoritz Sichert if (!IsGOTPCRel) {
2130a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> CodeSequence = {
2131a0a59644SMoritz Sichert 0x48, 0x8d, 0x3d, 0x00, 0x00, 0x00, // leaq <disp32>(%rip), %rdi
2132a0a59644SMoritz Sichert 0x00, 0xe8, 0x00, 0x00, 0x00, 0x00 // call __tls_get_addr@plt
2133a0a59644SMoritz Sichert };
2134a0a59644SMoritz Sichert ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2135a0a59644SMoritz Sichert TLSSequenceOffset = 3;
2136a0a59644SMoritz Sichert
2137a0a59644SMoritz Sichert // The replacement code for the small code model
2138a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> SmallSequence = {
2139a0a59644SMoritz Sichert 0x66, 0x66, 0x66, // three data16 prefixes (no-op)
2140a0a59644SMoritz Sichert 0x64, 0x48, 0x8b, 0x04, 0x25,
2141a0a59644SMoritz Sichert 0x00, 0x00, 0x00, 0x00 // mov %fs:0, %rax
2142a0a59644SMoritz Sichert };
2143a0a59644SMoritz Sichert NewCodeSequence = ArrayRef<uint8_t>(SmallSequence);
2144a0a59644SMoritz Sichert } else {
2145a0a59644SMoritz Sichert // This code sequence is not described in the TLS spec but gcc
2146a0a59644SMoritz Sichert // generates it sometimes.
2147a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> CodeSequence = {
2148a0a59644SMoritz Sichert 0x48, 0x8d, 0x3d, 0x00,
2149a0a59644SMoritz Sichert 0x00, 0x00, 0x00, // leaq <disp32>(%rip), %rdi
2150a0a59644SMoritz Sichert 0xff, 0x15, 0x00, 0x00,
2151a0a59644SMoritz Sichert 0x00, 0x00 // call
2152a0a59644SMoritz Sichert // *__tls_get_addr@gotpcrel(%rip)
2153a0a59644SMoritz Sichert };
2154a0a59644SMoritz Sichert ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2155a0a59644SMoritz Sichert TLSSequenceOffset = 3;
2156a0a59644SMoritz Sichert
2157a0a59644SMoritz Sichert // The replacement is code is just like above but it needs to be
2158a0a59644SMoritz Sichert // one byte longer.
2159a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> SmallSequence = {
2160a0a59644SMoritz Sichert 0x0f, 0x1f, 0x40, 0x00, // 4 byte nop
2161a0a59644SMoritz Sichert 0x64, 0x48, 0x8b, 0x04, 0x25,
2162a0a59644SMoritz Sichert 0x00, 0x00, 0x00, 0x00 // mov %fs:0, %rax
2163a0a59644SMoritz Sichert };
2164a0a59644SMoritz Sichert NewCodeSequence = ArrayRef<uint8_t>(SmallSequence);
2165a0a59644SMoritz Sichert }
2166a0a59644SMoritz Sichert } else {
2167a0a59644SMoritz Sichert // This is the same sequence as for the TLSGD sequence with the large
2168a0a59644SMoritz Sichert // memory model above
2169a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> CodeSequence = {
2170a0a59644SMoritz Sichert 0x48, 0x8d, 0x3d, 0x00, 0x00, 0x00, 0x00, // lea <disp32>(%rip),
2171a0a59644SMoritz Sichert // %rdi
2172a0a59644SMoritz Sichert 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2173a0a59644SMoritz Sichert 0x48, // movabs $__tls_get_addr@pltoff, %rax
2174a0a59644SMoritz Sichert 0x01, 0xd8, // add %rbx, %rax
2175a0a59644SMoritz Sichert 0xff, 0xd0 // call *%rax
2176a0a59644SMoritz Sichert };
2177a0a59644SMoritz Sichert ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2178a0a59644SMoritz Sichert TLSSequenceOffset = 3;
2179a0a59644SMoritz Sichert
2180a0a59644SMoritz Sichert // The replacement code for the large code model
2181a0a59644SMoritz Sichert static const std::initializer_list<uint8_t> LargeSequence = {
2182a0a59644SMoritz Sichert 0x66, 0x66, 0x66, // three data16 prefixes (no-op)
2183a0a59644SMoritz Sichert 0x66, 0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00,
2184a0a59644SMoritz Sichert 0x00, // 10 byte nop
2185a0a59644SMoritz Sichert 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00 // mov %fs:0,%rax
2186a0a59644SMoritz Sichert };
2187a0a59644SMoritz Sichert NewCodeSequence = ArrayRef<uint8_t>(LargeSequence);
2188a0a59644SMoritz Sichert }
2189a0a59644SMoritz Sichert } else {
2190a0a59644SMoritz Sichert llvm_unreachable("both TLS relocations handled above");
2191a0a59644SMoritz Sichert }
2192a0a59644SMoritz Sichert
2193a0a59644SMoritz Sichert assert(ExpectedCodeSequence.size() == NewCodeSequence.size() &&
2194a0a59644SMoritz Sichert "Old and new code sequences must have the same size");
2195a0a59644SMoritz Sichert
2196a0a59644SMoritz Sichert auto &Section = Sections[SectionID];
2197a0a59644SMoritz Sichert if (Offset < TLSSequenceOffset ||
2198a0a59644SMoritz Sichert (Offset - TLSSequenceOffset + NewCodeSequence.size()) >
2199a0a59644SMoritz Sichert Section.getSize()) {
2200a0a59644SMoritz Sichert report_fatal_error("unexpected end of section in TLS sequence");
2201a0a59644SMoritz Sichert }
2202a0a59644SMoritz Sichert
2203a0a59644SMoritz Sichert auto *TLSSequence = Section.getAddressWithOffset(Offset - TLSSequenceOffset);
2204a0a59644SMoritz Sichert if (ArrayRef<uint8_t>(TLSSequence, ExpectedCodeSequence.size()) !=
2205a0a59644SMoritz Sichert ExpectedCodeSequence) {
2206a0a59644SMoritz Sichert report_fatal_error(
2207a0a59644SMoritz Sichert "invalid TLS sequence for Global/Local Dynamic TLS Model");
2208a0a59644SMoritz Sichert }
2209a0a59644SMoritz Sichert
2210a0a59644SMoritz Sichert memcpy(TLSSequence, NewCodeSequence.data(), NewCodeSequence.size());
2211a0a59644SMoritz Sichert }
2212a0a59644SMoritz Sichert
getGOTEntrySize()22134612fed9SAndrew Kaylor size_t RuntimeDyldELF::getGOTEntrySize() {
22144612fed9SAndrew Kaylor // We don't use the GOT in all of these cases, but it's essentially free
22154612fed9SAndrew Kaylor // to put them all here.
22164612fed9SAndrew Kaylor size_t Result = 0;
22174612fed9SAndrew Kaylor switch (Arch) {
22184612fed9SAndrew Kaylor case Triple::x86_64:
22194612fed9SAndrew Kaylor case Triple::aarch64:
2220bd2ffa0fSJames Molloy case Triple::aarch64_be:
22214612fed9SAndrew Kaylor case Triple::ppc64:
22224612fed9SAndrew Kaylor case Triple::ppc64le:
22234612fed9SAndrew Kaylor case Triple::systemz:
22244612fed9SAndrew Kaylor Result = sizeof(uint64_t);
22254612fed9SAndrew Kaylor break;
22264612fed9SAndrew Kaylor case Triple::x86:
22274612fed9SAndrew Kaylor case Triple::arm:
22284612fed9SAndrew Kaylor case Triple::thumb:
22299720283eSPetar Jovanovic Result = sizeof(uint32_t);
22309720283eSPetar Jovanovic break;
22314612fed9SAndrew Kaylor case Triple::mips:
22324612fed9SAndrew Kaylor case Triple::mipsel:
22339720283eSPetar Jovanovic case Triple::mips64:
22349720283eSPetar Jovanovic case Triple::mips64el:
2235226752c1SSimon Dardis if (IsMipsO32ABI || IsMipsN32ABI)
22364612fed9SAndrew Kaylor Result = sizeof(uint32_t);
22379720283eSPetar Jovanovic else if (IsMipsN64ABI)
22389720283eSPetar Jovanovic Result = sizeof(uint64_t);
22399720283eSPetar Jovanovic else
22409720283eSPetar Jovanovic llvm_unreachable("Mips ABI not handled");
22414612fed9SAndrew Kaylor break;
22427608dc04SJuergen Ributzka default:
22437608dc04SJuergen Ributzka llvm_unreachable("Unsupported CPU type!");
22444612fed9SAndrew Kaylor }
22454612fed9SAndrew Kaylor return Result;
22464612fed9SAndrew Kaylor }
22474612fed9SAndrew Kaylor
allocateGOTEntries(unsigned no)22483e582c88SEugene Leviant uint64_t RuntimeDyldELF::allocateGOTEntries(unsigned no) {
224902628defSKeno Fischer if (GOTSectionID == 0) {
225002628defSKeno Fischer GOTSectionID = Sections.size();
225102628defSKeno Fischer // Reserve a section id. We'll allocate the section later
225202628defSKeno Fischer // once we know the total size
22538082592aSSanjoy Das Sections.push_back(SectionEntry(".got", nullptr, 0, 0, 0));
22544612fed9SAndrew Kaylor }
225502628defSKeno Fischer uint64_t StartOffset = CurrentGOTIndex * getGOTEntrySize();
225602628defSKeno Fischer CurrentGOTIndex += no;
225702628defSKeno Fischer return StartOffset;
22584612fed9SAndrew Kaylor }
22594612fed9SAndrew Kaylor
findOrAllocGOTEntry(const RelocationValueRef & Value,unsigned GOTRelType)22603e582c88SEugene Leviant uint64_t RuntimeDyldELF::findOrAllocGOTEntry(const RelocationValueRef &Value,
22613e582c88SEugene Leviant unsigned GOTRelType) {
22623e582c88SEugene Leviant auto E = GOTOffsetMap.insert({Value, 0});
22633e582c88SEugene Leviant if (E.second) {
22643e582c88SEugene Leviant uint64_t GOTOffset = allocateGOTEntries(1);
22653e582c88SEugene Leviant
22663e582c88SEugene Leviant // Create relocation for newly created GOT entry
22673e582c88SEugene Leviant RelocationEntry RE =
22683e582c88SEugene Leviant computeGOTOffsetRE(GOTOffset, Value.Offset, GOTRelType);
22693e582c88SEugene Leviant if (Value.SymbolName)
22703e582c88SEugene Leviant addRelocationForSymbol(RE, Value.SymbolName);
22713e582c88SEugene Leviant else
22723e582c88SEugene Leviant addRelocationForSection(RE, Value.SectionID);
22733e582c88SEugene Leviant
22743e582c88SEugene Leviant E.first->second = GOTOffset;
22753e582c88SEugene Leviant }
22763e582c88SEugene Leviant
22773e582c88SEugene Leviant return E.first->second;
22783e582c88SEugene Leviant }
22793e582c88SEugene Leviant
resolveGOTOffsetRelocation(unsigned SectionID,uint64_t Offset,uint64_t GOTOffset,uint32_t Type)22803e582c88SEugene Leviant void RuntimeDyldELF::resolveGOTOffsetRelocation(unsigned SectionID,
22813e582c88SEugene Leviant uint64_t Offset,
22823e582c88SEugene Leviant uint64_t GOTOffset,
22833e582c88SEugene Leviant uint32_t Type) {
228402628defSKeno Fischer // Fill in the relative address of the GOT Entry into the stub
22853e582c88SEugene Leviant RelocationEntry GOTRE(SectionID, Offset, Type, GOTOffset);
228602628defSKeno Fischer addRelocationForSection(GOTRE, GOTSectionID);
22874612fed9SAndrew Kaylor }
22884612fed9SAndrew Kaylor
computeGOTOffsetRE(uint64_t GOTOffset,uint64_t SymbolOffset,uint32_t Type)22893e582c88SEugene Leviant RelocationEntry RuntimeDyldELF::computeGOTOffsetRE(uint64_t GOTOffset,
22903e582c88SEugene Leviant uint64_t SymbolOffset,
22913e582c88SEugene Leviant uint32_t Type) {
229202628defSKeno Fischer return RelocationEntry(GOTSectionID, GOTOffset, Type, SymbolOffset);
2293480dcb3eSAndrew Kaylor }
22944612fed9SAndrew Kaylor
finalizeLoad(const ObjectFile & Obj,ObjSectionToIDMap & SectionMap)22958959531cSLang Hames Error RuntimeDyldELF::finalizeLoad(const ObjectFile &Obj,
229636072da3SLang Hames ObjSectionToIDMap &SectionMap) {
2297d22164dcSPetar Jovanovic if (IsMipsO32ABI)
2298d22164dcSPetar Jovanovic if (!PendingRelocs.empty())
22998959531cSLang Hames return make_error<RuntimeDyldError>("Can't find matching LO16 reloc");
2300d22164dcSPetar Jovanovic
23017bb1344cSAndrew Kaylor // If necessary, allocate the global offset table
230202628defSKeno Fischer if (GOTSectionID != 0) {
23034612fed9SAndrew Kaylor // Allocate memory for the section
230402628defSKeno Fischer size_t TotalSize = CurrentGOTIndex * getGOTEntrySize();
2305633fe146SLang Hames uint8_t *Addr = MemMgr.allocateDataSection(TotalSize, getGOTEntrySize(),
230602628defSKeno Fischer GOTSectionID, ".got", false);
23074612fed9SAndrew Kaylor if (!Addr)
23088959531cSLang Hames return make_error<RuntimeDyldError>("Unable to allocate memory for GOT!");
2309480dcb3eSAndrew Kaylor
23108082592aSSanjoy Das Sections[GOTSectionID] =
23118082592aSSanjoy Das SectionEntry(".got", Addr, TotalSize, TotalSize, 0);
231202628defSKeno Fischer
23134612fed9SAndrew Kaylor // For now, initialize all GOT entries to zero. We'll fill them in as
23144612fed9SAndrew Kaylor // needed when GOT-based relocations are applied.
23154612fed9SAndrew Kaylor memset(Addr, 0, TotalSize);
2316226752c1SSimon Dardis if (IsMipsN32ABI || IsMipsN64ABI) {
23179720283eSPetar Jovanovic // To correctly resolve Mips GOT relocations, we need a mapping from
23189720283eSPetar Jovanovic // object's sections to GOTs.
23199720283eSPetar Jovanovic for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
23209720283eSPetar Jovanovic SI != SE; ++SI) {
23219720283eSPetar Jovanovic if (SI->relocation_begin() != SI->relocation_end()) {
23222bf01dcbSGeorge Rimar Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
23232bf01dcbSGeorge Rimar if (!RelSecOrErr)
23242bf01dcbSGeorge Rimar return make_error<RuntimeDyldError>(
23252bf01dcbSGeorge Rimar toString(RelSecOrErr.takeError()));
23262bf01dcbSGeorge Rimar
23272bf01dcbSGeorge Rimar section_iterator RelocatedSection = *RelSecOrErr;
23289720283eSPetar Jovanovic ObjSectionToIDMap::iterator i = SectionMap.find(*RelocatedSection);
23299720283eSPetar Jovanovic assert (i != SectionMap.end());
23309720283eSPetar Jovanovic SectionToGOTMap[i->second] = GOTSectionID;
23319720283eSPetar Jovanovic }
23329720283eSPetar Jovanovic }
23339720283eSPetar Jovanovic GOTSymbolOffsets.clear();
23349720283eSPetar Jovanovic }
2335480dcb3eSAndrew Kaylor }
23367bb1344cSAndrew Kaylor
23377bb1344cSAndrew Kaylor // Look for and record the EH frame section.
23387bb1344cSAndrew Kaylor ObjSectionToIDMap::iterator i, e;
23397bb1344cSAndrew Kaylor for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
23407bb1344cSAndrew Kaylor const SectionRef &Section = i->first;
2341bcc00e1aSGeorge Rimar
23427bb1344cSAndrew Kaylor StringRef Name;
2343bcc00e1aSGeorge Rimar Expected<StringRef> NameOrErr = Section.getName();
2344bcc00e1aSGeorge Rimar if (NameOrErr)
2345bcc00e1aSGeorge Rimar Name = *NameOrErr;
2346bcc00e1aSGeorge Rimar else
2347bcc00e1aSGeorge Rimar consumeError(NameOrErr.takeError());
2348bcc00e1aSGeorge Rimar
23497bb1344cSAndrew Kaylor if (Name == ".eh_frame") {
23507bb1344cSAndrew Kaylor UnregisteredEHFrameSections.push_back(i->second);
23517bb1344cSAndrew Kaylor break;
23527bb1344cSAndrew Kaylor }
23537bb1344cSAndrew Kaylor }
235402628defSKeno Fischer
235502628defSKeno Fischer GOTSectionID = 0;
235602628defSKeno Fischer CurrentGOTIndex = 0;
23578959531cSLang Hames
23588959531cSLang Hames return Error::success();
23594612fed9SAndrew Kaylor }
23604612fed9SAndrew Kaylor
isCompatibleFile(const object::ObjectFile & Obj) const2361b5c7b1ffSLang Hames bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile &Obj) const {
2362b5c7b1ffSLang Hames return Obj.isELF();
2363173c69f2SLang Hames }
2364173c69f2SLang Hames
relocationNeedsGot(const RelocationRef & R) const23653e582c88SEugene Leviant bool RuntimeDyldELF::relocationNeedsGot(const RelocationRef &R) const {
23663e582c88SEugene Leviant unsigned RelTy = R.getType();
23673e582c88SEugene Leviant if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be)
23683e582c88SEugene Leviant return RelTy == ELF::R_AARCH64_ADR_GOT_PAGE ||
23693e582c88SEugene Leviant RelTy == ELF::R_AARCH64_LD64_GOT_LO12_NC;
23703e582c88SEugene Leviant
23713e582c88SEugene Leviant if (Arch == Triple::x86_64)
23723e582c88SEugene Leviant return RelTy == ELF::R_X86_64_GOTPCREL ||
23733e582c88SEugene Leviant RelTy == ELF::R_X86_64_GOTPCRELX ||
2374330f65b3SReid Kleckner RelTy == ELF::R_X86_64_GOT64 ||
23753e582c88SEugene Leviant RelTy == ELF::R_X86_64_REX_GOTPCRELX;
23763e582c88SEugene Leviant return false;
23773e582c88SEugene Leviant }
23783e582c88SEugene Leviant
relocationNeedsStub(const RelocationRef & R) const2379d5658b08SSanjoy Das bool RuntimeDyldELF::relocationNeedsStub(const RelocationRef &R) const {
2380d5658b08SSanjoy Das if (Arch != Triple::x86_64)
2381d5658b08SSanjoy Das return true; // Conservative answer
2382d5658b08SSanjoy Das
2383d5658b08SSanjoy Das switch (R.getType()) {
2384d5658b08SSanjoy Das default:
2385d5658b08SSanjoy Das return true; // Conservative answer
2386d5658b08SSanjoy Das
2387d5658b08SSanjoy Das
2388d5658b08SSanjoy Das case ELF::R_X86_64_GOTPCREL:
2389cefdf238SDavide Italiano case ELF::R_X86_64_GOTPCRELX:
2390cefdf238SDavide Italiano case ELF::R_X86_64_REX_GOTPCRELX:
2391330f65b3SReid Kleckner case ELF::R_X86_64_GOTPC64:
2392330f65b3SReid Kleckner case ELF::R_X86_64_GOT64:
2393330f65b3SReid Kleckner case ELF::R_X86_64_GOTOFF64:
2394d5658b08SSanjoy Das case ELF::R_X86_64_PC32:
2395d5658b08SSanjoy Das case ELF::R_X86_64_PC64:
2396d5658b08SSanjoy Das case ELF::R_X86_64_64:
2397d5658b08SSanjoy Das // We know that these reloation types won't need a stub function. This list
2398d5658b08SSanjoy Das // can be extended as needed.
2399d5658b08SSanjoy Das return false;
2400d5658b08SSanjoy Das }
2401d5658b08SSanjoy Das }
2402d5658b08SSanjoy Das
24034c647587SEli Bendersky } // namespace llvm
2404