1 //===- ARM64.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 "InputFiles.h"
10 #include "Symbols.h"
11 #include "SyntheticSections.h"
12 #include "Target.h"
13 
14 #include "lld/Common/ErrorHandler.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/BinaryFormat/MachO.h"
18 #include "llvm/Support/Endian.h"
19 #include "llvm/Support/MathExtras.h"
20 
21 using namespace llvm::MachO;
22 using namespace llvm::support::endian;
23 using namespace lld;
24 using namespace lld::macho;
25 
26 namespace {
27 
28 struct ARM64 : TargetInfo {
29   ARM64();
30 
31   uint64_t getEmbeddedAddend(MemoryBufferRef, const section_64 &,
32                              const relocation_info) const override;
33   void relocateOne(uint8_t *loc, const Reloc &, uint64_t va,
34                    uint64_t pc) const override;
35 
36   void writeStub(uint8_t *buf, const macho::Symbol &) const override;
37   void writeStubHelperHeader(uint8_t *buf) const override;
38   void writeStubHelperEntry(uint8_t *buf, const DylibSymbol &,
39                             uint64_t entryAddr) const override;
40 
41   void relaxGotLoad(uint8_t *loc, uint8_t type) const override;
42   const TargetInfo::RelocAttrs &getRelocAttrs(uint8_t type) const override;
43   uint64_t getPageSize() const override { return 16 * 1024; }
44 };
45 
46 } // namespace
47 
48 // Random notes on reloc types:
49 // ADDEND always pairs with BRANCH26, PAGE21, or PAGEOFF12
50 // SUBTRACTOR always pairs with UNSIGNED (a delta between two sections)
51 // POINTER_TO_GOT: 4-byte is pc-relative, 8-byte is absolute
52 
53 const TargetInfo::RelocAttrs &ARM64::getRelocAttrs(uint8_t type) const {
54   static const std::array<TargetInfo::RelocAttrs, 11> relocAttrsArray{{
55 #define B(x) RelocAttrBits::x
56       {"UNSIGNED", B(ABSOLUTE) | B(EXTERN) | B(LOCAL) | B(TLV) | B(DYSYM8) |
57                        B(BYTE4) | B(BYTE8)},
58       {"SUBTRACTOR", B(SUBTRAHEND) | B(BYTE8)},
59       {"BRANCH26", B(PCREL) | B(EXTERN) | B(BRANCH) | B(BYTE4)},
60       {"PAGE21", B(PCREL) | B(EXTERN) | B(BYTE4)},
61       {"PAGEOFF12", B(ABSOLUTE) | B(EXTERN) | B(BYTE4)},
62       {"GOT_LOAD_PAGE21", B(PCREL) | B(EXTERN) | B(GOT) | B(BYTE4)},
63       {"GOT_LOAD_PAGEOFF12",
64        B(ABSOLUTE) | B(EXTERN) | B(GOT) | B(LOAD) | B(BYTE4)},
65       {"POINTER_TO_GOT", B(PCREL) | B(EXTERN) | B(GOT) | B(BYTE4) | B(BYTE8)},
66       {"TLVP_LOAD_PAGE21", B(PCREL) | B(EXTERN) | B(TLV) | B(BYTE4)},
67       {"TLVP_LOAD_PAGEOFF12",
68        B(ABSOLUTE) | B(EXTERN) | B(TLV) | B(LOAD) | B(BYTE4)},
69       {"ADDEND", B(ADDEND)},
70 #undef B
71   }};
72   assert(type < relocAttrsArray.size() && "invalid relocation type");
73   if (type >= relocAttrsArray.size())
74     return TargetInfo::invalidRelocAttrs;
75   return relocAttrsArray[type];
76 }
77 
78 uint64_t ARM64::getEmbeddedAddend(MemoryBufferRef mb, const section_64 &sec,
79                                   const relocation_info rel) const {
80   // TODO(gkm): extract embedded addend just so we can assert that it is 0
81   return 0;
82 }
83 
84 inline uint64_t bitField(uint64_t value, int right, int width, int left) {
85   return ((value >> right) & ((1 << width) - 1)) << left;
86 }
87 
88 //              25                                                0
89 // +-----------+---------------------------------------------------+
90 // |           |                       imm26                       |
91 // +-----------+---------------------------------------------------+
92 
93 inline uint64_t encodeBranch26(uint64_t base, uint64_t va) {
94   // Since branch destinations are 4-byte aligned, the 2 least-
95   // significant bits are 0. They are right shifted off the end.
96   return (base | bitField(va, 2, 26, 0));
97 }
98 
99 //   30 29          23                                  5
100 // +-+---+---------+-------------------------------------+---------+
101 // | |ilo|         |                immhi                |         |
102 // +-+---+---------+-------------------------------------+---------+
103 
104 inline uint64_t encodePage21(uint64_t base, uint64_t va) {
105   return (base | bitField(va, 12, 2, 29) | bitField(va, 14, 19, 5));
106 }
107 
108 //                      21                   10
109 // +-------------------+-----------------------+-------------------+
110 // |                   |         imm12         |                   |
111 // +-------------------+-----------------------+-------------------+
112 
113 inline uint64_t encodePageOff12(uint64_t base, uint64_t va) {
114   int scale = ((base & 0x3b000000) == 0x39000000) ? base >> 30 : 0;
115   // TODO(gkm): extract embedded addend and warn if != 0
116   // uint64_t addend = ((base & 0x003FFC00) >> 10);
117   return (base | bitField(va, scale, 12 - scale, 10));
118 }
119 
120 inline uint64_t pageBits(uint64_t address) {
121   const uint64_t pageMask = ~0xfffull;
122   return address & pageMask;
123 }
124 
125 // For instruction relocations (load, store, add), the base
126 // instruction is pre-populated in the text section. A pre-populated
127 // instruction has opcode & register-operand bits set, with immediate
128 // operands zeroed. We read it from text, OR-in the immediate
129 // operands, then write-back the completed instruction.
130 
131 void ARM64::relocateOne(uint8_t *loc, const Reloc &r, uint64_t value,
132                         uint64_t pc) const {
133   uint32_t base = ((r.length == 2) ? read32le(loc) : 0);
134   value += r.addend;
135   switch (r.type) {
136   case ARM64_RELOC_BRANCH26:
137     value = encodeBranch26(base, value - pc);
138     break;
139   case ARM64_RELOC_UNSIGNED:
140     break;
141   case ARM64_RELOC_POINTER_TO_GOT:
142     if (r.pcrel)
143       value -= pc;
144     break;
145   case ARM64_RELOC_PAGE21:
146   case ARM64_RELOC_GOT_LOAD_PAGE21:
147   case ARM64_RELOC_TLVP_LOAD_PAGE21:
148     assert(r.pcrel);
149     value = encodePage21(base, pageBits(value) - pageBits(pc));
150     break;
151   case ARM64_RELOC_PAGEOFF12:
152   case ARM64_RELOC_GOT_LOAD_PAGEOFF12:
153   case ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
154     assert(!r.pcrel);
155     value = encodePageOff12(base, value);
156     break;
157   default:
158     llvm_unreachable("unexpected relocation type");
159   }
160 
161   switch (r.length) {
162   case 2:
163     write32le(loc, value);
164     break;
165   case 3:
166     write64le(loc, value);
167     break;
168   default:
169     llvm_unreachable("invalid r_length");
170   }
171 }
172 
173 static constexpr uint32_t stubCode[] = {
174     0x90000010, // 00: adrp  x16, __la_symbol_ptr@page
175     0xf9400210, // 04: ldr   x16, [x16, __la_symbol_ptr@pageoff]
176     0xd61f0200, // 08: br    x16
177 };
178 
179 void ARM64::writeStub(uint8_t *buf8, const macho::Symbol &sym) const {
180   auto *buf32 = reinterpret_cast<uint32_t *>(buf8);
181   uint64_t pcPageBits =
182       pageBits(in.stubs->addr + sym.stubsIndex * sizeof(stubCode));
183   uint64_t lazyPointerVA = in.lazyPointers->addr + sym.stubsIndex * WordSize;
184   buf32[0] = encodePage21(stubCode[0], pageBits(lazyPointerVA) - pcPageBits);
185   buf32[1] = encodePageOff12(stubCode[1], lazyPointerVA);
186   buf32[2] = stubCode[2];
187 }
188 
189 static constexpr uint32_t stubHelperHeaderCode[] = {
190     0x90000011, // 00: adrp  x17, _dyld_private@page
191     0x91000231, // 04: add   x17, x17, _dyld_private@pageoff
192     0xa9bf47f0, // 08: stp   x16/x17, [sp, #-16]!
193     0x90000010, // 0c: adrp  x16, dyld_stub_binder@page
194     0xf9400210, // 10: ldr   x16, [x16, dyld_stub_binder@pageoff]
195     0xd61f0200, // 14: br    x16
196 };
197 
198 void ARM64::writeStubHelperHeader(uint8_t *buf8) const {
199   auto *buf32 = reinterpret_cast<uint32_t *>(buf8);
200   auto pcPageBits = [](int i) {
201     return pageBits(in.stubHelper->addr + i * sizeof(uint32_t));
202   };
203   uint64_t loaderVA = in.imageLoaderCache->getVA();
204   buf32[0] =
205       encodePage21(stubHelperHeaderCode[0], pageBits(loaderVA) - pcPageBits(0));
206   buf32[1] = encodePageOff12(stubHelperHeaderCode[1], loaderVA);
207   buf32[2] = stubHelperHeaderCode[2];
208   uint64_t binderVA =
209       in.got->addr + in.stubHelper->stubBinder->gotIndex * WordSize;
210   buf32[3] =
211       encodePage21(stubHelperHeaderCode[3], pageBits(binderVA) - pcPageBits(3));
212   buf32[4] = encodePageOff12(stubHelperHeaderCode[4], binderVA);
213   buf32[5] = stubHelperHeaderCode[5];
214 }
215 
216 static constexpr uint32_t stubHelperEntryCode[] = {
217     0x18000050, // 00: ldr  w16, l0
218     0x14000000, // 04: b    stubHelperHeader
219     0x00000000, // 08: l0: .long 0
220 };
221 
222 void ARM64::writeStubHelperEntry(uint8_t *buf8, const DylibSymbol &sym,
223                                  uint64_t entryVA) const {
224   auto *buf32 = reinterpret_cast<uint32_t *>(buf8);
225   auto pcVA = [entryVA](int i) { return entryVA + i * sizeof(uint32_t); };
226   uint64_t stubHelperHeaderVA = in.stubHelper->addr;
227   buf32[0] = stubHelperEntryCode[0];
228   buf32[1] =
229       encodeBranch26(stubHelperEntryCode[1], stubHelperHeaderVA - pcVA(1));
230   buf32[2] = sym.lazyBindOffset;
231 }
232 
233 void ARM64::relaxGotLoad(uint8_t *loc, uint8_t type) const {
234   // The instruction format comments below are quoted from
235   // Arm® Architecture Reference Manual
236   // Armv8, for Armv8-A architecture profile
237   // ARM DDI 0487G.a (ID011921)
238   uint32_t instruction = read32le(loc);
239   // C6.2.132 LDR (immediate)
240   // LDR <Xt>, [<Xn|SP>{, #<pimm>}]
241   if ((instruction & 0xffc00000) != 0xf9400000)
242     error(getRelocAttrs(type).name + " reloc requires LDR instruction");
243   assert(((instruction >> 10) & 0xfff) == 0 &&
244          "non-zero embedded LDR immediate");
245   // C6.2.4 ADD (immediate)
246   // ADD <Xd|SP>, <Xn|SP>, #<imm>{, <shift>}
247   instruction = ((instruction & 0x001fffff) | 0x91000000);
248   write32le(loc, instruction);
249 }
250 
251 ARM64::ARM64() {
252   cpuType = CPU_TYPE_ARM64;
253   cpuSubtype = CPU_SUBTYPE_ARM64_ALL;
254 
255   stubSize = sizeof(stubCode);
256   stubHelperHeaderSize = sizeof(stubHelperHeaderCode);
257   stubHelperEntrySize = sizeof(stubHelperEntryCode);
258 }
259 
260 TargetInfo *macho::createARM64TargetInfo() {
261   static ARM64 t;
262   return &t;
263 }
264