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