xref: /llvm-project-15.0.7/lld/ELF/Thunks.cpp (revision 18b45339)
1 //===- Thunks.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 // This file contains Thunk subclasses.
10 //
11 // A thunk is a small piece of code written after an input section
12 // which is used to jump between "incompatible" functions
13 // such as MIPS PIC and non-PIC or ARM non-Thumb and Thumb functions.
14 //
15 // If a jump target is too far and its address doesn't fit to a
16 // short jump instruction, we need to create a thunk too, but we
17 // haven't supported it yet.
18 //
19 // i386 and x86-64 don't need thunks.
20 //
21 //===---------------------------------------------------------------------===//
22 
23 #include "Thunks.h"
24 #include "Config.h"
25 #include "InputSection.h"
26 #include "OutputSections.h"
27 #include "Symbols.h"
28 #include "SyntheticSections.h"
29 #include "Target.h"
30 #include "lld/Common/ErrorHandler.h"
31 #include "lld/Common/Memory.h"
32 #include "llvm/BinaryFormat/ELF.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/Endian.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include <cstdint>
38 #include <cstring>
39 
40 using namespace llvm;
41 using namespace llvm::object;
42 using namespace llvm::ELF;
43 using namespace lld;
44 using namespace lld::elf;
45 
46 namespace {
47 
48 // AArch64 long range Thunks
49 class AArch64ABSLongThunk final : public Thunk {
50 public:
51   AArch64ABSLongThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {}
52   uint32_t size() override { return 16; }
53   void writeTo(uint8_t *buf) override;
54   void addSymbols(ThunkSection &isec) override;
55 };
56 
57 class AArch64ADRPThunk final : public Thunk {
58 public:
59   AArch64ADRPThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {}
60   uint32_t size() override { return 12; }
61   void writeTo(uint8_t *buf) override;
62   void addSymbols(ThunkSection &isec) override;
63 };
64 
65 // Base class for ARM thunks.
66 //
67 // An ARM thunk may be either short or long. A short thunk is simply a branch
68 // (B) instruction, and it may be used to call ARM functions when the distance
69 // from the thunk to the target is less than 32MB. Long thunks can branch to any
70 // virtual address and can switch between ARM and Thumb, and they are
71 // implemented in the derived classes. This class tries to create a short thunk
72 // if the target is in range, otherwise it creates a long thunk.
73 class ARMThunk : public Thunk {
74 public:
75   ARMThunk(Symbol &dest) : Thunk(dest, 0) {}
76 
77   bool getMayUseShortThunk();
78   uint32_t size() override { return getMayUseShortThunk() ? 4 : sizeLong(); }
79   void writeTo(uint8_t *buf) override;
80   bool isCompatibleWith(const InputSection &isec,
81                         const Relocation &rel) const override;
82 
83   // Returns the size of a long thunk.
84   virtual uint32_t sizeLong() = 0;
85 
86   // Writes a long thunk to Buf.
87   virtual void writeLong(uint8_t *buf) = 0;
88 
89 private:
90   // This field tracks whether all previously considered layouts would allow
91   // this thunk to be short. If we have ever needed a long thunk, we always
92   // create a long thunk, even if the thunk may be short given the current
93   // distance to the target. We do this because transitioning from long to short
94   // can create layout oscillations in certain corner cases which would prevent
95   // the layout from converging.
96   bool mayUseShortThunk = true;
97 };
98 
99 // Base class for Thumb-2 thunks.
100 //
101 // This class is similar to ARMThunk, but it uses the Thumb-2 B.W instruction
102 // which has a range of 16MB.
103 class ThumbThunk : public Thunk {
104 public:
105   ThumbThunk(Symbol &dest) : Thunk(dest, 0) { alignment = 2; }
106 
107   bool getMayUseShortThunk();
108   uint32_t size() override { return getMayUseShortThunk() ? 4 : sizeLong(); }
109   void writeTo(uint8_t *buf) override;
110   bool isCompatibleWith(const InputSection &isec,
111                         const Relocation &rel) const override;
112 
113   // Returns the size of a long thunk.
114   virtual uint32_t sizeLong() = 0;
115 
116   // Writes a long thunk to Buf.
117   virtual void writeLong(uint8_t *buf) = 0;
118 
119 private:
120   // See comment in ARMThunk above.
121   bool mayUseShortThunk = true;
122 };
123 
124 // Specific ARM Thunk implementations. The naming convention is:
125 // Source State, TargetState, Target Requirement, ABS or PI, Range
126 class ARMV7ABSLongThunk final : public ARMThunk {
127 public:
128   ARMV7ABSLongThunk(Symbol &dest) : ARMThunk(dest) {}
129 
130   uint32_t sizeLong() override { return 12; }
131   void writeLong(uint8_t *buf) override;
132   void addSymbols(ThunkSection &isec) override;
133 };
134 
135 class ARMV7PILongThunk final : public ARMThunk {
136 public:
137   ARMV7PILongThunk(Symbol &dest) : ARMThunk(dest) {}
138 
139   uint32_t sizeLong() override { return 16; }
140   void writeLong(uint8_t *buf) override;
141   void addSymbols(ThunkSection &isec) override;
142 };
143 
144 class ThumbV7ABSLongThunk final : public ThumbThunk {
145 public:
146   ThumbV7ABSLongThunk(Symbol &dest) : ThumbThunk(dest) {}
147 
148   uint32_t sizeLong() override { return 10; }
149   void writeLong(uint8_t *buf) override;
150   void addSymbols(ThunkSection &isec) override;
151 };
152 
153 class ThumbV7PILongThunk final : public ThumbThunk {
154 public:
155   ThumbV7PILongThunk(Symbol &dest) : ThumbThunk(dest) {}
156 
157   uint32_t sizeLong() override { return 12; }
158   void writeLong(uint8_t *buf) override;
159   void addSymbols(ThunkSection &isec) override;
160 };
161 
162 // Implementations of Thunks for older Arm architectures that do not support
163 // the movt/movw instructions. These thunks require at least Architecture v5
164 // as used on processors such as the Arm926ej-s. There are no Thumb entry
165 // points as there is no Thumb branch instruction on these architecture that
166 // can result in a thunk
167 class ARMV5ABSLongThunk final : public ARMThunk {
168 public:
169   ARMV5ABSLongThunk(Symbol &dest) : ARMThunk(dest) {}
170 
171   uint32_t sizeLong() override { return 8; }
172   void writeLong(uint8_t *buf) override;
173   void addSymbols(ThunkSection &isec) override;
174   bool isCompatibleWith(const InputSection &isec,
175                         const Relocation &rel) const override;
176 };
177 
178 class ARMV5PILongThunk final : public ARMThunk {
179 public:
180   ARMV5PILongThunk(Symbol &dest) : ARMThunk(dest) {}
181 
182   uint32_t sizeLong() override { return 16; }
183   void writeLong(uint8_t *buf) override;
184   void addSymbols(ThunkSection &isec) override;
185   bool isCompatibleWith(const InputSection &isec,
186                         const Relocation &rel) const override;
187 };
188 
189 // Implementations of Thunks for Arm v6-M. Only Thumb instructions are permitted
190 class ThumbV6MABSLongThunk final : public ThumbThunk {
191 public:
192   ThumbV6MABSLongThunk(Symbol &dest) : ThumbThunk(dest) {}
193 
194   uint32_t sizeLong() override { return 12; }
195   void writeLong(uint8_t *buf) override;
196   void addSymbols(ThunkSection &isec) override;
197 };
198 
199 class ThumbV6MPILongThunk final : public ThumbThunk {
200 public:
201   ThumbV6MPILongThunk(Symbol &dest) : ThumbThunk(dest) {}
202 
203   uint32_t sizeLong() override { return 16; }
204   void writeLong(uint8_t *buf) override;
205   void addSymbols(ThunkSection &isec) override;
206 };
207 
208 // MIPS LA25 thunk
209 class MipsThunk final : public Thunk {
210 public:
211   MipsThunk(Symbol &dest) : Thunk(dest, 0) {}
212 
213   uint32_t size() override { return 16; }
214   void writeTo(uint8_t *buf) override;
215   void addSymbols(ThunkSection &isec) override;
216   InputSection *getTargetInputSection() const override;
217 };
218 
219 // microMIPS R2-R5 LA25 thunk
220 class MicroMipsThunk final : public Thunk {
221 public:
222   MicroMipsThunk(Symbol &dest) : Thunk(dest, 0) {}
223 
224   uint32_t size() override { return 14; }
225   void writeTo(uint8_t *buf) override;
226   void addSymbols(ThunkSection &isec) override;
227   InputSection *getTargetInputSection() const override;
228 };
229 
230 // microMIPS R6 LA25 thunk
231 class MicroMipsR6Thunk final : public Thunk {
232 public:
233   MicroMipsR6Thunk(Symbol &dest) : Thunk(dest, 0) {}
234 
235   uint32_t size() override { return 12; }
236   void writeTo(uint8_t *buf) override;
237   void addSymbols(ThunkSection &isec) override;
238   InputSection *getTargetInputSection() const override;
239 };
240 
241 class PPC32PltCallStub final : public Thunk {
242 public:
243   // For R_PPC_PLTREL24, Thunk::addend records the addend which will be used to
244   // decide the offsets in the call stub.
245   PPC32PltCallStub(const InputSection &isec, const Relocation &rel,
246                    Symbol &dest)
247       : Thunk(dest, rel.addend), file(isec.file) {}
248   uint32_t size() override { return 16; }
249   void writeTo(uint8_t *buf) override;
250   void addSymbols(ThunkSection &isec) override;
251   bool isCompatibleWith(const InputSection &isec, const Relocation &rel) const override;
252 
253 private:
254   // Records the call site of the call stub.
255   const InputFile *file;
256 };
257 
258 class PPC32LongThunk final : public Thunk {
259 public:
260   PPC32LongThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {}
261   uint32_t size() override { return config->isPic ? 32 : 16; }
262   void writeTo(uint8_t *buf) override;
263   void addSymbols(ThunkSection &isec) override;
264 };
265 
266 // PPC64 Plt call stubs.
267 // Any call site that needs to call through a plt entry needs a call stub in
268 // the .text section. The call stub is responsible for:
269 // 1) Saving the toc-pointer to the stack.
270 // 2) Loading the target functions address from the procedure linkage table into
271 //    r12 for use by the target functions global entry point, and into the count
272 //    register.
273 // 3) Transferring control to the target function through an indirect branch.
274 class PPC64PltCallStub final : public Thunk {
275 public:
276   PPC64PltCallStub(Symbol &dest) : Thunk(dest, 0) {}
277   uint32_t size() override { return 20; }
278   void writeTo(uint8_t *buf) override;
279   void addSymbols(ThunkSection &isec) override;
280 };
281 
282 // PPC64 R2 Save Stub
283 // When the caller requires a valid R2 TOC pointer but the callee does not
284 // require a TOC pointer and the callee cannot guarantee that it doesn't
285 // clobber R2 then we need to save R2. This stub:
286 // 1) Saves the TOC pointer to the stack.
287 // 2) Tail calls the callee.
288 class PPC64R2SaveStub final : public Thunk {
289 public:
290   PPC64R2SaveStub(Symbol &dest) : Thunk(dest, 0) {}
291   uint32_t size() override { return 8; }
292   void writeTo(uint8_t *buf) override;
293   void addSymbols(ThunkSection &isec) override;
294 };
295 
296 // PPC64 R12 Setup Stub
297 // When a caller that does not maintain a toc-pointer performs a local call to
298 // a callee which requires a toc-pointer then we need this stub to place the
299 // callee's global entry point into r12 without a save of R2.
300 class PPC64R12SetupStub final : public Thunk {
301 public:
302   PPC64R12SetupStub(Symbol &dest) : Thunk(dest, 0) {}
303   uint32_t size() override { return 16; }
304   void writeTo(uint8_t *buf) override;
305   void addSymbols(ThunkSection &isec) override;
306 };
307 
308 // A bl instruction uses a signed 24 bit offset, with an implicit 4 byte
309 // alignment. This gives a possible 26 bits of 'reach'. If the call offset is
310 // larger then that we need to emit a long-branch thunk. The target address
311 // of the callee is stored in a table to be accessed TOC-relative. Since the
312 // call must be local (a non-local call will have a PltCallStub instead) the
313 // table stores the address of the callee's local entry point. For
314 // position-independent code a corresponding relative dynamic relocation is
315 // used.
316 class PPC64LongBranchThunk : public Thunk {
317 public:
318   uint32_t size() override { return 16; }
319   void writeTo(uint8_t *buf) override;
320   void addSymbols(ThunkSection &isec) override;
321 
322 protected:
323   PPC64LongBranchThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {}
324 };
325 
326 class PPC64PILongBranchThunk final : public PPC64LongBranchThunk {
327 public:
328   PPC64PILongBranchThunk(Symbol &dest, int64_t addend)
329       : PPC64LongBranchThunk(dest, addend) {
330     assert(!dest.isPreemptible);
331     if (Optional<uint32_t> index =
332             in.ppc64LongBranchTarget->addEntry(&dest, addend)) {
333       mainPart->relaDyn->addReloc(
334           {target->relativeRel, in.ppc64LongBranchTarget, *index * UINT64_C(8),
335            true, &dest,
336            addend + getPPC64GlobalEntryToLocalEntryOffset(dest.stOther)});
337     }
338   }
339 };
340 
341 class PPC64PDLongBranchThunk final : public PPC64LongBranchThunk {
342 public:
343   PPC64PDLongBranchThunk(Symbol &dest, int64_t addend)
344       : PPC64LongBranchThunk(dest, addend) {
345     in.ppc64LongBranchTarget->addEntry(&dest, addend);
346   }
347 };
348 
349 } // end anonymous namespace
350 
351 Defined *Thunk::addSymbol(StringRef name, uint8_t type, uint64_t value,
352                           InputSectionBase &section) {
353   Defined *d = addSyntheticLocal(name, type, value, /*size=*/0, section);
354   syms.push_back(d);
355   return d;
356 }
357 
358 void Thunk::setOffset(uint64_t newOffset) {
359   for (Defined *d : syms)
360     d->value = d->value - offset + newOffset;
361   offset = newOffset;
362 }
363 
364 // AArch64 long range Thunks
365 
366 static uint64_t getAArch64ThunkDestVA(const Symbol &s, int64_t a) {
367   uint64_t v = s.isInPlt() ? s.getPltVA() : s.getVA(a);
368   return v;
369 }
370 
371 void AArch64ABSLongThunk::writeTo(uint8_t *buf) {
372   const uint8_t data[] = {
373     0x50, 0x00, 0x00, 0x58, //     ldr x16, L0
374     0x00, 0x02, 0x1f, 0xd6, //     br  x16
375     0x00, 0x00, 0x00, 0x00, // L0: .xword S
376     0x00, 0x00, 0x00, 0x00,
377   };
378   uint64_t s = getAArch64ThunkDestVA(destination, addend);
379   memcpy(buf, data, sizeof(data));
380   target->relocateNoSym(buf + 8, R_AARCH64_ABS64, s);
381 }
382 
383 void AArch64ABSLongThunk::addSymbols(ThunkSection &isec) {
384   addSymbol(saver.save("__AArch64AbsLongThunk_" + destination.getName()),
385             STT_FUNC, 0, isec);
386   addSymbol("$x", STT_NOTYPE, 0, isec);
387   addSymbol("$d", STT_NOTYPE, 8, isec);
388 }
389 
390 // This Thunk has a maximum range of 4Gb, this is sufficient for all programs
391 // using the small code model, including pc-relative ones. At time of writing
392 // clang and gcc do not support the large code model for position independent
393 // code so it is safe to use this for position independent thunks without
394 // worrying about the destination being more than 4Gb away.
395 void AArch64ADRPThunk::writeTo(uint8_t *buf) {
396   const uint8_t data[] = {
397       0x10, 0x00, 0x00, 0x90, // adrp x16, Dest R_AARCH64_ADR_PREL_PG_HI21(Dest)
398       0x10, 0x02, 0x00, 0x91, // add  x16, x16, R_AARCH64_ADD_ABS_LO12_NC(Dest)
399       0x00, 0x02, 0x1f, 0xd6, // br   x16
400   };
401   uint64_t s = getAArch64ThunkDestVA(destination, addend);
402   uint64_t p = getThunkTargetSym()->getVA();
403   memcpy(buf, data, sizeof(data));
404   target->relocateNoSym(buf, R_AARCH64_ADR_PREL_PG_HI21,
405                         getAArch64Page(s) - getAArch64Page(p));
406   target->relocateNoSym(buf + 4, R_AARCH64_ADD_ABS_LO12_NC, s);
407 }
408 
409 void AArch64ADRPThunk::addSymbols(ThunkSection &isec) {
410   addSymbol(saver.save("__AArch64ADRPThunk_" + destination.getName()), STT_FUNC,
411             0, isec);
412   addSymbol("$x", STT_NOTYPE, 0, isec);
413 }
414 
415 // ARM Target Thunks
416 static uint64_t getARMThunkDestVA(const Symbol &s) {
417   uint64_t v = s.isInPlt() ? s.getPltVA() : s.getVA();
418   return SignExtend64<32>(v);
419 }
420 
421 // This function returns true if the target is not Thumb and is within 2^26, and
422 // it has not previously returned false (see comment for mayUseShortThunk).
423 bool ARMThunk::getMayUseShortThunk() {
424   if (!mayUseShortThunk)
425     return false;
426   uint64_t s = getARMThunkDestVA(destination);
427   if (s & 1) {
428     mayUseShortThunk = false;
429     return false;
430   }
431   uint64_t p = getThunkTargetSym()->getVA();
432   int64_t offset = s - p - 8;
433   mayUseShortThunk = llvm::isInt<26>(offset);
434   return mayUseShortThunk;
435 }
436 
437 void ARMThunk::writeTo(uint8_t *buf) {
438   if (!getMayUseShortThunk()) {
439     writeLong(buf);
440     return;
441   }
442 
443   uint64_t s = getARMThunkDestVA(destination);
444   uint64_t p = getThunkTargetSym()->getVA();
445   int64_t offset = s - p - 8;
446   const uint8_t data[] = {
447     0x00, 0x00, 0x00, 0xea, // b S
448   };
449   memcpy(buf, data, sizeof(data));
450   target->relocateNoSym(buf, R_ARM_JUMP24, offset);
451 }
452 
453 bool ARMThunk::isCompatibleWith(const InputSection &isec,
454                                 const Relocation &rel) const {
455   // Thumb branch relocations can't use BLX
456   return rel.type != R_ARM_THM_JUMP19 && rel.type != R_ARM_THM_JUMP24;
457 }
458 
459 // This function returns true if the target is Thumb and is within 2^25, and
460 // it has not previously returned false (see comment for mayUseShortThunk).
461 bool ThumbThunk::getMayUseShortThunk() {
462   if (!mayUseShortThunk)
463     return false;
464   uint64_t s = getARMThunkDestVA(destination);
465   if ((s & 1) == 0) {
466     mayUseShortThunk = false;
467     return false;
468   }
469   uint64_t p = getThunkTargetSym()->getVA() & ~1;
470   int64_t offset = s - p - 4;
471   mayUseShortThunk = llvm::isInt<25>(offset);
472   return mayUseShortThunk;
473 }
474 
475 void ThumbThunk::writeTo(uint8_t *buf) {
476   if (!getMayUseShortThunk()) {
477     writeLong(buf);
478     return;
479   }
480 
481   uint64_t s = getARMThunkDestVA(destination);
482   uint64_t p = getThunkTargetSym()->getVA();
483   int64_t offset = s - p - 4;
484   const uint8_t data[] = {
485       0x00, 0xf0, 0x00, 0xb0, // b.w S
486   };
487   memcpy(buf, data, sizeof(data));
488   target->relocateNoSym(buf, R_ARM_THM_JUMP24, offset);
489 }
490 
491 bool ThumbThunk::isCompatibleWith(const InputSection &isec,
492                                   const Relocation &rel) const {
493   // ARM branch relocations can't use BLX
494   return rel.type != R_ARM_JUMP24 && rel.type != R_ARM_PC24 && rel.type != R_ARM_PLT32;
495 }
496 
497 void ARMV7ABSLongThunk::writeLong(uint8_t *buf) {
498   const uint8_t data[] = {
499       0x00, 0xc0, 0x00, 0xe3, // movw         ip,:lower16:S
500       0x00, 0xc0, 0x40, 0xe3, // movt         ip,:upper16:S
501       0x1c, 0xff, 0x2f, 0xe1, // bx   ip
502   };
503   uint64_t s = getARMThunkDestVA(destination);
504   memcpy(buf, data, sizeof(data));
505   target->relocateNoSym(buf, R_ARM_MOVW_ABS_NC, s);
506   target->relocateNoSym(buf + 4, R_ARM_MOVT_ABS, s);
507 }
508 
509 void ARMV7ABSLongThunk::addSymbols(ThunkSection &isec) {
510   addSymbol(saver.save("__ARMv7ABSLongThunk_" + destination.getName()),
511             STT_FUNC, 0, isec);
512   addSymbol("$a", STT_NOTYPE, 0, isec);
513 }
514 
515 void ThumbV7ABSLongThunk::writeLong(uint8_t *buf) {
516   const uint8_t data[] = {
517       0x40, 0xf2, 0x00, 0x0c, // movw         ip, :lower16:S
518       0xc0, 0xf2, 0x00, 0x0c, // movt         ip, :upper16:S
519       0x60, 0x47,             // bx   ip
520   };
521   uint64_t s = getARMThunkDestVA(destination);
522   memcpy(buf, data, sizeof(data));
523   target->relocateNoSym(buf, R_ARM_THM_MOVW_ABS_NC, s);
524   target->relocateNoSym(buf + 4, R_ARM_THM_MOVT_ABS, s);
525 }
526 
527 void ThumbV7ABSLongThunk::addSymbols(ThunkSection &isec) {
528   addSymbol(saver.save("__Thumbv7ABSLongThunk_" + destination.getName()),
529             STT_FUNC, 1, isec);
530   addSymbol("$t", STT_NOTYPE, 0, isec);
531 }
532 
533 void ARMV7PILongThunk::writeLong(uint8_t *buf) {
534   const uint8_t data[] = {
535       0xf0, 0xcf, 0x0f, 0xe3, // P:  movw ip,:lower16:S - (P + (L1-P) + 8)
536       0x00, 0xc0, 0x40, 0xe3, //     movt ip,:upper16:S - (P + (L1-P) + 8)
537       0x0f, 0xc0, 0x8c, 0xe0, // L1: add  ip, ip, pc
538       0x1c, 0xff, 0x2f, 0xe1, //     bx   ip
539   };
540   uint64_t s = getARMThunkDestVA(destination);
541   uint64_t p = getThunkTargetSym()->getVA();
542   int64_t offset = s - p - 16;
543   memcpy(buf, data, sizeof(data));
544   target->relocateNoSym(buf, R_ARM_MOVW_PREL_NC, offset);
545   target->relocateNoSym(buf + 4, R_ARM_MOVT_PREL, offset);
546 }
547 
548 void ARMV7PILongThunk::addSymbols(ThunkSection &isec) {
549   addSymbol(saver.save("__ARMV7PILongThunk_" + destination.getName()), STT_FUNC,
550             0, isec);
551   addSymbol("$a", STT_NOTYPE, 0, isec);
552 }
553 
554 void ThumbV7PILongThunk::writeLong(uint8_t *buf) {
555   const uint8_t data[] = {
556       0x4f, 0xf6, 0xf4, 0x7c, // P:  movw ip,:lower16:S - (P + (L1-P) + 4)
557       0xc0, 0xf2, 0x00, 0x0c, //     movt ip,:upper16:S - (P + (L1-P) + 4)
558       0xfc, 0x44,             // L1: add  ip, pc
559       0x60, 0x47,             //     bx   ip
560   };
561   uint64_t s = getARMThunkDestVA(destination);
562   uint64_t p = getThunkTargetSym()->getVA() & ~0x1;
563   int64_t offset = s - p - 12;
564   memcpy(buf, data, sizeof(data));
565   target->relocateNoSym(buf, R_ARM_THM_MOVW_PREL_NC, offset);
566   target->relocateNoSym(buf + 4, R_ARM_THM_MOVT_PREL, offset);
567 }
568 
569 void ThumbV7PILongThunk::addSymbols(ThunkSection &isec) {
570   addSymbol(saver.save("__ThumbV7PILongThunk_" + destination.getName()),
571             STT_FUNC, 1, isec);
572   addSymbol("$t", STT_NOTYPE, 0, isec);
573 }
574 
575 void ARMV5ABSLongThunk::writeLong(uint8_t *buf) {
576   const uint8_t data[] = {
577       0x04, 0xf0, 0x1f, 0xe5, //     ldr pc, [pc,#-4] ; L1
578       0x00, 0x00, 0x00, 0x00, // L1: .word S
579   };
580   memcpy(buf, data, sizeof(data));
581   target->relocateNoSym(buf + 4, R_ARM_ABS32, getARMThunkDestVA(destination));
582 }
583 
584 void ARMV5ABSLongThunk::addSymbols(ThunkSection &isec) {
585   addSymbol(saver.save("__ARMv5ABSLongThunk_" + destination.getName()),
586             STT_FUNC, 0, isec);
587   addSymbol("$a", STT_NOTYPE, 0, isec);
588   addSymbol("$d", STT_NOTYPE, 4, isec);
589 }
590 
591 bool ARMV5ABSLongThunk::isCompatibleWith(const InputSection &isec,
592                                          const Relocation &rel) const {
593   // Thumb branch relocations can't use BLX
594   return rel.type != R_ARM_THM_JUMP19 && rel.type != R_ARM_THM_JUMP24;
595 }
596 
597 void ARMV5PILongThunk::writeLong(uint8_t *buf) {
598   const uint8_t data[] = {
599       0x04, 0xc0, 0x9f, 0xe5, // P:  ldr ip, [pc,#4] ; L2
600       0x0c, 0xc0, 0x8f, 0xe0, // L1: add ip, pc, ip
601       0x1c, 0xff, 0x2f, 0xe1, //     bx ip
602       0x00, 0x00, 0x00, 0x00, // L2: .word S - (P + (L1 - P) + 8)
603   };
604   uint64_t s = getARMThunkDestVA(destination);
605   uint64_t p = getThunkTargetSym()->getVA() & ~0x1;
606   memcpy(buf, data, sizeof(data));
607   target->relocateNoSym(buf + 12, R_ARM_REL32, s - p - 12);
608 }
609 
610 void ARMV5PILongThunk::addSymbols(ThunkSection &isec) {
611   addSymbol(saver.save("__ARMV5PILongThunk_" + destination.getName()), STT_FUNC,
612             0, isec);
613   addSymbol("$a", STT_NOTYPE, 0, isec);
614   addSymbol("$d", STT_NOTYPE, 12, isec);
615 }
616 
617 bool ARMV5PILongThunk::isCompatibleWith(const InputSection &isec,
618                                         const Relocation &rel) const {
619   // Thumb branch relocations can't use BLX
620   return rel.type != R_ARM_THM_JUMP19 && rel.type != R_ARM_THM_JUMP24;
621 }
622 
623 void ThumbV6MABSLongThunk::writeLong(uint8_t *buf) {
624   // Most Thumb instructions cannot access the high registers r8 - r15. As the
625   // only register we can corrupt is r12 we must instead spill a low register
626   // to the stack to use as a scratch register. We push r1 even though we
627   // don't need to get some space to use for the return address.
628   const uint8_t data[] = {
629       0x03, 0xb4,            // push {r0, r1} ; Obtain scratch registers
630       0x01, 0x48,            // ldr r0, [pc, #4] ; L1
631       0x01, 0x90,            // str r0, [sp, #4] ; SP + 4 = S
632       0x01, 0xbd,            // pop {r0, pc} ; restore r0 and branch to dest
633       0x00, 0x00, 0x00, 0x00 // L1: .word S
634   };
635   uint64_t s = getARMThunkDestVA(destination);
636   memcpy(buf, data, sizeof(data));
637   target->relocateNoSym(buf + 8, R_ARM_ABS32, s);
638 }
639 
640 void ThumbV6MABSLongThunk::addSymbols(ThunkSection &isec) {
641   addSymbol(saver.save("__Thumbv6MABSLongThunk_" + destination.getName()),
642             STT_FUNC, 1, isec);
643   addSymbol("$t", STT_NOTYPE, 0, isec);
644   addSymbol("$d", STT_NOTYPE, 8, isec);
645 }
646 
647 void ThumbV6MPILongThunk::writeLong(uint8_t *buf) {
648   // Most Thumb instructions cannot access the high registers r8 - r15. As the
649   // only register we can corrupt is ip (r12) we must instead spill a low
650   // register to the stack to use as a scratch register.
651   const uint8_t data[] = {
652       0x01, 0xb4,             // P:  push {r0}        ; Obtain scratch register
653       0x02, 0x48,             //     ldr r0, [pc, #8] ; L2
654       0x84, 0x46,             //     mov ip, r0       ; high to low register
655       0x01, 0xbc,             //     pop {r0}         ; restore scratch register
656       0xe7, 0x44,             // L1: add pc, ip       ; transfer control
657       0xc0, 0x46,             //     nop              ; pad to 4-byte boundary
658       0x00, 0x00, 0x00, 0x00, // L2: .word S - (P + (L1 - P) + 4)
659   };
660   uint64_t s = getARMThunkDestVA(destination);
661   uint64_t p = getThunkTargetSym()->getVA() & ~0x1;
662   memcpy(buf, data, sizeof(data));
663   target->relocateNoSym(buf + 12, R_ARM_REL32, s - p - 12);
664 }
665 
666 void ThumbV6MPILongThunk::addSymbols(ThunkSection &isec) {
667   addSymbol(saver.save("__Thumbv6MPILongThunk_" + destination.getName()),
668             STT_FUNC, 1, isec);
669   addSymbol("$t", STT_NOTYPE, 0, isec);
670   addSymbol("$d", STT_NOTYPE, 12, isec);
671 }
672 
673 // Write MIPS LA25 thunk code to call PIC function from the non-PIC one.
674 void MipsThunk::writeTo(uint8_t *buf) {
675   uint64_t s = destination.getVA();
676   write32(buf, 0x3c190000); // lui   $25, %hi(func)
677   write32(buf + 4, 0x08000000 | (s >> 2)); // j     func
678   write32(buf + 8, 0x27390000); // addiu $25, $25, %lo(func)
679   write32(buf + 12, 0x00000000); // nop
680   target->relocateNoSym(buf, R_MIPS_HI16, s);
681   target->relocateNoSym(buf + 8, R_MIPS_LO16, s);
682 }
683 
684 void MipsThunk::addSymbols(ThunkSection &isec) {
685   addSymbol(saver.save("__LA25Thunk_" + destination.getName()), STT_FUNC, 0,
686             isec);
687 }
688 
689 InputSection *MipsThunk::getTargetInputSection() const {
690   auto &dr = cast<Defined>(destination);
691   return dyn_cast<InputSection>(dr.section);
692 }
693 
694 // Write microMIPS R2-R5 LA25 thunk code
695 // to call PIC function from the non-PIC one.
696 void MicroMipsThunk::writeTo(uint8_t *buf) {
697   uint64_t s = destination.getVA();
698   write16(buf, 0x41b9);       // lui   $25, %hi(func)
699   write16(buf + 4, 0xd400);   // j     func
700   write16(buf + 8, 0x3339);   // addiu $25, $25, %lo(func)
701   write16(buf + 12, 0x0c00);  // nop
702   target->relocateNoSym(buf, R_MICROMIPS_HI16, s);
703   target->relocateNoSym(buf + 4, R_MICROMIPS_26_S1, s);
704   target->relocateNoSym(buf + 8, R_MICROMIPS_LO16, s);
705 }
706 
707 void MicroMipsThunk::addSymbols(ThunkSection &isec) {
708   Defined *d = addSymbol(
709       saver.save("__microLA25Thunk_" + destination.getName()), STT_FUNC, 0, isec);
710   d->stOther |= STO_MIPS_MICROMIPS;
711 }
712 
713 InputSection *MicroMipsThunk::getTargetInputSection() const {
714   auto &dr = cast<Defined>(destination);
715   return dyn_cast<InputSection>(dr.section);
716 }
717 
718 // Write microMIPS R6 LA25 thunk code
719 // to call PIC function from the non-PIC one.
720 void MicroMipsR6Thunk::writeTo(uint8_t *buf) {
721   uint64_t s = destination.getVA();
722   uint64_t p = getThunkTargetSym()->getVA();
723   write16(buf, 0x1320);       // lui   $25, %hi(func)
724   write16(buf + 4, 0x3339);   // addiu $25, $25, %lo(func)
725   write16(buf + 8, 0x9400);   // bc    func
726   target->relocateNoSym(buf, R_MICROMIPS_HI16, s);
727   target->relocateNoSym(buf + 4, R_MICROMIPS_LO16, s);
728   target->relocateNoSym(buf + 8, R_MICROMIPS_PC26_S1, s - p - 12);
729 }
730 
731 void MicroMipsR6Thunk::addSymbols(ThunkSection &isec) {
732   Defined *d = addSymbol(
733       saver.save("__microLA25Thunk_" + destination.getName()), STT_FUNC, 0, isec);
734   d->stOther |= STO_MIPS_MICROMIPS;
735 }
736 
737 InputSection *MicroMipsR6Thunk::getTargetInputSection() const {
738   auto &dr = cast<Defined>(destination);
739   return dyn_cast<InputSection>(dr.section);
740 }
741 
742 void elf::writePPC32PltCallStub(uint8_t *buf, uint64_t gotPltVA,
743                                 const InputFile *file, int64_t addend) {
744   if (!config->isPic) {
745     write32(buf + 0, 0x3d600000 | (gotPltVA + 0x8000) >> 16); // lis r11,ha
746     write32(buf + 4, 0x816b0000 | (uint16_t)gotPltVA);        // lwz r11,l(r11)
747     write32(buf + 8, 0x7d6903a6);                             // mtctr r11
748     write32(buf + 12, 0x4e800420);                            // bctr
749     return;
750   }
751   uint32_t offset;
752   if (addend >= 0x8000) {
753     // The stub loads an address relative to r30 (.got2+Addend). Addend is
754     // almost always 0x8000. The address of .got2 is different in another object
755     // file, so a stub cannot be shared.
756     offset = gotPltVA - (in.ppc32Got2->getParent()->getVA() +
757                          file->ppc32Got2OutSecOff + addend);
758   } else {
759     // The stub loads an address relative to _GLOBAL_OFFSET_TABLE_ (which is
760     // currently the address of .got).
761     offset = gotPltVA - in.got->getVA();
762   }
763   uint16_t ha = (offset + 0x8000) >> 16, l = (uint16_t)offset;
764   if (ha == 0) {
765     write32(buf + 0, 0x817e0000 | l); // lwz r11,l(r30)
766     write32(buf + 4, 0x7d6903a6);     // mtctr r11
767     write32(buf + 8, 0x4e800420);     // bctr
768     write32(buf + 12, 0x60000000);    // nop
769   } else {
770     write32(buf + 0, 0x3d7e0000 | ha); // addis r11,r30,ha
771     write32(buf + 4, 0x816b0000 | l);  // lwz r11,l(r11)
772     write32(buf + 8, 0x7d6903a6);      // mtctr r11
773     write32(buf + 12, 0x4e800420);     // bctr
774   }
775 }
776 
777 void PPC32PltCallStub::writeTo(uint8_t *buf) {
778   writePPC32PltCallStub(buf, destination.getGotPltVA(), file, addend);
779 }
780 
781 void PPC32PltCallStub::addSymbols(ThunkSection &isec) {
782   std::string buf;
783   raw_string_ostream os(buf);
784   os << format_hex_no_prefix(addend, 8);
785   if (!config->isPic)
786     os << ".plt_call32.";
787   else if (addend >= 0x8000)
788     os << ".got2.plt_pic32.";
789   else
790     os << ".plt_pic32.";
791   os << destination.getName();
792   addSymbol(saver.save(os.str()), STT_FUNC, 0, isec);
793 }
794 
795 bool PPC32PltCallStub::isCompatibleWith(const InputSection &isec,
796                                         const Relocation &rel) const {
797   return !config->isPic || (isec.file == file && rel.addend == addend);
798 }
799 
800 void PPC32LongThunk::addSymbols(ThunkSection &isec) {
801   addSymbol(saver.save("__LongThunk_" + destination.getName()), STT_FUNC, 0,
802             isec);
803 }
804 
805 void PPC32LongThunk::writeTo(uint8_t *buf) {
806   auto ha = [](uint32_t v) -> uint16_t { return (v + 0x8000) >> 16; };
807   auto lo = [](uint32_t v) -> uint16_t { return v; };
808   uint32_t d = destination.getVA(addend);
809   if (config->isPic) {
810     uint32_t off = d - (getThunkTargetSym()->getVA() + 8);
811     write32(buf + 0, 0x7c0802a6);            // mflr r12,0
812     write32(buf + 4, 0x429f0005);            // bcl r20,r31,.+4
813     write32(buf + 8, 0x7d8802a6);            // mtctr r12
814     write32(buf + 12, 0x3d8c0000 | ha(off)); // addis r12,r12,off@ha
815     write32(buf + 16, 0x398c0000 | lo(off)); // addi r12,r12,off@l
816     write32(buf + 20, 0x7c0803a6);           // mtlr r0
817     buf += 24;
818   } else {
819     write32(buf + 0, 0x3d800000 | ha(d));    // lis r12,d@ha
820     write32(buf + 4, 0x398c0000 | lo(d));    // addi r12,r12,d@l
821     buf += 8;
822   }
823   write32(buf + 0, 0x7d8903a6);              // mtctr r12
824   write32(buf + 4, 0x4e800420);              // bctr
825 }
826 
827 void elf::writePPC64LoadAndBranch(uint8_t *buf, int64_t offset) {
828   uint16_t offHa = (offset + 0x8000) >> 16;
829   uint16_t offLo = offset & 0xffff;
830 
831   write32(buf + 0, 0x3d820000 | offHa); // addis r12, r2, OffHa
832   write32(buf + 4, 0xe98c0000 | offLo); // ld    r12, OffLo(r12)
833   write32(buf + 8, 0x7d8903a6);         // mtctr r12
834   write32(buf + 12, 0x4e800420);        // bctr
835 }
836 
837 void PPC64PltCallStub::writeTo(uint8_t *buf) {
838   int64_t offset = destination.getGotPltVA() - getPPC64TocBase();
839   // Save the TOC pointer to the save-slot reserved in the call frame.
840   write32(buf + 0, 0xf8410018); // std     r2,24(r1)
841   writePPC64LoadAndBranch(buf + 4, offset);
842 }
843 
844 void PPC64PltCallStub::addSymbols(ThunkSection &isec) {
845   Defined *s = addSymbol(saver.save("__plt_" + destination.getName()), STT_FUNC,
846                          0, isec);
847   s->needsTocRestore = true;
848   s->file = destination.file;
849 }
850 
851 void PPC64R2SaveStub::writeTo(uint8_t *buf) {
852   int64_t offset = destination.getVA() - (getThunkTargetSym()->getVA() + 4);
853   // The branch offset needs to fit in 26 bits.
854   if (!isInt<26>(offset))
855     fatal("R2 save stub branch offset is too large: " + Twine(offset));
856   write32(buf + 0, 0xf8410018);                         // std  r2,24(r1)
857   write32(buf + 4, 0x48000000 | (offset & 0x03fffffc)); // b    <offset>
858 }
859 
860 void PPC64R2SaveStub::addSymbols(ThunkSection &isec) {
861   Defined *s = addSymbol(saver.save("__toc_save_" + destination.getName()),
862                          STT_FUNC, 0, isec);
863   s->needsTocRestore = true;
864 }
865 
866 void PPC64R12SetupStub::writeTo(uint8_t *buf) {
867   int64_t offset = destination.getVA() - getThunkTargetSym()->getVA();
868   if (!isInt<34>(offset))
869     fatal("offset must fit in 34 bits to encode in the instruction");
870   uint64_t paddi = PADDI_R12_NO_DISP | (((offset >> 16) & 0x3ffff) << 32) |
871                    (offset & 0xffff);
872 
873   writePrefixedInstruction(buf + 0, paddi); // paddi r12, 0, func@pcrel, 1
874   write32(buf + 8, MTCTR_R12);              // mtctr r12
875   write32(buf + 12, BCTR);                  // bctr
876 }
877 
878 void PPC64R12SetupStub::addSymbols(ThunkSection &isec) {
879   addSymbol(saver.save("__gep_setup_" + destination.getName()), STT_FUNC, 0,
880             isec);
881 }
882 
883 void PPC64LongBranchThunk::writeTo(uint8_t *buf) {
884   int64_t offset = in.ppc64LongBranchTarget->getEntryVA(&destination, addend) -
885                    getPPC64TocBase();
886   writePPC64LoadAndBranch(buf, offset);
887 }
888 
889 void PPC64LongBranchThunk::addSymbols(ThunkSection &isec) {
890   addSymbol(saver.save("__long_branch_" + destination.getName()), STT_FUNC, 0,
891             isec);
892 }
893 
894 Thunk::Thunk(Symbol &d, int64_t a) : destination(d), addend(a), offset(0) {}
895 
896 Thunk::~Thunk() = default;
897 
898 static Thunk *addThunkAArch64(RelType type, Symbol &s, int64_t a) {
899   if (type != R_AARCH64_CALL26 && type != R_AARCH64_JUMP26 &&
900       type != R_AARCH64_PLT32)
901     fatal("unrecognized relocation type");
902   if (config->picThunk)
903     return make<AArch64ADRPThunk>(s, a);
904   return make<AArch64ABSLongThunk>(s, a);
905 }
906 
907 // Creates a thunk for Thumb-ARM interworking.
908 // Arm Architectures v5 and v6 do not support Thumb2 technology. This means
909 // - MOVT and MOVW instructions cannot be used
910 // - Only Thumb relocation that can generate a Thunk is a BL, this can always
911 //   be transformed into a BLX
912 static Thunk *addThunkPreArmv7(RelType reloc, Symbol &s) {
913   switch (reloc) {
914   case R_ARM_PC24:
915   case R_ARM_PLT32:
916   case R_ARM_JUMP24:
917   case R_ARM_CALL:
918   case R_ARM_THM_CALL:
919     if (config->picThunk)
920       return make<ARMV5PILongThunk>(s);
921     return make<ARMV5ABSLongThunk>(s);
922   }
923   fatal("relocation " + toString(reloc) + " to " + toString(s) +
924         " not supported for Armv5 or Armv6 targets");
925 }
926 
927 // Create a thunk for Thumb long branch on V6-M.
928 // Arm Architecture v6-M only supports Thumb instructions. This means
929 // - MOVT and MOVW instructions cannot be used.
930 // - Only a limited number of instructions can access registers r8 and above
931 // - No interworking support is needed (all Thumb).
932 static Thunk *addThunkV6M(RelType reloc, Symbol &s) {
933   switch (reloc) {
934   case R_ARM_THM_JUMP19:
935   case R_ARM_THM_JUMP24:
936   case R_ARM_THM_CALL:
937     if (config->isPic)
938       return make<ThumbV6MPILongThunk>(s);
939     return make<ThumbV6MABSLongThunk>(s);
940   }
941   fatal("relocation " + toString(reloc) + " to " + toString(s) +
942         " not supported for Armv6-M targets");
943 }
944 
945 // Creates a thunk for Thumb-ARM interworking or branch range extension.
946 static Thunk *addThunkArm(RelType reloc, Symbol &s) {
947   // Decide which Thunk is needed based on:
948   // Available instruction set
949   // - An Arm Thunk can only be used if Arm state is available.
950   // - A Thumb Thunk can only be used if Thumb state is available.
951   // - Can only use a Thunk if it uses instructions that the Target supports.
952   // Relocation is branch or branch and link
953   // - Branch instructions cannot change state, can only select Thunk that
954   //   starts in the same state as the caller.
955   // - Branch and link relocations can change state, can select Thunks from
956   //   either Arm or Thumb.
957   // Position independent Thunks if we require position independent code.
958 
959   // Handle architectures that have restrictions on the instructions that they
960   // can use in Thunks. The flags below are set by reading the BuildAttributes
961   // of the input objects. InputFiles.cpp contains the mapping from ARM
962   // architecture to flag.
963   if (!config->armHasMovtMovw) {
964     if (!config->armJ1J2BranchEncoding)
965       return addThunkPreArmv7(reloc, s);
966     return addThunkV6M(reloc, s);
967   }
968 
969   switch (reloc) {
970   case R_ARM_PC24:
971   case R_ARM_PLT32:
972   case R_ARM_JUMP24:
973   case R_ARM_CALL:
974     if (config->picThunk)
975       return make<ARMV7PILongThunk>(s);
976     return make<ARMV7ABSLongThunk>(s);
977   case R_ARM_THM_JUMP19:
978   case R_ARM_THM_JUMP24:
979   case R_ARM_THM_CALL:
980     if (config->picThunk)
981       return make<ThumbV7PILongThunk>(s);
982     return make<ThumbV7ABSLongThunk>(s);
983   }
984   fatal("unrecognized relocation type");
985 }
986 
987 static Thunk *addThunkMips(RelType type, Symbol &s) {
988   if ((s.stOther & STO_MIPS_MICROMIPS) && isMipsR6())
989     return make<MicroMipsR6Thunk>(s);
990   if (s.stOther & STO_MIPS_MICROMIPS)
991     return make<MicroMipsThunk>(s);
992   return make<MipsThunk>(s);
993 }
994 
995 static Thunk *addThunkPPC32(const InputSection &isec, const Relocation &rel,
996                             Symbol &s) {
997   assert((rel.type == R_PPC_LOCAL24PC || rel.type == R_PPC_REL24 ||
998           rel.type == R_PPC_PLTREL24) &&
999          "unexpected relocation type for thunk");
1000   if (s.isInPlt())
1001     return make<PPC32PltCallStub>(isec, rel, s);
1002   return make<PPC32LongThunk>(s, rel.addend);
1003 }
1004 
1005 static Thunk *addThunkPPC64(RelType type, Symbol &s, int64_t a) {
1006   assert((type == R_PPC64_REL14 || type == R_PPC64_REL24 ||
1007           type == R_PPC64_REL24_NOTOC) &&
1008          "unexpected relocation type for thunk");
1009   if (s.isInPlt())
1010     return make<PPC64PltCallStub>(s);
1011 
1012   // This check looks at the st_other bits of the callee. If the value is 1
1013   // then the callee clobbers the TOC and we need an R2 save stub.
1014   if ((s.stOther >> 5) == 1)
1015     return make<PPC64R2SaveStub>(s);
1016 
1017   if (type == R_PPC64_REL24_NOTOC && (s.stOther >> 5) > 1)
1018     return make<PPC64R12SetupStub>(s);
1019 
1020   if (config->picThunk)
1021     return make<PPC64PILongBranchThunk>(s, a);
1022 
1023   return make<PPC64PDLongBranchThunk>(s, a);
1024 }
1025 
1026 Thunk *elf::addThunk(const InputSection &isec, Relocation &rel) {
1027   Symbol &s = *rel.sym;
1028   int64_t a = rel.addend;
1029 
1030   if (config->emachine == EM_AARCH64)
1031     return addThunkAArch64(rel.type, s, a);
1032 
1033   if (config->emachine == EM_ARM)
1034     return addThunkArm(rel.type, s);
1035 
1036   if (config->emachine == EM_MIPS)
1037     return addThunkMips(rel.type, s);
1038 
1039   if (config->emachine == EM_PPC)
1040     return addThunkPPC32(isec, rel, s);
1041 
1042   if (config->emachine == EM_PPC64)
1043     return addThunkPPC64(rel.type, s, a);
1044 
1045   llvm_unreachable("add Thunk only supported for ARM, Mips and PowerPC");
1046 }
1047