xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/AArch64.cpp (revision 8881d206f4e68b564c2c5f50fc717086fc3e827a)
1 //===- AArch64.cpp --------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Symbols.h"
10 #include "SyntheticSections.h"
11 #include "Target.h"
12 #include "Thunks.h"
13 #include "lld/Common/ErrorHandler.h"
14 #include "llvm/Object/ELF.h"
15 #include "llvm/Support/Endian.h"
16 
17 using namespace llvm;
18 using namespace llvm::support::endian;
19 using namespace llvm::ELF;
20 using namespace lld;
21 using namespace lld::elf;
22 
23 // Page(Expr) is the page address of the expression Expr, defined
24 // as (Expr & ~0xFFF). (This applies even if the machine page size
25 // supported by the platform has a different value.)
26 uint64_t elf::getAArch64Page(uint64_t expr) {
27   return expr & ~static_cast<uint64_t>(0xFFF);
28 }
29 
30 namespace {
31 class AArch64 : public TargetInfo {
32 public:
33   AArch64();
34   RelExpr getRelExpr(RelType type, const Symbol &s,
35                      const uint8_t *loc) const override;
36   RelType getDynRel(RelType type) const override;
37   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
38   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
39   void writePltHeader(uint8_t *buf) const override;
40   void writePlt(uint8_t *buf, const Symbol &sym,
41                 uint64_t pltEntryAddr) const override;
42   bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
43                   uint64_t branchAddr, const Symbol &s,
44                   int64_t a) const override;
45   uint32_t getThunkSectionSpacing() const override;
46   bool inBranchRange(RelType type, uint64_t src, uint64_t dst) const override;
47   bool usesOnlyLowPageBits(RelType type) const override;
48   void relocate(uint8_t *loc, const Relocation &rel,
49                 uint64_t val) const override;
50   RelExpr adjustTlsExpr(RelType type, RelExpr expr) const override;
51   void relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
52                       uint64_t val) const override;
53   void relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
54                       uint64_t val) const override;
55   void relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
56                       uint64_t val) const override;
57 };
58 } // namespace
59 
60 AArch64::AArch64() {
61   copyRel = R_AARCH64_COPY;
62   relativeRel = R_AARCH64_RELATIVE;
63   iRelativeRel = R_AARCH64_IRELATIVE;
64   gotRel = R_AARCH64_GLOB_DAT;
65   noneRel = R_AARCH64_NONE;
66   pltRel = R_AARCH64_JUMP_SLOT;
67   symbolicRel = R_AARCH64_ABS64;
68   tlsDescRel = R_AARCH64_TLSDESC;
69   tlsGotRel = R_AARCH64_TLS_TPREL64;
70   pltHeaderSize = 32;
71   pltEntrySize = 16;
72   ipltEntrySize = 16;
73   defaultMaxPageSize = 65536;
74   gotBaseSymInGotPlt = false;
75 
76   // Align to the 2 MiB page size (known as a superpage or huge page).
77   // FreeBSD automatically promotes 2 MiB-aligned allocations.
78   defaultImageBase = 0x200000;
79 
80   needsThunks = true;
81 }
82 
83 RelExpr AArch64::getRelExpr(RelType type, const Symbol &s,
84                             const uint8_t *loc) const {
85   switch (type) {
86   case R_AARCH64_ABS16:
87   case R_AARCH64_ABS32:
88   case R_AARCH64_ABS64:
89   case R_AARCH64_ADD_ABS_LO12_NC:
90   case R_AARCH64_LDST128_ABS_LO12_NC:
91   case R_AARCH64_LDST16_ABS_LO12_NC:
92   case R_AARCH64_LDST32_ABS_LO12_NC:
93   case R_AARCH64_LDST64_ABS_LO12_NC:
94   case R_AARCH64_LDST8_ABS_LO12_NC:
95   case R_AARCH64_MOVW_SABS_G0:
96   case R_AARCH64_MOVW_SABS_G1:
97   case R_AARCH64_MOVW_SABS_G2:
98   case R_AARCH64_MOVW_UABS_G0:
99   case R_AARCH64_MOVW_UABS_G0_NC:
100   case R_AARCH64_MOVW_UABS_G1:
101   case R_AARCH64_MOVW_UABS_G1_NC:
102   case R_AARCH64_MOVW_UABS_G2:
103   case R_AARCH64_MOVW_UABS_G2_NC:
104   case R_AARCH64_MOVW_UABS_G3:
105     return R_ABS;
106   case R_AARCH64_TLSDESC_ADR_PAGE21:
107     return R_AARCH64_TLSDESC_PAGE;
108   case R_AARCH64_TLSDESC_LD64_LO12:
109   case R_AARCH64_TLSDESC_ADD_LO12:
110     return R_TLSDESC;
111   case R_AARCH64_TLSDESC_CALL:
112     return R_TLSDESC_CALL;
113   case R_AARCH64_TLSLE_ADD_TPREL_HI12:
114   case R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
115   case R_AARCH64_TLSLE_LDST8_TPREL_LO12_NC:
116   case R_AARCH64_TLSLE_LDST16_TPREL_LO12_NC:
117   case R_AARCH64_TLSLE_LDST32_TPREL_LO12_NC:
118   case R_AARCH64_TLSLE_LDST64_TPREL_LO12_NC:
119   case R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC:
120   case R_AARCH64_TLSLE_MOVW_TPREL_G0:
121   case R_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
122   case R_AARCH64_TLSLE_MOVW_TPREL_G1:
123   case R_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
124   case R_AARCH64_TLSLE_MOVW_TPREL_G2:
125     return R_TPREL;
126   case R_AARCH64_CALL26:
127   case R_AARCH64_CONDBR19:
128   case R_AARCH64_JUMP26:
129   case R_AARCH64_TSTBR14:
130   case R_AARCH64_PLT32:
131     return R_PLT_PC;
132   case R_AARCH64_PREL16:
133   case R_AARCH64_PREL32:
134   case R_AARCH64_PREL64:
135   case R_AARCH64_ADR_PREL_LO21:
136   case R_AARCH64_LD_PREL_LO19:
137   case R_AARCH64_MOVW_PREL_G0:
138   case R_AARCH64_MOVW_PREL_G0_NC:
139   case R_AARCH64_MOVW_PREL_G1:
140   case R_AARCH64_MOVW_PREL_G1_NC:
141   case R_AARCH64_MOVW_PREL_G2:
142   case R_AARCH64_MOVW_PREL_G2_NC:
143   case R_AARCH64_MOVW_PREL_G3:
144     return R_PC;
145   case R_AARCH64_ADR_PREL_PG_HI21:
146   case R_AARCH64_ADR_PREL_PG_HI21_NC:
147     return R_AARCH64_PAGE_PC;
148   case R_AARCH64_LD64_GOT_LO12_NC:
149   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
150     return R_GOT;
151   case R_AARCH64_LD64_GOTPAGE_LO15:
152     return R_AARCH64_GOT_PAGE;
153   case R_AARCH64_ADR_GOT_PAGE:
154   case R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
155     return R_AARCH64_GOT_PAGE_PC;
156   case R_AARCH64_NONE:
157     return R_NONE;
158   default:
159     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
160           ") against symbol " + toString(s));
161     return R_NONE;
162   }
163 }
164 
165 RelExpr AArch64::adjustTlsExpr(RelType type, RelExpr expr) const {
166   if (expr == R_RELAX_TLS_GD_TO_IE) {
167     if (type == R_AARCH64_TLSDESC_ADR_PAGE21)
168       return R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC;
169     return R_RELAX_TLS_GD_TO_IE_ABS;
170   }
171   return expr;
172 }
173 
174 bool AArch64::usesOnlyLowPageBits(RelType type) const {
175   switch (type) {
176   default:
177     return false;
178   case R_AARCH64_ADD_ABS_LO12_NC:
179   case R_AARCH64_LD64_GOT_LO12_NC:
180   case R_AARCH64_LDST128_ABS_LO12_NC:
181   case R_AARCH64_LDST16_ABS_LO12_NC:
182   case R_AARCH64_LDST32_ABS_LO12_NC:
183   case R_AARCH64_LDST64_ABS_LO12_NC:
184   case R_AARCH64_LDST8_ABS_LO12_NC:
185   case R_AARCH64_TLSDESC_ADD_LO12:
186   case R_AARCH64_TLSDESC_LD64_LO12:
187   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
188     return true;
189   }
190 }
191 
192 RelType AArch64::getDynRel(RelType type) const {
193   if (type == R_AARCH64_ABS64)
194     return type;
195   return R_AARCH64_NONE;
196 }
197 
198 int64_t AArch64::getImplicitAddend(const uint8_t *buf, RelType type) const {
199   switch (type) {
200   case R_AARCH64_TLSDESC:
201     return read64(buf + 8);
202   case R_AARCH64_NONE:
203     return 0;
204   case R_AARCH64_PREL32:
205     return SignExtend64<32>(read32(buf));
206   case R_AARCH64_ABS64:
207   case R_AARCH64_PREL64:
208     return read64(buf);
209   default:
210     internalLinkerError(getErrorLocation(buf),
211                         "cannot read addend for relocation " + toString(type));
212     return 0;
213   }
214 }
215 
216 void AArch64::writeGotPlt(uint8_t *buf, const Symbol &) const {
217   write64(buf, in.plt->getVA());
218 }
219 
220 void AArch64::writePltHeader(uint8_t *buf) const {
221   const uint8_t pltData[] = {
222       0xf0, 0x7b, 0xbf, 0xa9, // stp    x16, x30, [sp,#-16]!
223       0x10, 0x00, 0x00, 0x90, // adrp   x16, Page(&(.plt.got[2]))
224       0x11, 0x02, 0x40, 0xf9, // ldr    x17, [x16, Offset(&(.plt.got[2]))]
225       0x10, 0x02, 0x00, 0x91, // add    x16, x16, Offset(&(.plt.got[2]))
226       0x20, 0x02, 0x1f, 0xd6, // br     x17
227       0x1f, 0x20, 0x03, 0xd5, // nop
228       0x1f, 0x20, 0x03, 0xd5, // nop
229       0x1f, 0x20, 0x03, 0xd5  // nop
230   };
231   memcpy(buf, pltData, sizeof(pltData));
232 
233   uint64_t got = in.gotPlt->getVA();
234   uint64_t plt = in.plt->getVA();
235   relocateNoSym(buf + 4, R_AARCH64_ADR_PREL_PG_HI21,
236                 getAArch64Page(got + 16) - getAArch64Page(plt + 4));
237   relocateNoSym(buf + 8, R_AARCH64_LDST64_ABS_LO12_NC, got + 16);
238   relocateNoSym(buf + 12, R_AARCH64_ADD_ABS_LO12_NC, got + 16);
239 }
240 
241 void AArch64::writePlt(uint8_t *buf, const Symbol &sym,
242                        uint64_t pltEntryAddr) const {
243   const uint8_t inst[] = {
244       0x10, 0x00, 0x00, 0x90, // adrp x16, Page(&(.plt.got[n]))
245       0x11, 0x02, 0x40, 0xf9, // ldr  x17, [x16, Offset(&(.plt.got[n]))]
246       0x10, 0x02, 0x00, 0x91, // add  x16, x16, Offset(&(.plt.got[n]))
247       0x20, 0x02, 0x1f, 0xd6  // br   x17
248   };
249   memcpy(buf, inst, sizeof(inst));
250 
251   uint64_t gotPltEntryAddr = sym.getGotPltVA();
252   relocateNoSym(buf, R_AARCH64_ADR_PREL_PG_HI21,
253                 getAArch64Page(gotPltEntryAddr) - getAArch64Page(pltEntryAddr));
254   relocateNoSym(buf + 4, R_AARCH64_LDST64_ABS_LO12_NC, gotPltEntryAddr);
255   relocateNoSym(buf + 8, R_AARCH64_ADD_ABS_LO12_NC, gotPltEntryAddr);
256 }
257 
258 bool AArch64::needsThunk(RelExpr expr, RelType type, const InputFile *file,
259                          uint64_t branchAddr, const Symbol &s,
260                          int64_t a) const {
261   // If s is an undefined weak symbol and does not have a PLT entry then it
262   // will be resolved as a branch to the next instruction.
263   if (s.isUndefWeak() && !s.isInPlt())
264     return false;
265   // ELF for the ARM 64-bit architecture, section Call and Jump relocations
266   // only permits range extension thunks for R_AARCH64_CALL26 and
267   // R_AARCH64_JUMP26 relocation types.
268   if (type != R_AARCH64_CALL26 && type != R_AARCH64_JUMP26 &&
269       type != R_AARCH64_PLT32)
270     return false;
271   uint64_t dst = expr == R_PLT_PC ? s.getPltVA() : s.getVA(a);
272   return !inBranchRange(type, branchAddr, dst);
273 }
274 
275 uint32_t AArch64::getThunkSectionSpacing() const {
276   // See comment in Arch/ARM.cpp for a more detailed explanation of
277   // getThunkSectionSpacing(). For AArch64 the only branches we are permitted to
278   // Thunk have a range of +/- 128 MiB
279   return (128 * 1024 * 1024) - 0x30000;
280 }
281 
282 bool AArch64::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
283   if (type != R_AARCH64_CALL26 && type != R_AARCH64_JUMP26 &&
284       type != R_AARCH64_PLT32)
285     return true;
286   // The AArch64 call and unconditional branch instructions have a range of
287   // +/- 128 MiB. The PLT32 relocation supports a range up to +/- 2 GiB.
288   uint64_t range =
289       type == R_AARCH64_PLT32 ? (UINT64_C(1) << 31) : (128 * 1024 * 1024);
290   if (dst > src) {
291     // Immediate of branch is signed.
292     range -= 4;
293     return dst - src <= range;
294   }
295   return src - dst <= range;
296 }
297 
298 static void write32AArch64Addr(uint8_t *l, uint64_t imm) {
299   uint32_t immLo = (imm & 0x3) << 29;
300   uint32_t immHi = (imm & 0x1FFFFC) << 3;
301   uint64_t mask = (0x3 << 29) | (0x1FFFFC << 3);
302   write32le(l, (read32le(l) & ~mask) | immLo | immHi);
303 }
304 
305 // Return the bits [Start, End] from Val shifted Start bits.
306 // For instance, getBits(0xF0, 4, 8) returns 0xF.
307 static uint64_t getBits(uint64_t val, int start, int end) {
308   uint64_t mask = ((uint64_t)1 << (end + 1 - start)) - 1;
309   return (val >> start) & mask;
310 }
311 
312 static void or32le(uint8_t *p, int32_t v) { write32le(p, read32le(p) | v); }
313 
314 // Update the immediate field in a AARCH64 ldr, str, and add instruction.
315 static void or32AArch64Imm(uint8_t *l, uint64_t imm) {
316   or32le(l, (imm & 0xFFF) << 10);
317 }
318 
319 // Update the immediate field in an AArch64 movk, movn or movz instruction
320 // for a signed relocation, and update the opcode of a movn or movz instruction
321 // to match the sign of the operand.
322 static void writeSMovWImm(uint8_t *loc, uint32_t imm) {
323   uint32_t inst = read32le(loc);
324   // Opcode field is bits 30, 29, with 10 = movz, 00 = movn and 11 = movk.
325   if (!(inst & (1 << 29))) {
326     // movn or movz.
327     if (imm & 0x10000) {
328       // Change opcode to movn, which takes an inverted operand.
329       imm ^= 0xFFFF;
330       inst &= ~(1 << 30);
331     } else {
332       // Change opcode to movz.
333       inst |= 1 << 30;
334     }
335   }
336   write32le(loc, inst | ((imm & 0xFFFF) << 5));
337 }
338 
339 void AArch64::relocate(uint8_t *loc, const Relocation &rel,
340                        uint64_t val) const {
341   switch (rel.type) {
342   case R_AARCH64_ABS16:
343   case R_AARCH64_PREL16:
344     checkIntUInt(loc, val, 16, rel);
345     write16(loc, val);
346     break;
347   case R_AARCH64_ABS32:
348   case R_AARCH64_PREL32:
349     checkIntUInt(loc, val, 32, rel);
350     write32(loc, val);
351     break;
352   case R_AARCH64_PLT32:
353     checkInt(loc, val, 32, rel);
354     write32(loc, val);
355     break;
356   case R_AARCH64_ABS64:
357   case R_AARCH64_PREL64:
358     write64(loc, val);
359     break;
360   case R_AARCH64_ADD_ABS_LO12_NC:
361     or32AArch64Imm(loc, val);
362     break;
363   case R_AARCH64_ADR_GOT_PAGE:
364   case R_AARCH64_ADR_PREL_PG_HI21:
365   case R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
366   case R_AARCH64_TLSDESC_ADR_PAGE21:
367     checkInt(loc, val, 33, rel);
368     LLVM_FALLTHROUGH;
369   case R_AARCH64_ADR_PREL_PG_HI21_NC:
370     write32AArch64Addr(loc, val >> 12);
371     break;
372   case R_AARCH64_ADR_PREL_LO21:
373     checkInt(loc, val, 21, rel);
374     write32AArch64Addr(loc, val);
375     break;
376   case R_AARCH64_JUMP26:
377     // Normally we would just write the bits of the immediate field, however
378     // when patching instructions for the cpu errata fix -fix-cortex-a53-843419
379     // we want to replace a non-branch instruction with a branch immediate
380     // instruction. By writing all the bits of the instruction including the
381     // opcode and the immediate (0 001 | 01 imm26) we can do this
382     // transformation by placing a R_AARCH64_JUMP26 relocation at the offset of
383     // the instruction we want to patch.
384     write32le(loc, 0x14000000);
385     LLVM_FALLTHROUGH;
386   case R_AARCH64_CALL26:
387     checkInt(loc, val, 28, rel);
388     or32le(loc, (val & 0x0FFFFFFC) >> 2);
389     break;
390   case R_AARCH64_CONDBR19:
391   case R_AARCH64_LD_PREL_LO19:
392     checkAlignment(loc, val, 4, rel);
393     checkInt(loc, val, 21, rel);
394     or32le(loc, (val & 0x1FFFFC) << 3);
395     break;
396   case R_AARCH64_LDST8_ABS_LO12_NC:
397   case R_AARCH64_TLSLE_LDST8_TPREL_LO12_NC:
398     or32AArch64Imm(loc, getBits(val, 0, 11));
399     break;
400   case R_AARCH64_LDST16_ABS_LO12_NC:
401   case R_AARCH64_TLSLE_LDST16_TPREL_LO12_NC:
402     checkAlignment(loc, val, 2, rel);
403     or32AArch64Imm(loc, getBits(val, 1, 11));
404     break;
405   case R_AARCH64_LDST32_ABS_LO12_NC:
406   case R_AARCH64_TLSLE_LDST32_TPREL_LO12_NC:
407     checkAlignment(loc, val, 4, rel);
408     or32AArch64Imm(loc, getBits(val, 2, 11));
409     break;
410   case R_AARCH64_LDST64_ABS_LO12_NC:
411   case R_AARCH64_LD64_GOT_LO12_NC:
412   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
413   case R_AARCH64_TLSLE_LDST64_TPREL_LO12_NC:
414   case R_AARCH64_TLSDESC_LD64_LO12:
415     checkAlignment(loc, val, 8, rel);
416     or32AArch64Imm(loc, getBits(val, 3, 11));
417     break;
418   case R_AARCH64_LDST128_ABS_LO12_NC:
419   case R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC:
420     checkAlignment(loc, val, 16, rel);
421     or32AArch64Imm(loc, getBits(val, 4, 11));
422     break;
423   case R_AARCH64_LD64_GOTPAGE_LO15:
424     checkAlignment(loc, val, 8, rel);
425     or32AArch64Imm(loc, getBits(val, 3, 14));
426     break;
427   case R_AARCH64_MOVW_UABS_G0:
428     checkUInt(loc, val, 16, rel);
429     LLVM_FALLTHROUGH;
430   case R_AARCH64_MOVW_UABS_G0_NC:
431     or32le(loc, (val & 0xFFFF) << 5);
432     break;
433   case R_AARCH64_MOVW_UABS_G1:
434     checkUInt(loc, val, 32, rel);
435     LLVM_FALLTHROUGH;
436   case R_AARCH64_MOVW_UABS_G1_NC:
437     or32le(loc, (val & 0xFFFF0000) >> 11);
438     break;
439   case R_AARCH64_MOVW_UABS_G2:
440     checkUInt(loc, val, 48, rel);
441     LLVM_FALLTHROUGH;
442   case R_AARCH64_MOVW_UABS_G2_NC:
443     or32le(loc, (val & 0xFFFF00000000) >> 27);
444     break;
445   case R_AARCH64_MOVW_UABS_G3:
446     or32le(loc, (val & 0xFFFF000000000000) >> 43);
447     break;
448   case R_AARCH64_MOVW_PREL_G0:
449   case R_AARCH64_MOVW_SABS_G0:
450   case R_AARCH64_TLSLE_MOVW_TPREL_G0:
451     checkInt(loc, val, 17, rel);
452     LLVM_FALLTHROUGH;
453   case R_AARCH64_MOVW_PREL_G0_NC:
454   case R_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
455     writeSMovWImm(loc, val);
456     break;
457   case R_AARCH64_MOVW_PREL_G1:
458   case R_AARCH64_MOVW_SABS_G1:
459   case R_AARCH64_TLSLE_MOVW_TPREL_G1:
460     checkInt(loc, val, 33, rel);
461     LLVM_FALLTHROUGH;
462   case R_AARCH64_MOVW_PREL_G1_NC:
463   case R_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
464     writeSMovWImm(loc, val >> 16);
465     break;
466   case R_AARCH64_MOVW_PREL_G2:
467   case R_AARCH64_MOVW_SABS_G2:
468   case R_AARCH64_TLSLE_MOVW_TPREL_G2:
469     checkInt(loc, val, 49, rel);
470     LLVM_FALLTHROUGH;
471   case R_AARCH64_MOVW_PREL_G2_NC:
472     writeSMovWImm(loc, val >> 32);
473     break;
474   case R_AARCH64_MOVW_PREL_G3:
475     writeSMovWImm(loc, val >> 48);
476     break;
477   case R_AARCH64_TSTBR14:
478     checkInt(loc, val, 16, rel);
479     or32le(loc, (val & 0xFFFC) << 3);
480     break;
481   case R_AARCH64_TLSLE_ADD_TPREL_HI12:
482     checkUInt(loc, val, 24, rel);
483     or32AArch64Imm(loc, val >> 12);
484     break;
485   case R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
486   case R_AARCH64_TLSDESC_ADD_LO12:
487     or32AArch64Imm(loc, val);
488     break;
489   case R_AARCH64_TLSDESC:
490     // For R_AARCH64_TLSDESC the addend is stored in the second 64-bit word.
491     write64(loc + 8, val);
492     break;
493   default:
494     llvm_unreachable("unknown relocation");
495   }
496 }
497 
498 void AArch64::relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
499                              uint64_t val) const {
500   // TLSDESC Global-Dynamic relocation are in the form:
501   //   adrp    x0, :tlsdesc:v             [R_AARCH64_TLSDESC_ADR_PAGE21]
502   //   ldr     x1, [x0, #:tlsdesc_lo12:v  [R_AARCH64_TLSDESC_LD64_LO12]
503   //   add     x0, x0, :tlsdesc_los:v     [R_AARCH64_TLSDESC_ADD_LO12]
504   //   .tlsdesccall                       [R_AARCH64_TLSDESC_CALL]
505   //   blr     x1
506   // And it can optimized to:
507   //   movz    x0, #0x0, lsl #16
508   //   movk    x0, #0x10
509   //   nop
510   //   nop
511   checkUInt(loc, val, 32, rel);
512 
513   switch (rel.type) {
514   case R_AARCH64_TLSDESC_ADD_LO12:
515   case R_AARCH64_TLSDESC_CALL:
516     write32le(loc, 0xd503201f); // nop
517     return;
518   case R_AARCH64_TLSDESC_ADR_PAGE21:
519     write32le(loc, 0xd2a00000 | (((val >> 16) & 0xffff) << 5)); // movz
520     return;
521   case R_AARCH64_TLSDESC_LD64_LO12:
522     write32le(loc, 0xf2800000 | ((val & 0xffff) << 5)); // movk
523     return;
524   default:
525     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
526   }
527 }
528 
529 void AArch64::relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
530                              uint64_t val) const {
531   // TLSDESC Global-Dynamic relocation are in the form:
532   //   adrp    x0, :tlsdesc:v             [R_AARCH64_TLSDESC_ADR_PAGE21]
533   //   ldr     x1, [x0, #:tlsdesc_lo12:v  [R_AARCH64_TLSDESC_LD64_LO12]
534   //   add     x0, x0, :tlsdesc_los:v     [R_AARCH64_TLSDESC_ADD_LO12]
535   //   .tlsdesccall                       [R_AARCH64_TLSDESC_CALL]
536   //   blr     x1
537   // And it can optimized to:
538   //   adrp    x0, :gottprel:v
539   //   ldr     x0, [x0, :gottprel_lo12:v]
540   //   nop
541   //   nop
542 
543   switch (rel.type) {
544   case R_AARCH64_TLSDESC_ADD_LO12:
545   case R_AARCH64_TLSDESC_CALL:
546     write32le(loc, 0xd503201f); // nop
547     break;
548   case R_AARCH64_TLSDESC_ADR_PAGE21:
549     write32le(loc, 0x90000000); // adrp
550     relocateNoSym(loc, R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21, val);
551     break;
552   case R_AARCH64_TLSDESC_LD64_LO12:
553     write32le(loc, 0xf9400000); // ldr
554     relocateNoSym(loc, R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC, val);
555     break;
556   default:
557     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
558   }
559 }
560 
561 void AArch64::relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
562                              uint64_t val) const {
563   checkUInt(loc, val, 32, rel);
564 
565   if (rel.type == R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21) {
566     // Generate MOVZ.
567     uint32_t regNo = read32le(loc) & 0x1f;
568     write32le(loc, (0xd2a00000 | regNo) | (((val >> 16) & 0xffff) << 5));
569     return;
570   }
571   if (rel.type == R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC) {
572     // Generate MOVK.
573     uint32_t regNo = read32le(loc) & 0x1f;
574     write32le(loc, (0xf2800000 | regNo) | ((val & 0xffff) << 5));
575     return;
576   }
577   llvm_unreachable("invalid relocation for TLS IE to LE relaxation");
578 }
579 
580 // AArch64 may use security features in variant PLT sequences. These are:
581 // Pointer Authentication (PAC), introduced in armv8.3-a and Branch Target
582 // Indicator (BTI) introduced in armv8.5-a. The additional instructions used
583 // in the variant Plt sequences are encoded in the Hint space so they can be
584 // deployed on older architectures, which treat the instructions as a nop.
585 // PAC and BTI can be combined leading to the following combinations:
586 // writePltHeader
587 // writePltHeaderBti (no PAC Header needed)
588 // writePlt
589 // writePltBti (BTI only)
590 // writePltPac (PAC only)
591 // writePltBtiPac (BTI and PAC)
592 //
593 // When PAC is enabled the dynamic loader encrypts the address that it places
594 // in the .got.plt using the pacia1716 instruction which encrypts the value in
595 // x17 using the modifier in x16. The static linker places autia1716 before the
596 // indirect branch to x17 to authenticate the address in x17 with the modifier
597 // in x16. This makes it more difficult for an attacker to modify the value in
598 // the .got.plt.
599 //
600 // When BTI is enabled all indirect branches must land on a bti instruction.
601 // The static linker must place a bti instruction at the start of any PLT entry
602 // that may be the target of an indirect branch. As the PLT entries call the
603 // lazy resolver indirectly this must have a bti instruction at start. In
604 // general a bti instruction is not needed for a PLT entry as indirect calls
605 // are resolved to the function address and not the PLT entry for the function.
606 // There are a small number of cases where the PLT address can escape, such as
607 // taking the address of a function or ifunc via a non got-generating
608 // relocation, and a shared library refers to that symbol.
609 //
610 // We use the bti c variant of the instruction which permits indirect branches
611 // (br) via x16/x17 and indirect function calls (blr) via any register. The ABI
612 // guarantees that all indirect branches from code requiring BTI protection
613 // will go via x16/x17
614 
615 namespace {
616 class AArch64BtiPac final : public AArch64 {
617 public:
618   AArch64BtiPac();
619   void writePltHeader(uint8_t *buf) const override;
620   void writePlt(uint8_t *buf, const Symbol &sym,
621                 uint64_t pltEntryAddr) const override;
622 
623 private:
624   bool btiHeader; // bti instruction needed in PLT Header
625   bool btiEntry;  // bti instruction needed in PLT Entry
626   bool pacEntry;  // autia1716 instruction needed in PLT Entry
627 };
628 } // namespace
629 
630 AArch64BtiPac::AArch64BtiPac() {
631   btiHeader = (config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI);
632   // A BTI (Branch Target Indicator) Plt Entry is only required if the
633   // address of the PLT entry can be taken by the program, which permits an
634   // indirect jump to the PLT entry. This can happen when the address
635   // of the PLT entry for a function is canonicalised due to the address of
636   // the function in an executable being taken by a shared library.
637   // FIXME: There is a potential optimization to omit the BTI if we detect
638   // that the address of the PLT entry isn't taken.
639   // The PAC PLT entries require dynamic loader support and this isn't known
640   // from properties in the objects, so we use the command line flag.
641   btiEntry = btiHeader && !config->shared;
642   pacEntry = config->zPacPlt;
643 
644   if (btiEntry || pacEntry) {
645     pltEntrySize = 24;
646     ipltEntrySize = 24;
647   }
648 }
649 
650 void AArch64BtiPac::writePltHeader(uint8_t *buf) const {
651   const uint8_t btiData[] = { 0x5f, 0x24, 0x03, 0xd5 }; // bti c
652   const uint8_t pltData[] = {
653       0xf0, 0x7b, 0xbf, 0xa9, // stp    x16, x30, [sp,#-16]!
654       0x10, 0x00, 0x00, 0x90, // adrp   x16, Page(&(.plt.got[2]))
655       0x11, 0x02, 0x40, 0xf9, // ldr    x17, [x16, Offset(&(.plt.got[2]))]
656       0x10, 0x02, 0x00, 0x91, // add    x16, x16, Offset(&(.plt.got[2]))
657       0x20, 0x02, 0x1f, 0xd6, // br     x17
658       0x1f, 0x20, 0x03, 0xd5, // nop
659       0x1f, 0x20, 0x03, 0xd5  // nop
660   };
661   const uint8_t nopData[] = { 0x1f, 0x20, 0x03, 0xd5 }; // nop
662 
663   uint64_t got = in.gotPlt->getVA();
664   uint64_t plt = in.plt->getVA();
665 
666   if (btiHeader) {
667     // PltHeader is called indirectly by plt[N]. Prefix pltData with a BTI C
668     // instruction.
669     memcpy(buf, btiData, sizeof(btiData));
670     buf += sizeof(btiData);
671     plt += sizeof(btiData);
672   }
673   memcpy(buf, pltData, sizeof(pltData));
674 
675   relocateNoSym(buf + 4, R_AARCH64_ADR_PREL_PG_HI21,
676                 getAArch64Page(got + 16) - getAArch64Page(plt + 8));
677   relocateNoSym(buf + 8, R_AARCH64_LDST64_ABS_LO12_NC, got + 16);
678   relocateNoSym(buf + 12, R_AARCH64_ADD_ABS_LO12_NC, got + 16);
679   if (!btiHeader)
680     // We didn't add the BTI c instruction so round out size with NOP.
681     memcpy(buf + sizeof(pltData), nopData, sizeof(nopData));
682 }
683 
684 void AArch64BtiPac::writePlt(uint8_t *buf, const Symbol &sym,
685                              uint64_t pltEntryAddr) const {
686   // The PLT entry is of the form:
687   // [btiData] addrInst (pacBr | stdBr) [nopData]
688   const uint8_t btiData[] = { 0x5f, 0x24, 0x03, 0xd5 }; // bti c
689   const uint8_t addrInst[] = {
690       0x10, 0x00, 0x00, 0x90,  // adrp x16, Page(&(.plt.got[n]))
691       0x11, 0x02, 0x40, 0xf9,  // ldr  x17, [x16, Offset(&(.plt.got[n]))]
692       0x10, 0x02, 0x00, 0x91   // add  x16, x16, Offset(&(.plt.got[n]))
693   };
694   const uint8_t pacBr[] = {
695       0x9f, 0x21, 0x03, 0xd5,  // autia1716
696       0x20, 0x02, 0x1f, 0xd6   // br   x17
697   };
698   const uint8_t stdBr[] = {
699       0x20, 0x02, 0x1f, 0xd6,  // br   x17
700       0x1f, 0x20, 0x03, 0xd5   // nop
701   };
702   const uint8_t nopData[] = { 0x1f, 0x20, 0x03, 0xd5 }; // nop
703 
704   if (btiEntry) {
705     memcpy(buf, btiData, sizeof(btiData));
706     buf += sizeof(btiData);
707     pltEntryAddr += sizeof(btiData);
708   }
709 
710   uint64_t gotPltEntryAddr = sym.getGotPltVA();
711   memcpy(buf, addrInst, sizeof(addrInst));
712   relocateNoSym(buf, R_AARCH64_ADR_PREL_PG_HI21,
713                 getAArch64Page(gotPltEntryAddr) - getAArch64Page(pltEntryAddr));
714   relocateNoSym(buf + 4, R_AARCH64_LDST64_ABS_LO12_NC, gotPltEntryAddr);
715   relocateNoSym(buf + 8, R_AARCH64_ADD_ABS_LO12_NC, gotPltEntryAddr);
716 
717   if (pacEntry)
718     memcpy(buf + sizeof(addrInst), pacBr, sizeof(pacBr));
719   else
720     memcpy(buf + sizeof(addrInst), stdBr, sizeof(stdBr));
721   if (!btiEntry)
722     // We didn't add the BTI c instruction so round out size with NOP.
723     memcpy(buf + sizeof(addrInst) + sizeof(stdBr), nopData, sizeof(nopData));
724 }
725 
726 static TargetInfo *getTargetInfo() {
727   if (config->andFeatures & (GNU_PROPERTY_AARCH64_FEATURE_1_BTI |
728                              GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
729     static AArch64BtiPac t;
730     return &t;
731   }
732   static AArch64 t;
733   return &t;
734 }
735 
736 TargetInfo *elf::getAArch64TargetInfo() { return getTargetInfo(); }
737