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