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