xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/AArch64.cpp (revision 7ef62cebc2f965b0f640263e179276928885e33d)
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 "OutputSections.h"
10 #include "Symbols.h"
11 #include "SyntheticSections.h"
12 #include "Target.h"
13 #include "lld/Common/ErrorHandler.h"
14 #include "llvm/BinaryFormat/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 writeIgotPlt(uint8_t *buf, const Symbol &s) const override;
40   void writePltHeader(uint8_t *buf) const override;
41   void writePlt(uint8_t *buf, const Symbol &sym,
42                 uint64_t pltEntryAddr) const override;
43   bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
44                   uint64_t branchAddr, const Symbol &s,
45                   int64_t a) const override;
46   uint32_t getThunkSectionSpacing() const override;
47   bool inBranchRange(RelType type, uint64_t src, uint64_t dst) const override;
48   bool usesOnlyLowPageBits(RelType type) const override;
49   void relocate(uint8_t *loc, const Relocation &rel,
50                 uint64_t val) const override;
51   RelExpr adjustTlsExpr(RelType type, RelExpr expr) const override;
52   void relocateAlloc(InputSectionBase &sec, uint8_t *buf) const override;
53 
54 private:
55   void relaxTlsGdToLe(uint8_t *loc, const Relocation &rel, uint64_t val) const;
56   void relaxTlsGdToIe(uint8_t *loc, const Relocation &rel, uint64_t val) const;
57   void relaxTlsIeToLe(uint8_t *loc, const Relocation &rel, uint64_t val) const;
58 };
59 
60 struct AArch64Relaxer {
61   bool safeToRelaxAdrpLdr = false;
62 
63   AArch64Relaxer(ArrayRef<Relocation> relocs);
64   bool tryRelaxAdrpAdd(const Relocation &adrpRel, const Relocation &addRel,
65                        uint64_t secAddr, uint8_t *buf) const;
66   bool tryRelaxAdrpLdr(const Relocation &adrpRel, const Relocation &ldrRel,
67                        uint64_t secAddr, uint8_t *buf) const;
68 };
69 } // namespace
70 
71 AArch64::AArch64() {
72   copyRel = R_AARCH64_COPY;
73   relativeRel = R_AARCH64_RELATIVE;
74   iRelativeRel = R_AARCH64_IRELATIVE;
75   gotRel = R_AARCH64_GLOB_DAT;
76   pltRel = R_AARCH64_JUMP_SLOT;
77   symbolicRel = R_AARCH64_ABS64;
78   tlsDescRel = R_AARCH64_TLSDESC;
79   tlsGotRel = R_AARCH64_TLS_TPREL64;
80   pltHeaderSize = 32;
81   pltEntrySize = 16;
82   ipltEntrySize = 16;
83   defaultMaxPageSize = 65536;
84 
85   // Align to the 2 MiB page size (known as a superpage or huge page).
86   // FreeBSD automatically promotes 2 MiB-aligned allocations.
87   defaultImageBase = 0x200000;
88 
89   needsThunks = true;
90 }
91 
92 RelExpr AArch64::getRelExpr(RelType type, const Symbol &s,
93                             const uint8_t *loc) const {
94   switch (type) {
95   case R_AARCH64_ABS16:
96   case R_AARCH64_ABS32:
97   case R_AARCH64_ABS64:
98   case R_AARCH64_ADD_ABS_LO12_NC:
99   case R_AARCH64_LDST128_ABS_LO12_NC:
100   case R_AARCH64_LDST16_ABS_LO12_NC:
101   case R_AARCH64_LDST32_ABS_LO12_NC:
102   case R_AARCH64_LDST64_ABS_LO12_NC:
103   case R_AARCH64_LDST8_ABS_LO12_NC:
104   case R_AARCH64_MOVW_SABS_G0:
105   case R_AARCH64_MOVW_SABS_G1:
106   case R_AARCH64_MOVW_SABS_G2:
107   case R_AARCH64_MOVW_UABS_G0:
108   case R_AARCH64_MOVW_UABS_G0_NC:
109   case R_AARCH64_MOVW_UABS_G1:
110   case R_AARCH64_MOVW_UABS_G1_NC:
111   case R_AARCH64_MOVW_UABS_G2:
112   case R_AARCH64_MOVW_UABS_G2_NC:
113   case R_AARCH64_MOVW_UABS_G3:
114     return R_ABS;
115   case R_AARCH64_TLSDESC_ADR_PAGE21:
116     return R_AARCH64_TLSDESC_PAGE;
117   case R_AARCH64_TLSDESC_LD64_LO12:
118   case R_AARCH64_TLSDESC_ADD_LO12:
119     return R_TLSDESC;
120   case R_AARCH64_TLSDESC_CALL:
121     return R_TLSDESC_CALL;
122   case R_AARCH64_TLSLE_ADD_TPREL_HI12:
123   case R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
124   case R_AARCH64_TLSLE_LDST8_TPREL_LO12_NC:
125   case R_AARCH64_TLSLE_LDST16_TPREL_LO12_NC:
126   case R_AARCH64_TLSLE_LDST32_TPREL_LO12_NC:
127   case R_AARCH64_TLSLE_LDST64_TPREL_LO12_NC:
128   case R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC:
129   case R_AARCH64_TLSLE_MOVW_TPREL_G0:
130   case R_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
131   case R_AARCH64_TLSLE_MOVW_TPREL_G1:
132   case R_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
133   case R_AARCH64_TLSLE_MOVW_TPREL_G2:
134     return R_TPREL;
135   case R_AARCH64_CALL26:
136   case R_AARCH64_CONDBR19:
137   case R_AARCH64_JUMP26:
138   case R_AARCH64_TSTBR14:
139   case R_AARCH64_PLT32:
140     return R_PLT_PC;
141   case R_AARCH64_PREL16:
142   case R_AARCH64_PREL32:
143   case R_AARCH64_PREL64:
144   case R_AARCH64_ADR_PREL_LO21:
145   case R_AARCH64_LD_PREL_LO19:
146   case R_AARCH64_MOVW_PREL_G0:
147   case R_AARCH64_MOVW_PREL_G0_NC:
148   case R_AARCH64_MOVW_PREL_G1:
149   case R_AARCH64_MOVW_PREL_G1_NC:
150   case R_AARCH64_MOVW_PREL_G2:
151   case R_AARCH64_MOVW_PREL_G2_NC:
152   case R_AARCH64_MOVW_PREL_G3:
153     return R_PC;
154   case R_AARCH64_ADR_PREL_PG_HI21:
155   case R_AARCH64_ADR_PREL_PG_HI21_NC:
156     return R_AARCH64_PAGE_PC;
157   case R_AARCH64_LD64_GOT_LO12_NC:
158   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
159     return R_GOT;
160   case R_AARCH64_LD64_GOTPAGE_LO15:
161     return R_AARCH64_GOT_PAGE;
162   case R_AARCH64_ADR_GOT_PAGE:
163   case R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
164     return R_AARCH64_GOT_PAGE_PC;
165   case R_AARCH64_NONE:
166     return R_NONE;
167   default:
168     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
169           ") against symbol " + toString(s));
170     return R_NONE;
171   }
172 }
173 
174 RelExpr AArch64::adjustTlsExpr(RelType type, RelExpr expr) const {
175   if (expr == R_RELAX_TLS_GD_TO_IE) {
176     if (type == R_AARCH64_TLSDESC_ADR_PAGE21)
177       return R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC;
178     return R_RELAX_TLS_GD_TO_IE_ABS;
179   }
180   return expr;
181 }
182 
183 bool AArch64::usesOnlyLowPageBits(RelType type) const {
184   switch (type) {
185   default:
186     return false;
187   case R_AARCH64_ADD_ABS_LO12_NC:
188   case R_AARCH64_LD64_GOT_LO12_NC:
189   case R_AARCH64_LDST128_ABS_LO12_NC:
190   case R_AARCH64_LDST16_ABS_LO12_NC:
191   case R_AARCH64_LDST32_ABS_LO12_NC:
192   case R_AARCH64_LDST64_ABS_LO12_NC:
193   case R_AARCH64_LDST8_ABS_LO12_NC:
194   case R_AARCH64_TLSDESC_ADD_LO12:
195   case R_AARCH64_TLSDESC_LD64_LO12:
196   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
197     return true;
198   }
199 }
200 
201 RelType AArch64::getDynRel(RelType type) const {
202   if (type == R_AARCH64_ABS64)
203     return type;
204   return R_AARCH64_NONE;
205 }
206 
207 int64_t AArch64::getImplicitAddend(const uint8_t *buf, RelType type) const {
208   switch (type) {
209   case R_AARCH64_TLSDESC:
210     return read64(buf + 8);
211   case R_AARCH64_NONE:
212   case R_AARCH64_GLOB_DAT:
213   case R_AARCH64_JUMP_SLOT:
214     return 0;
215   case R_AARCH64_PREL32:
216     return SignExtend64<32>(read32(buf));
217   case R_AARCH64_ABS64:
218   case R_AARCH64_PREL64:
219   case R_AARCH64_RELATIVE:
220   case R_AARCH64_IRELATIVE:
221   case R_AARCH64_TLS_TPREL64:
222     return read64(buf);
223   default:
224     internalLinkerError(getErrorLocation(buf),
225                         "cannot read addend for relocation " + toString(type));
226     return 0;
227   }
228 }
229 
230 void AArch64::writeGotPlt(uint8_t *buf, const Symbol &) const {
231   write64(buf, in.plt->getVA());
232 }
233 
234 void AArch64::writeIgotPlt(uint8_t *buf, const Symbol &s) const {
235   if (config->writeAddends)
236     write64(buf, s.getVA());
237 }
238 
239 void AArch64::writePltHeader(uint8_t *buf) const {
240   const uint8_t pltData[] = {
241       0xf0, 0x7b, 0xbf, 0xa9, // stp    x16, x30, [sp,#-16]!
242       0x10, 0x00, 0x00, 0x90, // adrp   x16, Page(&(.got.plt[2]))
243       0x11, 0x02, 0x40, 0xf9, // ldr    x17, [x16, Offset(&(.got.plt[2]))]
244       0x10, 0x02, 0x00, 0x91, // add    x16, x16, Offset(&(.got.plt[2]))
245       0x20, 0x02, 0x1f, 0xd6, // br     x17
246       0x1f, 0x20, 0x03, 0xd5, // nop
247       0x1f, 0x20, 0x03, 0xd5, // nop
248       0x1f, 0x20, 0x03, 0xd5  // nop
249   };
250   memcpy(buf, pltData, sizeof(pltData));
251 
252   uint64_t got = in.gotPlt->getVA();
253   uint64_t plt = in.plt->getVA();
254   relocateNoSym(buf + 4, R_AARCH64_ADR_PREL_PG_HI21,
255                 getAArch64Page(got + 16) - getAArch64Page(plt + 4));
256   relocateNoSym(buf + 8, R_AARCH64_LDST64_ABS_LO12_NC, got + 16);
257   relocateNoSym(buf + 12, R_AARCH64_ADD_ABS_LO12_NC, got + 16);
258 }
259 
260 void AArch64::writePlt(uint8_t *buf, const Symbol &sym,
261                        uint64_t pltEntryAddr) const {
262   const uint8_t inst[] = {
263       0x10, 0x00, 0x00, 0x90, // adrp x16, Page(&(.got.plt[n]))
264       0x11, 0x02, 0x40, 0xf9, // ldr  x17, [x16, Offset(&(.got.plt[n]))]
265       0x10, 0x02, 0x00, 0x91, // add  x16, x16, Offset(&(.got.plt[n]))
266       0x20, 0x02, 0x1f, 0xd6  // br   x17
267   };
268   memcpy(buf, inst, sizeof(inst));
269 
270   uint64_t gotPltEntryAddr = sym.getGotPltVA();
271   relocateNoSym(buf, R_AARCH64_ADR_PREL_PG_HI21,
272                 getAArch64Page(gotPltEntryAddr) - getAArch64Page(pltEntryAddr));
273   relocateNoSym(buf + 4, R_AARCH64_LDST64_ABS_LO12_NC, gotPltEntryAddr);
274   relocateNoSym(buf + 8, R_AARCH64_ADD_ABS_LO12_NC, gotPltEntryAddr);
275 }
276 
277 bool AArch64::needsThunk(RelExpr expr, RelType type, const InputFile *file,
278                          uint64_t branchAddr, const Symbol &s,
279                          int64_t a) const {
280   // If s is an undefined weak symbol and does not have a PLT entry then it will
281   // be resolved as a branch to the next instruction. If it is hidden, its
282   // binding has been converted to local, so we just check isUndefined() here. A
283   // undefined non-weak symbol will have been errored.
284   if (s.isUndefined() && !s.isInPlt())
285     return false;
286   // ELF for the ARM 64-bit architecture, section Call and Jump relocations
287   // only permits range extension thunks for R_AARCH64_CALL26 and
288   // R_AARCH64_JUMP26 relocation types.
289   if (type != R_AARCH64_CALL26 && type != R_AARCH64_JUMP26 &&
290       type != R_AARCH64_PLT32)
291     return false;
292   uint64_t dst = expr == R_PLT_PC ? s.getPltVA() : s.getVA(a);
293   return !inBranchRange(type, branchAddr, dst);
294 }
295 
296 uint32_t AArch64::getThunkSectionSpacing() const {
297   // See comment in Arch/ARM.cpp for a more detailed explanation of
298   // getThunkSectionSpacing(). For AArch64 the only branches we are permitted to
299   // Thunk have a range of +/- 128 MiB
300   return (128 * 1024 * 1024) - 0x30000;
301 }
302 
303 bool AArch64::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
304   if (type != R_AARCH64_CALL26 && type != R_AARCH64_JUMP26 &&
305       type != R_AARCH64_PLT32)
306     return true;
307   // The AArch64 call and unconditional branch instructions have a range of
308   // +/- 128 MiB. The PLT32 relocation supports a range up to +/- 2 GiB.
309   uint64_t range =
310       type == R_AARCH64_PLT32 ? (UINT64_C(1) << 31) : (128 * 1024 * 1024);
311   if (dst > src) {
312     // Immediate of branch is signed.
313     range -= 4;
314     return dst - src <= range;
315   }
316   return src - dst <= range;
317 }
318 
319 static void write32AArch64Addr(uint8_t *l, uint64_t imm) {
320   uint32_t immLo = (imm & 0x3) << 29;
321   uint32_t immHi = (imm & 0x1FFFFC) << 3;
322   uint64_t mask = (0x3 << 29) | (0x1FFFFC << 3);
323   write32le(l, (read32le(l) & ~mask) | immLo | immHi);
324 }
325 
326 // Return the bits [Start, End] from Val shifted Start bits.
327 // For instance, getBits(0xF0, 4, 8) returns 0xF.
328 static uint64_t getBits(uint64_t val, int start, int end) {
329   uint64_t mask = ((uint64_t)1 << (end + 1 - start)) - 1;
330   return (val >> start) & mask;
331 }
332 
333 static void or32le(uint8_t *p, int32_t v) { write32le(p, read32le(p) | v); }
334 
335 // Update the immediate field in a AARCH64 ldr, str, and add instruction.
336 static void or32AArch64Imm(uint8_t *l, uint64_t imm) {
337   or32le(l, (imm & 0xFFF) << 10);
338 }
339 
340 // Update the immediate field in an AArch64 movk, movn or movz instruction
341 // for a signed relocation, and update the opcode of a movn or movz instruction
342 // to match the sign of the operand.
343 static void writeSMovWImm(uint8_t *loc, uint32_t imm) {
344   uint32_t inst = read32le(loc);
345   // Opcode field is bits 30, 29, with 10 = movz, 00 = movn and 11 = movk.
346   if (!(inst & (1 << 29))) {
347     // movn or movz.
348     if (imm & 0x10000) {
349       // Change opcode to movn, which takes an inverted operand.
350       imm ^= 0xFFFF;
351       inst &= ~(1 << 30);
352     } else {
353       // Change opcode to movz.
354       inst |= 1 << 30;
355     }
356   }
357   write32le(loc, inst | ((imm & 0xFFFF) << 5));
358 }
359 
360 void AArch64::relocate(uint8_t *loc, const Relocation &rel,
361                        uint64_t val) const {
362   switch (rel.type) {
363   case R_AARCH64_ABS16:
364   case R_AARCH64_PREL16:
365     checkIntUInt(loc, val, 16, rel);
366     write16(loc, val);
367     break;
368   case R_AARCH64_ABS32:
369   case R_AARCH64_PREL32:
370     checkIntUInt(loc, val, 32, rel);
371     write32(loc, val);
372     break;
373   case R_AARCH64_PLT32:
374     checkInt(loc, val, 32, rel);
375     write32(loc, val);
376     break;
377   case R_AARCH64_ABS64:
378   case R_AARCH64_PREL64:
379     write64(loc, val);
380     break;
381   case R_AARCH64_ADD_ABS_LO12_NC:
382     or32AArch64Imm(loc, val);
383     break;
384   case R_AARCH64_ADR_GOT_PAGE:
385   case R_AARCH64_ADR_PREL_PG_HI21:
386   case R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
387   case R_AARCH64_TLSDESC_ADR_PAGE21:
388     checkInt(loc, val, 33, rel);
389     [[fallthrough]];
390   case R_AARCH64_ADR_PREL_PG_HI21_NC:
391     write32AArch64Addr(loc, val >> 12);
392     break;
393   case R_AARCH64_ADR_PREL_LO21:
394     checkInt(loc, val, 21, rel);
395     write32AArch64Addr(loc, val);
396     break;
397   case R_AARCH64_JUMP26:
398     // Normally we would just write the bits of the immediate field, however
399     // when patching instructions for the cpu errata fix -fix-cortex-a53-843419
400     // we want to replace a non-branch instruction with a branch immediate
401     // instruction. By writing all the bits of the instruction including the
402     // opcode and the immediate (0 001 | 01 imm26) we can do this
403     // transformation by placing a R_AARCH64_JUMP26 relocation at the offset of
404     // the instruction we want to patch.
405     write32le(loc, 0x14000000);
406     [[fallthrough]];
407   case R_AARCH64_CALL26:
408     checkInt(loc, val, 28, rel);
409     or32le(loc, (val & 0x0FFFFFFC) >> 2);
410     break;
411   case R_AARCH64_CONDBR19:
412   case R_AARCH64_LD_PREL_LO19:
413     checkAlignment(loc, val, 4, rel);
414     checkInt(loc, val, 21, rel);
415     or32le(loc, (val & 0x1FFFFC) << 3);
416     break;
417   case R_AARCH64_LDST8_ABS_LO12_NC:
418   case R_AARCH64_TLSLE_LDST8_TPREL_LO12_NC:
419     or32AArch64Imm(loc, getBits(val, 0, 11));
420     break;
421   case R_AARCH64_LDST16_ABS_LO12_NC:
422   case R_AARCH64_TLSLE_LDST16_TPREL_LO12_NC:
423     checkAlignment(loc, val, 2, rel);
424     or32AArch64Imm(loc, getBits(val, 1, 11));
425     break;
426   case R_AARCH64_LDST32_ABS_LO12_NC:
427   case R_AARCH64_TLSLE_LDST32_TPREL_LO12_NC:
428     checkAlignment(loc, val, 4, rel);
429     or32AArch64Imm(loc, getBits(val, 2, 11));
430     break;
431   case R_AARCH64_LDST64_ABS_LO12_NC:
432   case R_AARCH64_LD64_GOT_LO12_NC:
433   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
434   case R_AARCH64_TLSLE_LDST64_TPREL_LO12_NC:
435   case R_AARCH64_TLSDESC_LD64_LO12:
436     checkAlignment(loc, val, 8, rel);
437     or32AArch64Imm(loc, getBits(val, 3, 11));
438     break;
439   case R_AARCH64_LDST128_ABS_LO12_NC:
440   case R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC:
441     checkAlignment(loc, val, 16, rel);
442     or32AArch64Imm(loc, getBits(val, 4, 11));
443     break;
444   case R_AARCH64_LD64_GOTPAGE_LO15:
445     checkAlignment(loc, val, 8, rel);
446     or32AArch64Imm(loc, getBits(val, 3, 14));
447     break;
448   case R_AARCH64_MOVW_UABS_G0:
449     checkUInt(loc, val, 16, rel);
450     [[fallthrough]];
451   case R_AARCH64_MOVW_UABS_G0_NC:
452     or32le(loc, (val & 0xFFFF) << 5);
453     break;
454   case R_AARCH64_MOVW_UABS_G1:
455     checkUInt(loc, val, 32, rel);
456     [[fallthrough]];
457   case R_AARCH64_MOVW_UABS_G1_NC:
458     or32le(loc, (val & 0xFFFF0000) >> 11);
459     break;
460   case R_AARCH64_MOVW_UABS_G2:
461     checkUInt(loc, val, 48, rel);
462     [[fallthrough]];
463   case R_AARCH64_MOVW_UABS_G2_NC:
464     or32le(loc, (val & 0xFFFF00000000) >> 27);
465     break;
466   case R_AARCH64_MOVW_UABS_G3:
467     or32le(loc, (val & 0xFFFF000000000000) >> 43);
468     break;
469   case R_AARCH64_MOVW_PREL_G0:
470   case R_AARCH64_MOVW_SABS_G0:
471   case R_AARCH64_TLSLE_MOVW_TPREL_G0:
472     checkInt(loc, val, 17, rel);
473     [[fallthrough]];
474   case R_AARCH64_MOVW_PREL_G0_NC:
475   case R_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
476     writeSMovWImm(loc, val);
477     break;
478   case R_AARCH64_MOVW_PREL_G1:
479   case R_AARCH64_MOVW_SABS_G1:
480   case R_AARCH64_TLSLE_MOVW_TPREL_G1:
481     checkInt(loc, val, 33, rel);
482     [[fallthrough]];
483   case R_AARCH64_MOVW_PREL_G1_NC:
484   case R_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
485     writeSMovWImm(loc, val >> 16);
486     break;
487   case R_AARCH64_MOVW_PREL_G2:
488   case R_AARCH64_MOVW_SABS_G2:
489   case R_AARCH64_TLSLE_MOVW_TPREL_G2:
490     checkInt(loc, val, 49, rel);
491     [[fallthrough]];
492   case R_AARCH64_MOVW_PREL_G2_NC:
493     writeSMovWImm(loc, val >> 32);
494     break;
495   case R_AARCH64_MOVW_PREL_G3:
496     writeSMovWImm(loc, val >> 48);
497     break;
498   case R_AARCH64_TSTBR14:
499     checkInt(loc, val, 16, rel);
500     or32le(loc, (val & 0xFFFC) << 3);
501     break;
502   case R_AARCH64_TLSLE_ADD_TPREL_HI12:
503     checkUInt(loc, val, 24, rel);
504     or32AArch64Imm(loc, val >> 12);
505     break;
506   case R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
507   case R_AARCH64_TLSDESC_ADD_LO12:
508     or32AArch64Imm(loc, val);
509     break;
510   case R_AARCH64_TLSDESC:
511     // For R_AARCH64_TLSDESC the addend is stored in the second 64-bit word.
512     write64(loc + 8, val);
513     break;
514   default:
515     llvm_unreachable("unknown relocation");
516   }
517 }
518 
519 void AArch64::relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
520                              uint64_t val) const {
521   // TLSDESC Global-Dynamic relocation are in the form:
522   //   adrp    x0, :tlsdesc:v             [R_AARCH64_TLSDESC_ADR_PAGE21]
523   //   ldr     x1, [x0, #:tlsdesc_lo12:v  [R_AARCH64_TLSDESC_LD64_LO12]
524   //   add     x0, x0, :tlsdesc_los:v     [R_AARCH64_TLSDESC_ADD_LO12]
525   //   .tlsdesccall                       [R_AARCH64_TLSDESC_CALL]
526   //   blr     x1
527   // And it can optimized to:
528   //   movz    x0, #0x0, lsl #16
529   //   movk    x0, #0x10
530   //   nop
531   //   nop
532   checkUInt(loc, val, 32, rel);
533 
534   switch (rel.type) {
535   case R_AARCH64_TLSDESC_ADD_LO12:
536   case R_AARCH64_TLSDESC_CALL:
537     write32le(loc, 0xd503201f); // nop
538     return;
539   case R_AARCH64_TLSDESC_ADR_PAGE21:
540     write32le(loc, 0xd2a00000 | (((val >> 16) & 0xffff) << 5)); // movz
541     return;
542   case R_AARCH64_TLSDESC_LD64_LO12:
543     write32le(loc, 0xf2800000 | ((val & 0xffff) << 5)); // movk
544     return;
545   default:
546     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
547   }
548 }
549 
550 void AArch64::relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
551                              uint64_t val) const {
552   // TLSDESC Global-Dynamic relocation are in the form:
553   //   adrp    x0, :tlsdesc:v             [R_AARCH64_TLSDESC_ADR_PAGE21]
554   //   ldr     x1, [x0, #:tlsdesc_lo12:v  [R_AARCH64_TLSDESC_LD64_LO12]
555   //   add     x0, x0, :tlsdesc_los:v     [R_AARCH64_TLSDESC_ADD_LO12]
556   //   .tlsdesccall                       [R_AARCH64_TLSDESC_CALL]
557   //   blr     x1
558   // And it can optimized to:
559   //   adrp    x0, :gottprel:v
560   //   ldr     x0, [x0, :gottprel_lo12:v]
561   //   nop
562   //   nop
563 
564   switch (rel.type) {
565   case R_AARCH64_TLSDESC_ADD_LO12:
566   case R_AARCH64_TLSDESC_CALL:
567     write32le(loc, 0xd503201f); // nop
568     break;
569   case R_AARCH64_TLSDESC_ADR_PAGE21:
570     write32le(loc, 0x90000000); // adrp
571     relocateNoSym(loc, R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21, val);
572     break;
573   case R_AARCH64_TLSDESC_LD64_LO12:
574     write32le(loc, 0xf9400000); // ldr
575     relocateNoSym(loc, R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC, val);
576     break;
577   default:
578     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
579   }
580 }
581 
582 void AArch64::relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
583                              uint64_t val) const {
584   checkUInt(loc, val, 32, rel);
585 
586   if (rel.type == R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21) {
587     // Generate MOVZ.
588     uint32_t regNo = read32le(loc) & 0x1f;
589     write32le(loc, (0xd2a00000 | regNo) | (((val >> 16) & 0xffff) << 5));
590     return;
591   }
592   if (rel.type == R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC) {
593     // Generate MOVK.
594     uint32_t regNo = read32le(loc) & 0x1f;
595     write32le(loc, (0xf2800000 | regNo) | ((val & 0xffff) << 5));
596     return;
597   }
598   llvm_unreachable("invalid relocation for TLS IE to LE relaxation");
599 }
600 
601 AArch64Relaxer::AArch64Relaxer(ArrayRef<Relocation> relocs) {
602   if (!config->relax)
603     return;
604   // Check if R_AARCH64_ADR_GOT_PAGE and R_AARCH64_LD64_GOT_LO12_NC
605   // always appear in pairs.
606   size_t i = 0;
607   const size_t size = relocs.size();
608   for (; i != size; ++i) {
609     if (relocs[i].type == R_AARCH64_ADR_GOT_PAGE) {
610       if (i + 1 < size && relocs[i + 1].type == R_AARCH64_LD64_GOT_LO12_NC) {
611         ++i;
612         continue;
613       }
614       break;
615     } else if (relocs[i].type == R_AARCH64_LD64_GOT_LO12_NC) {
616       break;
617     }
618   }
619   safeToRelaxAdrpLdr = i == size;
620 }
621 
622 bool AArch64Relaxer::tryRelaxAdrpAdd(const Relocation &adrpRel,
623                                      const Relocation &addRel, uint64_t secAddr,
624                                      uint8_t *buf) const {
625   // When the address of sym is within the range of ADR then
626   // we may relax
627   // ADRP xn, sym
628   // ADD  xn, xn, :lo12: sym
629   // to
630   // NOP
631   // ADR xn, sym
632   if (!config->relax || adrpRel.type != R_AARCH64_ADR_PREL_PG_HI21 ||
633       addRel.type != R_AARCH64_ADD_ABS_LO12_NC)
634     return false;
635   // Check if the relocations apply to consecutive instructions.
636   if (adrpRel.offset + 4 != addRel.offset)
637     return false;
638   if (adrpRel.sym != addRel.sym)
639     return false;
640   if (adrpRel.addend != 0 || addRel.addend != 0)
641     return false;
642 
643   uint32_t adrpInstr = read32le(buf + adrpRel.offset);
644   uint32_t addInstr = read32le(buf + addRel.offset);
645   // Check if the first instruction is ADRP and the second instruction is ADD.
646   if ((adrpInstr & 0x9f000000) != 0x90000000 ||
647       (addInstr & 0xffc00000) != 0x91000000)
648     return false;
649   uint32_t adrpDestReg = adrpInstr & 0x1f;
650   uint32_t addDestReg = addInstr & 0x1f;
651   uint32_t addSrcReg = (addInstr >> 5) & 0x1f;
652   if (adrpDestReg != addDestReg || adrpDestReg != addSrcReg)
653     return false;
654 
655   Symbol &sym = *adrpRel.sym;
656   // Check if the address difference is within 1MiB range.
657   int64_t val = sym.getVA() - (secAddr + addRel.offset);
658   if (val < -1024 * 1024 || val >= 1024 * 1024)
659     return false;
660 
661   Relocation adrRel = {R_ABS, R_AARCH64_ADR_PREL_LO21, addRel.offset,
662                        /*addend=*/0, &sym};
663   // nop
664   write32le(buf + adrpRel.offset, 0xd503201f);
665   // adr x_<dest_reg>
666   write32le(buf + adrRel.offset, 0x10000000 | adrpDestReg);
667   target->relocate(buf + adrRel.offset, adrRel, val);
668   return true;
669 }
670 
671 bool AArch64Relaxer::tryRelaxAdrpLdr(const Relocation &adrpRel,
672                                      const Relocation &ldrRel, uint64_t secAddr,
673                                      uint8_t *buf) const {
674   if (!safeToRelaxAdrpLdr)
675     return false;
676 
677   // When the definition of sym is not preemptible then we may
678   // be able to relax
679   // ADRP xn, :got: sym
680   // LDR xn, [ xn :got_lo12: sym]
681   // to
682   // ADRP xn, sym
683   // ADD xn, xn, :lo_12: sym
684 
685   if (adrpRel.type != R_AARCH64_ADR_GOT_PAGE ||
686       ldrRel.type != R_AARCH64_LD64_GOT_LO12_NC)
687     return false;
688   // Check if the relocations apply to consecutive instructions.
689   if (adrpRel.offset + 4 != ldrRel.offset)
690     return false;
691   // Check if the relocations reference the same symbol and
692   // skip undefined, preemptible and STT_GNU_IFUNC symbols.
693   if (!adrpRel.sym || adrpRel.sym != ldrRel.sym || !adrpRel.sym->isDefined() ||
694       adrpRel.sym->isPreemptible || adrpRel.sym->isGnuIFunc())
695     return false;
696   // Check if the addends of the both relocations are zero.
697   if (adrpRel.addend != 0 || ldrRel.addend != 0)
698     return false;
699   uint32_t adrpInstr = read32le(buf + adrpRel.offset);
700   uint32_t ldrInstr = read32le(buf + ldrRel.offset);
701   // Check if the first instruction is ADRP and the second instruction is LDR.
702   if ((adrpInstr & 0x9f000000) != 0x90000000 ||
703       (ldrInstr & 0x3b000000) != 0x39000000)
704     return false;
705   // Check the value of the sf bit.
706   if (!(ldrInstr >> 31))
707     return false;
708   uint32_t adrpDestReg = adrpInstr & 0x1f;
709   uint32_t ldrDestReg = ldrInstr & 0x1f;
710   uint32_t ldrSrcReg = (ldrInstr >> 5) & 0x1f;
711   // Check if ADPR and LDR use the same register.
712   if (adrpDestReg != ldrDestReg || adrpDestReg != ldrSrcReg)
713     return false;
714 
715   Symbol &sym = *adrpRel.sym;
716   // GOT references to absolute symbols can't be relaxed to use ADRP/ADD in
717   // position-independent code because these instructions produce a relative
718   // address.
719   if (config->isPic && !cast<Defined>(sym).section)
720     return false;
721   // Check if the address difference is within 4GB range.
722   int64_t val =
723       getAArch64Page(sym.getVA()) - getAArch64Page(secAddr + adrpRel.offset);
724   if (val != llvm::SignExtend64(val, 33))
725     return false;
726 
727   Relocation adrpSymRel = {R_AARCH64_PAGE_PC, R_AARCH64_ADR_PREL_PG_HI21,
728                            adrpRel.offset, /*addend=*/0, &sym};
729   Relocation addRel = {R_ABS, R_AARCH64_ADD_ABS_LO12_NC, ldrRel.offset,
730                        /*addend=*/0, &sym};
731 
732   // adrp x_<dest_reg>
733   write32le(buf + adrpSymRel.offset, 0x90000000 | adrpDestReg);
734   // add x_<dest reg>, x_<dest reg>
735   write32le(buf + addRel.offset, 0x91000000 | adrpDestReg | (adrpDestReg << 5));
736 
737   target->relocate(buf + adrpSymRel.offset, adrpSymRel,
738                    SignExtend64(getAArch64Page(sym.getVA()) -
739                                     getAArch64Page(secAddr + adrpSymRel.offset),
740                                 64));
741   target->relocate(buf + addRel.offset, addRel, SignExtend64(sym.getVA(), 64));
742   tryRelaxAdrpAdd(adrpSymRel, addRel, secAddr, buf);
743   return true;
744 }
745 
746 void AArch64::relocateAlloc(InputSectionBase &sec, uint8_t *buf) const {
747   uint64_t secAddr = sec.getOutputSection()->addr;
748   if (auto *s = dyn_cast<InputSection>(&sec))
749     secAddr += s->outSecOff;
750   AArch64Relaxer relaxer(sec.relocs());
751   for (size_t i = 0, size = sec.relocs().size(); i != size; ++i) {
752     const Relocation &rel = sec.relocs()[i];
753     uint8_t *loc = buf + rel.offset;
754     const uint64_t val =
755         sec.getRelocTargetVA(sec.file, rel.type, rel.addend,
756                              secAddr + rel.offset, *rel.sym, rel.expr);
757     switch (rel.expr) {
758     case R_AARCH64_GOT_PAGE_PC:
759       if (i + 1 < size &&
760           relaxer.tryRelaxAdrpLdr(rel, sec.relocs()[i + 1], secAddr, buf)) {
761         ++i;
762         continue;
763       }
764       break;
765     case R_AARCH64_PAGE_PC:
766       if (i + 1 < size &&
767           relaxer.tryRelaxAdrpAdd(rel, sec.relocs()[i + 1], secAddr, buf)) {
768         ++i;
769         continue;
770       }
771       break;
772     case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
773     case R_RELAX_TLS_GD_TO_IE_ABS:
774       relaxTlsGdToIe(loc, rel, val);
775       continue;
776     case R_RELAX_TLS_GD_TO_LE:
777       relaxTlsGdToLe(loc, rel, val);
778       continue;
779     case R_RELAX_TLS_IE_TO_LE:
780       relaxTlsIeToLe(loc, rel, val);
781       continue;
782     default:
783       break;
784     }
785     relocate(loc, rel, val);
786   }
787 }
788 
789 // AArch64 may use security features in variant PLT sequences. These are:
790 // Pointer Authentication (PAC), introduced in armv8.3-a and Branch Target
791 // Indicator (BTI) introduced in armv8.5-a. The additional instructions used
792 // in the variant Plt sequences are encoded in the Hint space so they can be
793 // deployed on older architectures, which treat the instructions as a nop.
794 // PAC and BTI can be combined leading to the following combinations:
795 // writePltHeader
796 // writePltHeaderBti (no PAC Header needed)
797 // writePlt
798 // writePltBti (BTI only)
799 // writePltPac (PAC only)
800 // writePltBtiPac (BTI and PAC)
801 //
802 // When PAC is enabled the dynamic loader encrypts the address that it places
803 // in the .got.plt using the pacia1716 instruction which encrypts the value in
804 // x17 using the modifier in x16. The static linker places autia1716 before the
805 // indirect branch to x17 to authenticate the address in x17 with the modifier
806 // in x16. This makes it more difficult for an attacker to modify the value in
807 // the .got.plt.
808 //
809 // When BTI is enabled all indirect branches must land on a bti instruction.
810 // The static linker must place a bti instruction at the start of any PLT entry
811 // that may be the target of an indirect branch. As the PLT entries call the
812 // lazy resolver indirectly this must have a bti instruction at start. In
813 // general a bti instruction is not needed for a PLT entry as indirect calls
814 // are resolved to the function address and not the PLT entry for the function.
815 // There are a small number of cases where the PLT address can escape, such as
816 // taking the address of a function or ifunc via a non got-generating
817 // relocation, and a shared library refers to that symbol.
818 //
819 // We use the bti c variant of the instruction which permits indirect branches
820 // (br) via x16/x17 and indirect function calls (blr) via any register. The ABI
821 // guarantees that all indirect branches from code requiring BTI protection
822 // will go via x16/x17
823 
824 namespace {
825 class AArch64BtiPac final : public AArch64 {
826 public:
827   AArch64BtiPac();
828   void writePltHeader(uint8_t *buf) const override;
829   void writePlt(uint8_t *buf, const Symbol &sym,
830                 uint64_t pltEntryAddr) const override;
831 
832 private:
833   bool btiHeader; // bti instruction needed in PLT Header and Entry
834   bool pacEntry;  // autia1716 instruction needed in PLT Entry
835 };
836 } // namespace
837 
838 AArch64BtiPac::AArch64BtiPac() {
839   btiHeader = (config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI);
840   // A BTI (Branch Target Indicator) Plt Entry is only required if the
841   // address of the PLT entry can be taken by the program, which permits an
842   // indirect jump to the PLT entry. This can happen when the address
843   // of the PLT entry for a function is canonicalised due to the address of
844   // the function in an executable being taken by a shared library, or
845   // non-preemptible ifunc referenced by non-GOT-generating, non-PLT-generating
846   // relocations.
847   // The PAC PLT entries require dynamic loader support and this isn't known
848   // from properties in the objects, so we use the command line flag.
849   pacEntry = config->zPacPlt;
850 
851   if (btiHeader || pacEntry) {
852     pltEntrySize = 24;
853     ipltEntrySize = 24;
854   }
855 }
856 
857 void AArch64BtiPac::writePltHeader(uint8_t *buf) const {
858   const uint8_t btiData[] = { 0x5f, 0x24, 0x03, 0xd5 }; // bti c
859   const uint8_t pltData[] = {
860       0xf0, 0x7b, 0xbf, 0xa9, // stp    x16, x30, [sp,#-16]!
861       0x10, 0x00, 0x00, 0x90, // adrp   x16, Page(&(.got.plt[2]))
862       0x11, 0x02, 0x40, 0xf9, // ldr    x17, [x16, Offset(&(.got.plt[2]))]
863       0x10, 0x02, 0x00, 0x91, // add    x16, x16, Offset(&(.got.plt[2]))
864       0x20, 0x02, 0x1f, 0xd6, // br     x17
865       0x1f, 0x20, 0x03, 0xd5, // nop
866       0x1f, 0x20, 0x03, 0xd5  // nop
867   };
868   const uint8_t nopData[] = { 0x1f, 0x20, 0x03, 0xd5 }; // nop
869 
870   uint64_t got = in.gotPlt->getVA();
871   uint64_t plt = in.plt->getVA();
872 
873   if (btiHeader) {
874     // PltHeader is called indirectly by plt[N]. Prefix pltData with a BTI C
875     // instruction.
876     memcpy(buf, btiData, sizeof(btiData));
877     buf += sizeof(btiData);
878     plt += sizeof(btiData);
879   }
880   memcpy(buf, pltData, sizeof(pltData));
881 
882   relocateNoSym(buf + 4, R_AARCH64_ADR_PREL_PG_HI21,
883                 getAArch64Page(got + 16) - getAArch64Page(plt + 8));
884   relocateNoSym(buf + 8, R_AARCH64_LDST64_ABS_LO12_NC, got + 16);
885   relocateNoSym(buf + 12, R_AARCH64_ADD_ABS_LO12_NC, got + 16);
886   if (!btiHeader)
887     // We didn't add the BTI c instruction so round out size with NOP.
888     memcpy(buf + sizeof(pltData), nopData, sizeof(nopData));
889 }
890 
891 void AArch64BtiPac::writePlt(uint8_t *buf, const Symbol &sym,
892                              uint64_t pltEntryAddr) const {
893   // The PLT entry is of the form:
894   // [btiData] addrInst (pacBr | stdBr) [nopData]
895   const uint8_t btiData[] = { 0x5f, 0x24, 0x03, 0xd5 }; // bti c
896   const uint8_t addrInst[] = {
897       0x10, 0x00, 0x00, 0x90,  // adrp x16, Page(&(.got.plt[n]))
898       0x11, 0x02, 0x40, 0xf9,  // ldr  x17, [x16, Offset(&(.got.plt[n]))]
899       0x10, 0x02, 0x00, 0x91   // add  x16, x16, Offset(&(.got.plt[n]))
900   };
901   const uint8_t pacBr[] = {
902       0x9f, 0x21, 0x03, 0xd5,  // autia1716
903       0x20, 0x02, 0x1f, 0xd6   // br   x17
904   };
905   const uint8_t stdBr[] = {
906       0x20, 0x02, 0x1f, 0xd6,  // br   x17
907       0x1f, 0x20, 0x03, 0xd5   // nop
908   };
909   const uint8_t nopData[] = { 0x1f, 0x20, 0x03, 0xd5 }; // nop
910 
911   // NEEDS_COPY indicates a non-ifunc canonical PLT entry whose address may
912   // escape to shared objects. isInIplt indicates a non-preemptible ifunc. Its
913   // address may escape if referenced by a direct relocation. The condition is
914   // conservative.
915   bool hasBti = btiHeader && (sym.hasFlag(NEEDS_COPY) || sym.isInIplt);
916   if (hasBti) {
917     memcpy(buf, btiData, sizeof(btiData));
918     buf += sizeof(btiData);
919     pltEntryAddr += sizeof(btiData);
920   }
921 
922   uint64_t gotPltEntryAddr = sym.getGotPltVA();
923   memcpy(buf, addrInst, sizeof(addrInst));
924   relocateNoSym(buf, R_AARCH64_ADR_PREL_PG_HI21,
925                 getAArch64Page(gotPltEntryAddr) - getAArch64Page(pltEntryAddr));
926   relocateNoSym(buf + 4, R_AARCH64_LDST64_ABS_LO12_NC, gotPltEntryAddr);
927   relocateNoSym(buf + 8, R_AARCH64_ADD_ABS_LO12_NC, gotPltEntryAddr);
928 
929   if (pacEntry)
930     memcpy(buf + sizeof(addrInst), pacBr, sizeof(pacBr));
931   else
932     memcpy(buf + sizeof(addrInst), stdBr, sizeof(stdBr));
933   if (!hasBti)
934     // We didn't add the BTI c instruction so round out size with NOP.
935     memcpy(buf + sizeof(addrInst) + sizeof(stdBr), nopData, sizeof(nopData));
936 }
937 
938 static TargetInfo *getTargetInfo() {
939   if ((config->andFeatures & GNU_PROPERTY_AARCH64_FEATURE_1_BTI) ||
940       config->zPacPlt) {
941     static AArch64BtiPac t;
942     return &t;
943   }
944   static AArch64 t;
945   return &t;
946 }
947 
948 TargetInfo *elf::getAArch64TargetInfo() { return getTargetInfo(); }
949