062d402610a744ebf5c93a8a15717f7d7f703cab
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / Targets / RuntimeDyldMachOAArch64.h
1 //===-- RuntimeDyldMachOAArch64.h -- MachO/AArch64 specific code. -*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDMACHOAARCH64_H
11 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDMACHOAARCH64_H
12
13 #include "../RuntimeDyldMachO.h"
14 #include "llvm/Support/Endian.h"
15
16 #define DEBUG_TYPE "dyld"
17
18 namespace llvm {
19
20 class RuntimeDyldMachOAArch64
21     : public RuntimeDyldMachOCRTPBase<RuntimeDyldMachOAArch64> {
22 public:
23   RuntimeDyldMachOAArch64(RTDyldMemoryManager *MM)
24       : RuntimeDyldMachOCRTPBase(MM) {}
25
26   unsigned getMaxStubSize() override { return 8; }
27
28   unsigned getStubAlignment() override { return 8; }
29
30   /// Extract the addend encoded in the instruction / memory location.
31   int64_t decodeAddend(const RelocationEntry &RE) const {
32     const SectionEntry &Section = Sections[RE.SectionID];
33     uint8_t *LocalAddress = Section.Address + RE.Offset;
34     unsigned NumBytes = 1 << RE.Size;
35     int64_t Addend = 0;
36     // Verify that the relocation has the correct size and alignment.
37     switch (RE.RelType) {
38     default:
39       llvm_unreachable("Unsupported relocation type!");
40     case MachO::ARM64_RELOC_UNSIGNED:
41       assert((NumBytes == 4 || NumBytes == 8) && "Invalid relocation size.");
42       break;
43     case MachO::ARM64_RELOC_BRANCH26:
44     case MachO::ARM64_RELOC_PAGE21:
45     case MachO::ARM64_RELOC_PAGEOFF12:
46     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
47     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
48       assert(NumBytes == 4 && "Invalid relocation size.");
49       assert((((uintptr_t)LocalAddress & 0x3) == 0) &&
50              "Instruction address is not aligned to 4 bytes.");
51       break;
52     }
53
54     switch (RE.RelType) {
55     default:
56       llvm_unreachable("Unsupported relocation type!");
57     case MachO::ARM64_RELOC_UNSIGNED:
58       // This could be an unaligned memory location.
59       if (NumBytes == 4)
60         Addend = *reinterpret_cast<support::ulittle32_t *>(LocalAddress);
61       else
62         Addend = *reinterpret_cast<support::ulittle64_t *>(LocalAddress);
63       break;
64     case MachO::ARM64_RELOC_BRANCH26: {
65       // Verify that the relocation points to the expected branch instruction.
66       auto *p = reinterpret_cast<support::aligned_ulittle32_t *>(LocalAddress);
67       assert((*p & 0xFC000000) == 0x14000000 && "Expected branch instruction.");
68
69       // Get the 26 bit addend encoded in the branch instruction and sign-extend
70       // to 64 bit. The lower 2 bits are always zeros and are therefore implicit
71       // (<< 2).
72       Addend = (*p & 0x03FFFFFF) << 2;
73       Addend = SignExtend64(Addend, 28);
74       break;
75     }
76     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
77     case MachO::ARM64_RELOC_PAGE21: {
78       // Verify that the relocation points to the expected adrp instruction.
79       auto *p = reinterpret_cast<support::aligned_ulittle32_t *>(LocalAddress);
80       assert((*p & 0x9F000000) == 0x90000000 && "Expected adrp instruction.");
81
82       // Get the 21 bit addend encoded in the adrp instruction and sign-extend
83       // to 64 bit. The lower 12 bits (4096 byte page) are always zeros and are
84       // therefore implicit (<< 12).
85       Addend = ((*p & 0x60000000) >> 29) | ((*p & 0x01FFFFE0) >> 3) << 12;
86       Addend = SignExtend64(Addend, 33);
87       break;
88     }
89     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: {
90       // Verify that the relocation points to one of the expected load / store
91       // instructions.
92       auto *p = reinterpret_cast<support::aligned_ulittle32_t *>(LocalAddress);
93       (void)p;
94       assert((*p & 0x3B000000) == 0x39000000 &&
95              "Only expected load / store instructions.");
96     } // fall-through
97     case MachO::ARM64_RELOC_PAGEOFF12: {
98       // Verify that the relocation points to one of the expected load / store
99       // or add / sub instructions.
100       auto *p = reinterpret_cast<support::aligned_ulittle32_t *>(LocalAddress);
101       assert((((*p & 0x3B000000) == 0x39000000) ||
102               ((*p & 0x11C00000) == 0x11000000)   ) &&
103              "Expected load / store  or add/sub instruction.");
104
105       // Get the 12 bit addend encoded in the instruction.
106       Addend = (*p & 0x003FFC00) >> 10;
107
108       // Check which instruction we are decoding to obtain the implicit shift
109       // factor of the instruction.
110       int ImplicitShift = 0;
111       if ((*p & 0x3B000000) == 0x39000000) { // << load / store
112         // For load / store instructions the size is encoded in bits 31:30.
113         ImplicitShift = ((*p >> 30) & 0x3);
114         if (ImplicitShift == 0) {
115           // Check if this a vector op to get the correct shift value.
116           if ((*p & 0x04800000) == 0x04800000)
117             ImplicitShift = 4;
118         }
119       }
120       // Compensate for implicit shift.
121       Addend <<= ImplicitShift;
122       break;
123     }
124     }
125     return Addend;
126   }
127
128   /// Extract the addend encoded in the instruction.
129   void encodeAddend(uint8_t *LocalAddress, unsigned NumBytes,
130                     MachO::RelocationInfoType RelType, int64_t Addend) const {
131     // Verify that the relocation has the correct alignment.
132     switch (RelType) {
133     default:
134       llvm_unreachable("Unsupported relocation type!");
135     case MachO::ARM64_RELOC_UNSIGNED:
136       assert((NumBytes == 4 || NumBytes == 8) && "Invalid relocation size.");
137       break;
138     case MachO::ARM64_RELOC_BRANCH26:
139     case MachO::ARM64_RELOC_PAGE21:
140     case MachO::ARM64_RELOC_PAGEOFF12:
141     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
142     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
143       assert(NumBytes == 4 && "Invalid relocation size.");
144       assert((((uintptr_t)LocalAddress & 0x3) == 0) &&
145              "Instruction address is not aligned to 4 bytes.");
146       break;
147     }
148
149     switch (RelType) {
150     default:
151       llvm_unreachable("Unsupported relocation type!");
152     case MachO::ARM64_RELOC_UNSIGNED:
153       // This could be an unaligned memory location.
154       if (NumBytes == 4)
155         *reinterpret_cast<support::ulittle32_t *>(LocalAddress) = Addend;
156       else
157         *reinterpret_cast<support::ulittle64_t *>(LocalAddress) = Addend;
158       break;
159     case MachO::ARM64_RELOC_BRANCH26: {
160       auto *p = reinterpret_cast<support::aligned_ulittle32_t *>(LocalAddress);
161       // Verify that the relocation points to the expected branch instruction.
162       assert((*p & 0xFC000000) == 0x14000000 && "Expected branch instruction.");
163
164       // Verify addend value.
165       assert((Addend & 0x3) == 0 && "Branch target is not aligned");
166       assert(isInt<28>(Addend) && "Branch target is out of range.");
167
168       // Encode the addend as 26 bit immediate in the branch instruction.
169       *p = (*p & 0xFC000000) | ((uint32_t)(Addend >> 2) & 0x03FFFFFF);
170       break;
171     }
172     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
173     case MachO::ARM64_RELOC_PAGE21: {
174       // Verify that the relocation points to the expected adrp instruction.
175       auto *p = reinterpret_cast<support::aligned_ulittle32_t *>(LocalAddress);
176       assert((*p & 0x9F000000) == 0x90000000 && "Expected adrp instruction.");
177
178       // Check that the addend fits into 21 bits (+ 12 lower bits).
179       assert((Addend & 0xFFF) == 0 && "ADRP target is not page aligned.");
180       assert(isInt<33>(Addend) && "Invalid page reloc value.");
181
182       // Encode the addend into the instruction.
183       uint32_t ImmLoValue = (uint32_t)(Addend << 17) & 0x60000000;
184       uint32_t ImmHiValue = (uint32_t)(Addend >> 9) & 0x00FFFFE0;
185       *p = (*p & 0x9F00001F) | ImmHiValue | ImmLoValue;
186       break;
187     }
188     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: {
189       // Verify that the relocation points to one of the expected load / store
190       // instructions.
191       auto *p = reinterpret_cast<support::aligned_ulittle32_t *>(LocalAddress);
192       assert((*p & 0x3B000000) == 0x39000000 &&
193              "Only expected load / store instructions.");
194       (void)p;
195     } // fall-through
196     case MachO::ARM64_RELOC_PAGEOFF12: {
197       // Verify that the relocation points to one of the expected load / store
198       // or add / sub instructions.
199       auto *p = reinterpret_cast<support::aligned_ulittle32_t *>(LocalAddress);
200       assert((((*p & 0x3B000000) == 0x39000000) ||
201               ((*p & 0x11C00000) == 0x11000000)   ) &&
202              "Expected load / store  or add/sub instruction.");
203
204       // Check which instruction we are decoding to obtain the implicit shift
205       // factor of the instruction and verify alignment.
206       int ImplicitShift = 0;
207       if ((*p & 0x3B000000) == 0x39000000) { // << load / store
208         // For load / store instructions the size is encoded in bits 31:30.
209         ImplicitShift = ((*p >> 30) & 0x3);
210         switch (ImplicitShift) {
211         case 0:
212           // Check if this a vector op to get the correct shift value.
213           if ((*p & 0x04800000) == 0x04800000) {
214             ImplicitShift = 4;
215             assert(((Addend & 0xF) == 0) &&
216                    "128-bit LDR/STR not 16-byte aligned.");
217           }
218           break;
219         case 1:
220           assert(((Addend & 0x1) == 0) && "16-bit LDR/STR not 2-byte aligned.");
221           break;
222         case 2:
223           assert(((Addend & 0x3) == 0) && "32-bit LDR/STR not 4-byte aligned.");
224           break;
225         case 3:
226           assert(((Addend & 0x7) == 0) && "64-bit LDR/STR not 8-byte aligned.");
227           break;
228         }
229       }
230       // Compensate for implicit shift.
231       Addend >>= ImplicitShift;
232       assert(isUInt<12>(Addend) && "Addend cannot be encoded.");
233
234       // Encode the addend into the instruction.
235       *p = (*p & 0xFFC003FF) | ((uint32_t)(Addend << 10) & 0x003FFC00);
236       break;
237     }
238     }
239   }
240
241   relocation_iterator
242   processRelocationRef(unsigned SectionID, relocation_iterator RelI,
243                        ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
244                        const SymbolTableMap &Symbols, StubMap &Stubs) override {
245     const MachOObjectFile &Obj =
246         static_cast<const MachOObjectFile &>(*ObjImg.getObjectFile());
247     MachO::any_relocation_info RelInfo =
248         Obj.getRelocation(RelI->getRawDataRefImpl());
249
250     assert(!Obj.isRelocationScattered(RelInfo) && "");
251
252     // ARM64 has an ARM64_RELOC_ADDEND relocation type that carries an explicit
253     // addend for the following relocation. If found: (1) store the associated
254     // addend, (2) consume the next relocation, and (3) use the stored addend to
255     // override the addend.
256     int64_t ExplicitAddend = 0;
257     if (Obj.getAnyRelocationType(RelInfo) == MachO::ARM64_RELOC_ADDEND) {
258       assert(!Obj.getPlainRelocationExternal(RelInfo));
259       assert(!Obj.getAnyRelocationPCRel(RelInfo));
260       assert(Obj.getAnyRelocationLength(RelInfo) == 2);
261       int64_t RawAddend = Obj.getPlainRelocationSymbolNum(RelInfo);
262       // Sign-extend the 24-bit to 64-bit.
263       ExplicitAddend = SignExtend64(RawAddend, 24);
264       ++RelI;
265       RelInfo = Obj.getRelocation(RelI->getRawDataRefImpl());
266     }
267
268     RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
269     RE.Addend = decodeAddend(RE);
270     RelocationValueRef Value(
271         getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
272
273     assert((ExplicitAddend == 0 || RE.Addend == 0) && "Relocation has "\
274       "ARM64_RELOC_ADDEND and embedded addend in the instruction.");
275     if (ExplicitAddend) {
276       RE.Addend = ExplicitAddend;
277       Value.Addend = ExplicitAddend;
278     }
279
280     bool IsExtern = Obj.getPlainRelocationExternal(RelInfo);
281     if (!IsExtern && RE.IsPCRel)
282       makeValueAddendPCRel(Value, ObjImg, RelI, 1 << RE.Size);
283
284     RE.Addend = Value.Addend;
285
286     if (RE.RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGE21 ||
287         RE.RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12)
288       processGOTRelocation(RE, Value, Stubs);
289     else {
290       if (Value.SymbolName)
291         addRelocationForSymbol(RE, Value.SymbolName);
292       else
293         addRelocationForSection(RE, Value.SectionID);
294     }
295
296     return ++RelI;
297   }
298
299   void resolveRelocation(const RelocationEntry &RE, uint64_t Value) {
300     DEBUG(dumpRelocationToResolve(RE, Value));
301
302     const SectionEntry &Section = Sections[RE.SectionID];
303     uint8_t *LocalAddress = Section.Address + RE.Offset;
304     MachO::RelocationInfoType RelType =
305       static_cast<MachO::RelocationInfoType>(RE.RelType);
306
307     switch (RelType) {
308     default:
309       llvm_unreachable("Invalid relocation type!");
310     case MachO::ARM64_RELOC_UNSIGNED: {
311       assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_UNSIGNED not supported");
312       // Mask in the target value a byte at a time (we don't have an alignment
313       // guarantee for the target address, so this is safest).
314       if (RE.Size < 2)
315         llvm_unreachable("Invalid size for ARM64_RELOC_UNSIGNED");
316
317       encodeAddend(LocalAddress, 1 << RE.Size, RelType, Value + RE.Addend);
318       break;
319     }
320     case MachO::ARM64_RELOC_BRANCH26: {
321       assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_BRANCH26 not supported");
322       // Check if branch is in range.
323       uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
324       int64_t PCRelVal = Value - FinalAddress + RE.Addend;
325       encodeAddend(LocalAddress, /*Size=*/4, RelType, PCRelVal);
326       break;
327     }
328     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
329     case MachO::ARM64_RELOC_PAGE21: {
330       assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_PAGE21 not supported");
331       // Adjust for PC-relative relocation and offset.
332       uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
333       int64_t PCRelVal =
334         ((Value + RE.Addend) & (-4096)) - (FinalAddress & (-4096));
335       encodeAddend(LocalAddress, /*Size=*/4, RelType, PCRelVal);
336       break;
337     }
338     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
339     case MachO::ARM64_RELOC_PAGEOFF12: {
340       assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_PAGEOFF21 not supported");
341       // Add the offset from the symbol.
342       Value += RE.Addend;
343       // Mask out the page address and only use the lower 12 bits.
344       Value &= 0xFFF;
345       encodeAddend(LocalAddress, /*Size=*/4, RelType, Value);
346       break;
347     }
348     case MachO::ARM64_RELOC_SUBTRACTOR:
349     case MachO::ARM64_RELOC_POINTER_TO_GOT:
350     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
351     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
352       llvm_unreachable("Relocation type not yet implemented!");
353     case MachO::ARM64_RELOC_ADDEND:
354       llvm_unreachable("ARM64_RELOC_ADDEND should have been handeled by "
355                        "processRelocationRef!");
356     }
357   }
358
359   void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
360                        const SectionRef &Section) {}
361
362 private:
363   void processGOTRelocation(const RelocationEntry &RE,
364                             RelocationValueRef &Value, StubMap &Stubs) {
365     assert(RE.Size == 2);
366     SectionEntry &Section = Sections[RE.SectionID];
367     StubMap::const_iterator i = Stubs.find(Value);
368     uintptr_t Addr;
369     if (i != Stubs.end())
370       Addr = reinterpret_cast<uintptr_t>(Section.Address) + i->second;
371     else {
372       // FIXME: There must be a better way to do this then to check and fix the
373       // alignment every time!!!
374       uintptr_t BaseAddress = uintptr_t(Section.Address);
375       uintptr_t StubAlignment = getStubAlignment();
376       uintptr_t StubAddress =
377           (BaseAddress + Section.StubOffset + StubAlignment - 1) &
378           -StubAlignment;
379       unsigned StubOffset = StubAddress - BaseAddress;
380       Stubs[Value] = StubOffset;
381       assert(((StubAddress % getStubAlignment()) == 0) &&
382              "GOT entry not aligned");
383       RelocationEntry GOTRE(RE.SectionID, StubOffset,
384                             MachO::ARM64_RELOC_UNSIGNED, Value.Addend,
385                             /*IsPCRel=*/false, /*Size=*/3);
386       if (Value.SymbolName)
387         addRelocationForSymbol(GOTRE, Value.SymbolName);
388       else
389         addRelocationForSection(GOTRE, Value.SectionID);
390       Section.StubOffset = StubOffset + getMaxStubSize();
391       Addr = StubAddress;
392     }
393     RelocationEntry TargetRE(RE.SectionID, RE.Offset, RE.RelType, /*Addend=*/0,
394                              RE.IsPCRel, RE.Size);
395     resolveRelocation(TargetRE, static_cast<uint64_t>(Addr));
396   }
397 };
398 }
399
400 #undef DEBUG_TYPE
401
402 #endif