1ece8a530Spatrick //===- AArch64ErrataFix.cpp -----------------------------------------------===//
2ece8a530Spatrick //
3ece8a530Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ece8a530Spatrick // See https://llvm.org/LICENSE.txt for license information.
5ece8a530Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ece8a530Spatrick //
7ece8a530Spatrick //===----------------------------------------------------------------------===//
8ece8a530Spatrick // This file implements Section Patching for the purpose of working around
9ece8a530Spatrick // the AArch64 Cortex-53 errata 843419 that affects r0p0, r0p1, r0p2 and r0p4
10ece8a530Spatrick // versions of the core.
11ece8a530Spatrick //
12ece8a530Spatrick // The general principle is that an erratum sequence of one or
13ece8a530Spatrick // more instructions is detected in the instruction stream, one of the
14ece8a530Spatrick // instructions in the sequence is replaced with a branch to a patch sequence
15ece8a530Spatrick // of replacement instructions. At the end of the replacement sequence the
16ece8a530Spatrick // patch branches back to the instruction stream.
17ece8a530Spatrick
18ece8a530Spatrick // This technique is only suitable for fixing an erratum when:
19ece8a530Spatrick // - There is a set of necessary conditions required to trigger the erratum that
20ece8a530Spatrick // can be detected at static link time.
21ece8a530Spatrick // - There is a set of replacement instructions that can be used to remove at
22ece8a530Spatrick // least one of the necessary conditions that trigger the erratum.
23ece8a530Spatrick // - We can overwrite an instruction in the erratum sequence with a branch to
24ece8a530Spatrick // the replacement sequence.
25ece8a530Spatrick // - We can place the replacement sequence within range of the branch.
26ece8a530Spatrick //===----------------------------------------------------------------------===//
27ece8a530Spatrick
28ece8a530Spatrick #include "AArch64ErrataFix.h"
29*dfe94b16Srobert #include "InputFiles.h"
30ece8a530Spatrick #include "LinkerScript.h"
31ece8a530Spatrick #include "OutputSections.h"
32ece8a530Spatrick #include "Relocations.h"
33ece8a530Spatrick #include "Symbols.h"
34ece8a530Spatrick #include "SyntheticSections.h"
35ece8a530Spatrick #include "Target.h"
36*dfe94b16Srobert #include "lld/Common/CommonLinkerContext.h"
37ece8a530Spatrick #include "lld/Common/Strings.h"
38ece8a530Spatrick #include "llvm/Support/Endian.h"
39ece8a530Spatrick #include <algorithm>
40ece8a530Spatrick
41ece8a530Spatrick using namespace llvm;
42ece8a530Spatrick using namespace llvm::ELF;
43ece8a530Spatrick using namespace llvm::object;
44ece8a530Spatrick using namespace llvm::support;
45ece8a530Spatrick using namespace llvm::support::endian;
46bb684c34Spatrick using namespace lld;
47bb684c34Spatrick using namespace lld::elf;
48ece8a530Spatrick
49ece8a530Spatrick // Helper functions to identify instructions and conditions needed to trigger
50ece8a530Spatrick // the Cortex-A53-843419 erratum.
51ece8a530Spatrick
52ece8a530Spatrick // ADRP
53ece8a530Spatrick // | 1 | immlo (2) | 1 | 0 0 0 0 | immhi (19) | Rd (5) |
isADRP(uint32_t instr)54ece8a530Spatrick static bool isADRP(uint32_t instr) {
55ece8a530Spatrick return (instr & 0x9f000000) == 0x90000000;
56ece8a530Spatrick }
57ece8a530Spatrick
58*dfe94b16Srobert // Load and store bit patterns from ARMv8-A.
59ece8a530Spatrick // Instructions appear in order of appearance starting from table in
60ece8a530Spatrick // C4.1.3 Loads and Stores.
61ece8a530Spatrick
62ece8a530Spatrick // All loads and stores have 1 (at bit position 27), (0 at bit position 25).
63ece8a530Spatrick // | op0 x op1 (2) | 1 op2 0 op3 (2) | x | op4 (5) | xxxx | op5 (2) | x (10) |
isLoadStoreClass(uint32_t instr)64ece8a530Spatrick static bool isLoadStoreClass(uint32_t instr) {
65ece8a530Spatrick return (instr & 0x0a000000) == 0x08000000;
66ece8a530Spatrick }
67ece8a530Spatrick
68ece8a530Spatrick // LDN/STN multiple no offset
69ece8a530Spatrick // | 0 Q 00 | 1100 | 0 L 00 | 0000 | opcode (4) | size (2) | Rn (5) | Rt (5) |
70ece8a530Spatrick // LDN/STN multiple post-indexed
71ece8a530Spatrick // | 0 Q 00 | 1100 | 1 L 0 | Rm (5)| opcode (4) | size (2) | Rn (5) | Rt (5) |
72ece8a530Spatrick // L == 0 for stores.
73ece8a530Spatrick
74ece8a530Spatrick // Utility routine to decode opcode field of LDN/STN multiple structure
75ece8a530Spatrick // instructions to find the ST1 instructions.
76ece8a530Spatrick // opcode == 0010 ST1 4 registers.
77ece8a530Spatrick // opcode == 0110 ST1 3 registers.
78ece8a530Spatrick // opcode == 0111 ST1 1 register.
79ece8a530Spatrick // opcode == 1010 ST1 2 registers.
isST1MultipleOpcode(uint32_t instr)80ece8a530Spatrick static bool isST1MultipleOpcode(uint32_t instr) {
81ece8a530Spatrick return (instr & 0x0000f000) == 0x00002000 ||
82ece8a530Spatrick (instr & 0x0000f000) == 0x00006000 ||
83ece8a530Spatrick (instr & 0x0000f000) == 0x00007000 ||
84ece8a530Spatrick (instr & 0x0000f000) == 0x0000a000;
85ece8a530Spatrick }
86ece8a530Spatrick
isST1Multiple(uint32_t instr)87ece8a530Spatrick static bool isST1Multiple(uint32_t instr) {
88ece8a530Spatrick return (instr & 0xbfff0000) == 0x0c000000 && isST1MultipleOpcode(instr);
89ece8a530Spatrick }
90ece8a530Spatrick
91ece8a530Spatrick // Writes to Rn (writeback).
isST1MultiplePost(uint32_t instr)92ece8a530Spatrick static bool isST1MultiplePost(uint32_t instr) {
93ece8a530Spatrick return (instr & 0xbfe00000) == 0x0c800000 && isST1MultipleOpcode(instr);
94ece8a530Spatrick }
95ece8a530Spatrick
96ece8a530Spatrick // LDN/STN single no offset
97ece8a530Spatrick // | 0 Q 00 | 1101 | 0 L R 0 | 0000 | opc (3) S | size (2) | Rn (5) | Rt (5)|
98ece8a530Spatrick // LDN/STN single post-indexed
99ece8a530Spatrick // | 0 Q 00 | 1101 | 1 L R | Rm (5) | opc (3) S | size (2) | Rn (5) | Rt (5)|
100ece8a530Spatrick // L == 0 for stores
101ece8a530Spatrick
102ece8a530Spatrick // Utility routine to decode opcode field of LDN/STN single structure
103ece8a530Spatrick // instructions to find the ST1 instructions.
104ece8a530Spatrick // R == 0 for ST1 and ST3, R == 1 for ST2 and ST4.
105ece8a530Spatrick // opcode == 000 ST1 8-bit.
106ece8a530Spatrick // opcode == 010 ST1 16-bit.
107ece8a530Spatrick // opcode == 100 ST1 32 or 64-bit (Size determines which).
isST1SingleOpcode(uint32_t instr)108ece8a530Spatrick static bool isST1SingleOpcode(uint32_t instr) {
109ece8a530Spatrick return (instr & 0x0040e000) == 0x00000000 ||
110ece8a530Spatrick (instr & 0x0040e000) == 0x00004000 ||
111ece8a530Spatrick (instr & 0x0040e000) == 0x00008000;
112ece8a530Spatrick }
113ece8a530Spatrick
isST1Single(uint32_t instr)114ece8a530Spatrick static bool isST1Single(uint32_t instr) {
115ece8a530Spatrick return (instr & 0xbfff0000) == 0x0d000000 && isST1SingleOpcode(instr);
116ece8a530Spatrick }
117ece8a530Spatrick
118ece8a530Spatrick // Writes to Rn (writeback).
isST1SinglePost(uint32_t instr)119ece8a530Spatrick static bool isST1SinglePost(uint32_t instr) {
120ece8a530Spatrick return (instr & 0xbfe00000) == 0x0d800000 && isST1SingleOpcode(instr);
121ece8a530Spatrick }
122ece8a530Spatrick
isST1(uint32_t instr)123ece8a530Spatrick static bool isST1(uint32_t instr) {
124ece8a530Spatrick return isST1Multiple(instr) || isST1MultiplePost(instr) ||
125ece8a530Spatrick isST1Single(instr) || isST1SinglePost(instr);
126ece8a530Spatrick }
127ece8a530Spatrick
128ece8a530Spatrick // Load/store exclusive
129ece8a530Spatrick // | size (2) 00 | 1000 | o2 L o1 | Rs (5) | o0 | Rt2 (5) | Rn (5) | Rt (5) |
130ece8a530Spatrick // L == 0 for Stores.
isLoadStoreExclusive(uint32_t instr)131ece8a530Spatrick static bool isLoadStoreExclusive(uint32_t instr) {
132ece8a530Spatrick return (instr & 0x3f000000) == 0x08000000;
133ece8a530Spatrick }
134ece8a530Spatrick
isLoadExclusive(uint32_t instr)135ece8a530Spatrick static bool isLoadExclusive(uint32_t instr) {
136ece8a530Spatrick return (instr & 0x3f400000) == 0x08400000;
137ece8a530Spatrick }
138ece8a530Spatrick
139ece8a530Spatrick // Load register literal
140ece8a530Spatrick // | opc (2) 01 | 1 V 00 | imm19 | Rt (5) |
isLoadLiteral(uint32_t instr)141ece8a530Spatrick static bool isLoadLiteral(uint32_t instr) {
142ece8a530Spatrick return (instr & 0x3b000000) == 0x18000000;
143ece8a530Spatrick }
144ece8a530Spatrick
145ece8a530Spatrick // Load/store no-allocate pair
146ece8a530Spatrick // (offset)
147ece8a530Spatrick // | opc (2) 10 | 1 V 00 | 0 L | imm7 | Rt2 (5) | Rn (5) | Rt (5) |
148ece8a530Spatrick // L == 0 for stores.
149ece8a530Spatrick // Never writes to register
isSTNP(uint32_t instr)150ece8a530Spatrick static bool isSTNP(uint32_t instr) {
151ece8a530Spatrick return (instr & 0x3bc00000) == 0x28000000;
152ece8a530Spatrick }
153ece8a530Spatrick
154ece8a530Spatrick // Load/store register pair
155ece8a530Spatrick // (post-indexed)
156ece8a530Spatrick // | opc (2) 10 | 1 V 00 | 1 L | imm7 | Rt2 (5) | Rn (5) | Rt (5) |
157ece8a530Spatrick // L == 0 for stores, V == 0 for Scalar, V == 1 for Simd/FP
158ece8a530Spatrick // Writes to Rn.
isSTPPost(uint32_t instr)159ece8a530Spatrick static bool isSTPPost(uint32_t instr) {
160ece8a530Spatrick return (instr & 0x3bc00000) == 0x28800000;
161ece8a530Spatrick }
162ece8a530Spatrick
163ece8a530Spatrick // (offset)
164ece8a530Spatrick // | opc (2) 10 | 1 V 01 | 0 L | imm7 | Rt2 (5) | Rn (5) | Rt (5) |
isSTPOffset(uint32_t instr)165ece8a530Spatrick static bool isSTPOffset(uint32_t instr) {
166ece8a530Spatrick return (instr & 0x3bc00000) == 0x29000000;
167ece8a530Spatrick }
168ece8a530Spatrick
169ece8a530Spatrick // (pre-index)
170ece8a530Spatrick // | opc (2) 10 | 1 V 01 | 1 L | imm7 | Rt2 (5) | Rn (5) | Rt (5) |
171ece8a530Spatrick // Writes to Rn.
isSTPPre(uint32_t instr)172ece8a530Spatrick static bool isSTPPre(uint32_t instr) {
173ece8a530Spatrick return (instr & 0x3bc00000) == 0x29800000;
174ece8a530Spatrick }
175ece8a530Spatrick
isSTP(uint32_t instr)176ece8a530Spatrick static bool isSTP(uint32_t instr) {
177ece8a530Spatrick return isSTPPost(instr) || isSTPOffset(instr) || isSTPPre(instr);
178ece8a530Spatrick }
179ece8a530Spatrick
180ece8a530Spatrick // Load/store register (unscaled immediate)
181ece8a530Spatrick // | size (2) 11 | 1 V 00 | opc (2) 0 | imm9 | 00 | Rn (5) | Rt (5) |
182ece8a530Spatrick // V == 0 for Scalar, V == 1 for Simd/FP.
isLoadStoreUnscaled(uint32_t instr)183ece8a530Spatrick static bool isLoadStoreUnscaled(uint32_t instr) {
184ece8a530Spatrick return (instr & 0x3b000c00) == 0x38000000;
185ece8a530Spatrick }
186ece8a530Spatrick
187ece8a530Spatrick // Load/store register (immediate post-indexed)
188ece8a530Spatrick // | size (2) 11 | 1 V 00 | opc (2) 0 | imm9 | 01 | Rn (5) | Rt (5) |
isLoadStoreImmediatePost(uint32_t instr)189ece8a530Spatrick static bool isLoadStoreImmediatePost(uint32_t instr) {
190ece8a530Spatrick return (instr & 0x3b200c00) == 0x38000400;
191ece8a530Spatrick }
192ece8a530Spatrick
193ece8a530Spatrick // Load/store register (unprivileged)
194ece8a530Spatrick // | size (2) 11 | 1 V 00 | opc (2) 0 | imm9 | 10 | Rn (5) | Rt (5) |
isLoadStoreUnpriv(uint32_t instr)195ece8a530Spatrick static bool isLoadStoreUnpriv(uint32_t instr) {
196ece8a530Spatrick return (instr & 0x3b200c00) == 0x38000800;
197ece8a530Spatrick }
198ece8a530Spatrick
199ece8a530Spatrick // Load/store register (immediate pre-indexed)
200ece8a530Spatrick // | size (2) 11 | 1 V 00 | opc (2) 0 | imm9 | 11 | Rn (5) | Rt (5) |
isLoadStoreImmediatePre(uint32_t instr)201ece8a530Spatrick static bool isLoadStoreImmediatePre(uint32_t instr) {
202ece8a530Spatrick return (instr & 0x3b200c00) == 0x38000c00;
203ece8a530Spatrick }
204ece8a530Spatrick
205ece8a530Spatrick // Load/store register (register offset)
206ece8a530Spatrick // | size (2) 11 | 1 V 00 | opc (2) 1 | Rm (5) | option (3) S | 10 | Rn | Rt |
isLoadStoreRegisterOff(uint32_t instr)207ece8a530Spatrick static bool isLoadStoreRegisterOff(uint32_t instr) {
208ece8a530Spatrick return (instr & 0x3b200c00) == 0x38200800;
209ece8a530Spatrick }
210ece8a530Spatrick
211ece8a530Spatrick // Load/store register (unsigned immediate)
212ece8a530Spatrick // | size (2) 11 | 1 V 01 | opc (2) | imm12 | Rn (5) | Rt (5) |
isLoadStoreRegisterUnsigned(uint32_t instr)213ece8a530Spatrick static bool isLoadStoreRegisterUnsigned(uint32_t instr) {
214ece8a530Spatrick return (instr & 0x3b000000) == 0x39000000;
215ece8a530Spatrick }
216ece8a530Spatrick
217ece8a530Spatrick // Rt is always in bit position 0 - 4.
getRt(uint32_t instr)218ece8a530Spatrick static uint32_t getRt(uint32_t instr) { return (instr & 0x1f); }
219ece8a530Spatrick
220ece8a530Spatrick // Rn is always in bit position 5 - 9.
getRn(uint32_t instr)221ece8a530Spatrick static uint32_t getRn(uint32_t instr) { return (instr >> 5) & 0x1f; }
222ece8a530Spatrick
223ece8a530Spatrick // C4.1.2 Branches, Exception Generating and System instructions
224ece8a530Spatrick // | op0 (3) 1 | 01 op1 (4) | x (22) |
225ece8a530Spatrick // op0 == 010 101 op1 == 0xxx Conditional Branch.
226ece8a530Spatrick // op0 == 110 101 op1 == 1xxx Unconditional Branch Register.
227ece8a530Spatrick // op0 == x00 101 op1 == xxxx Unconditional Branch immediate.
228ece8a530Spatrick // op0 == x01 101 op1 == 0xxx Compare and branch immediate.
229ece8a530Spatrick // op0 == x01 101 op1 == 1xxx Test and branch immediate.
isBranch(uint32_t instr)230ece8a530Spatrick static bool isBranch(uint32_t instr) {
231ece8a530Spatrick return ((instr & 0xfe000000) == 0xd6000000) || // Cond branch.
232ece8a530Spatrick ((instr & 0xfe000000) == 0x54000000) || // Uncond branch reg.
233ece8a530Spatrick ((instr & 0x7c000000) == 0x14000000) || // Uncond branch imm.
234ece8a530Spatrick ((instr & 0x7c000000) == 0x34000000); // Compare and test branch.
235ece8a530Spatrick }
236ece8a530Spatrick
isV8SingleRegisterNonStructureLoadStore(uint32_t instr)237ece8a530Spatrick static bool isV8SingleRegisterNonStructureLoadStore(uint32_t instr) {
238ece8a530Spatrick return isLoadStoreUnscaled(instr) || isLoadStoreImmediatePost(instr) ||
239ece8a530Spatrick isLoadStoreUnpriv(instr) || isLoadStoreImmediatePre(instr) ||
240ece8a530Spatrick isLoadStoreRegisterOff(instr) || isLoadStoreRegisterUnsigned(instr);
241ece8a530Spatrick }
242ece8a530Spatrick
243ece8a530Spatrick // Note that this function refers to v8.0 only and does not include the
244ece8a530Spatrick // additional load and store instructions added for in later revisions of
245ece8a530Spatrick // the architecture such as the Atomic memory operations introduced
246ece8a530Spatrick // in v8.1.
isV8NonStructureLoad(uint32_t instr)247ece8a530Spatrick static bool isV8NonStructureLoad(uint32_t instr) {
248ece8a530Spatrick if (isLoadExclusive(instr))
249ece8a530Spatrick return true;
250ece8a530Spatrick if (isLoadLiteral(instr))
251ece8a530Spatrick return true;
252ece8a530Spatrick else if (isV8SingleRegisterNonStructureLoadStore(instr)) {
253ece8a530Spatrick // For Load and Store single register, Loads are derived from a
254ece8a530Spatrick // combination of the Size, V and Opc fields.
255ece8a530Spatrick uint32_t size = (instr >> 30) & 0xff;
256ece8a530Spatrick uint32_t v = (instr >> 26) & 0x1;
257ece8a530Spatrick uint32_t opc = (instr >> 22) & 0x3;
258ece8a530Spatrick // For the load and store instructions that we are decoding.
259ece8a530Spatrick // Opc == 0 are all stores.
260ece8a530Spatrick // Opc == 1 with a couple of exceptions are loads. The exceptions are:
261ece8a530Spatrick // Size == 00 (0), V == 1, Opc == 10 (2) which is a store and
262ece8a530Spatrick // Size == 11 (3), V == 0, Opc == 10 (2) which is a prefetch.
263ece8a530Spatrick return opc != 0 && !(size == 0 && v == 1 && opc == 2) &&
264ece8a530Spatrick !(size == 3 && v == 0 && opc == 2);
265ece8a530Spatrick }
266ece8a530Spatrick return false;
267ece8a530Spatrick }
268ece8a530Spatrick
269ece8a530Spatrick // The following decode instructions are only complete up to the instructions
270ece8a530Spatrick // needed for errata 843419.
271ece8a530Spatrick
272ece8a530Spatrick // Instruction with writeback updates the index register after the load/store.
hasWriteback(uint32_t instr)273ece8a530Spatrick static bool hasWriteback(uint32_t instr) {
274ece8a530Spatrick return isLoadStoreImmediatePre(instr) || isLoadStoreImmediatePost(instr) ||
275ece8a530Spatrick isSTPPre(instr) || isSTPPost(instr) || isST1SinglePost(instr) ||
276ece8a530Spatrick isST1MultiplePost(instr);
277ece8a530Spatrick }
278ece8a530Spatrick
279ece8a530Spatrick // For the load and store class of instructions, a load can write to the
280ece8a530Spatrick // destination register, a load and a store can write to the base register when
281ece8a530Spatrick // the instruction has writeback.
doesLoadStoreWriteToReg(uint32_t instr,uint32_t reg)282ece8a530Spatrick static bool doesLoadStoreWriteToReg(uint32_t instr, uint32_t reg) {
283ece8a530Spatrick return (isV8NonStructureLoad(instr) && getRt(instr) == reg) ||
284ece8a530Spatrick (hasWriteback(instr) && getRn(instr) == reg);
285ece8a530Spatrick }
286ece8a530Spatrick
287ece8a530Spatrick // Scanner for Cortex-A53 errata 843419
288ece8a530Spatrick // Full details are available in the Cortex A53 MPCore revision 0 Software
289ece8a530Spatrick // Developers Errata Notice (ARM-EPM-048406).
290ece8a530Spatrick //
291ece8a530Spatrick // The instruction sequence that triggers the erratum is common in compiled
292ece8a530Spatrick // AArch64 code, however it is sensitive to the offset of the sequence within
293ece8a530Spatrick // a 4k page. This means that by scanning and fixing the patch after we have
294ece8a530Spatrick // assigned addresses we only need to disassemble and fix instances of the
295ece8a530Spatrick // sequence in the range of affected offsets.
296ece8a530Spatrick //
297ece8a530Spatrick // In summary the erratum conditions are a series of 4 instructions:
298ece8a530Spatrick // 1.) An ADRP instruction that writes to register Rn with low 12 bits of
299ece8a530Spatrick // address of instruction either 0xff8 or 0xffc.
300ece8a530Spatrick // 2.) A load or store instruction that can be:
301ece8a530Spatrick // - A single register load or store, of either integer or vector registers.
302ece8a530Spatrick // - An STP or STNP, of either integer or vector registers.
303ece8a530Spatrick // - An Advanced SIMD ST1 store instruction.
304ece8a530Spatrick // - Must not write to Rn, but may optionally read from it.
305ece8a530Spatrick // 3.) An optional instruction that is not a branch and does not write to Rn.
306ece8a530Spatrick // 4.) A load or store from the Load/store register (unsigned immediate) class
307ece8a530Spatrick // that uses Rn as the base address register.
308ece8a530Spatrick //
309ece8a530Spatrick // Note that we do not attempt to scan for Sequence 2 as described in the
310ece8a530Spatrick // Software Developers Errata Notice as this has been assessed to be extremely
311ece8a530Spatrick // unlikely to occur in compiled code. This matches gold and ld.bfd behavior.
312ece8a530Spatrick
313ece8a530Spatrick // Return true if the Instruction sequence Adrp, Instr2, and Instr4 match
314ece8a530Spatrick // the erratum sequence. The Adrp, Instr2 and Instr4 correspond to 1.), 2.),
315ece8a530Spatrick // and 4.) in the Scanner for Cortex-A53 errata comment above.
is843419ErratumSequence(uint32_t instr1,uint32_t instr2,uint32_t instr4)316ece8a530Spatrick static bool is843419ErratumSequence(uint32_t instr1, uint32_t instr2,
317ece8a530Spatrick uint32_t instr4) {
318ece8a530Spatrick if (!isADRP(instr1))
319ece8a530Spatrick return false;
320ece8a530Spatrick
321ece8a530Spatrick uint32_t rn = getRt(instr1);
322ece8a530Spatrick return isLoadStoreClass(instr2) &&
323ece8a530Spatrick (isLoadStoreExclusive(instr2) || isLoadLiteral(instr2) ||
324ece8a530Spatrick isV8SingleRegisterNonStructureLoadStore(instr2) || isSTP(instr2) ||
325ece8a530Spatrick isSTNP(instr2) || isST1(instr2)) &&
326ece8a530Spatrick !doesLoadStoreWriteToReg(instr2, rn) &&
327ece8a530Spatrick isLoadStoreRegisterUnsigned(instr4) && getRn(instr4) == rn;
328ece8a530Spatrick }
329ece8a530Spatrick
330ece8a530Spatrick // Scan the instruction sequence starting at Offset Off from the base of
331ece8a530Spatrick // InputSection isec. We update Off in this function rather than in the caller
332ece8a530Spatrick // as we can skip ahead much further into the section when we know how many
333ece8a530Spatrick // instructions we've scanned.
334ece8a530Spatrick // Return the offset of the load or store instruction in isec that we want to
335ece8a530Spatrick // patch or 0 if no patch required.
scanCortexA53Errata843419(InputSection * isec,uint64_t & off,uint64_t limit)336ece8a530Spatrick static uint64_t scanCortexA53Errata843419(InputSection *isec, uint64_t &off,
337ece8a530Spatrick uint64_t limit) {
338ece8a530Spatrick uint64_t isecAddr = isec->getVA(0);
339ece8a530Spatrick
340ece8a530Spatrick // Advance Off so that (isecAddr + Off) modulo 0x1000 is at least 0xff8.
341ece8a530Spatrick uint64_t initialPageOff = (isecAddr + off) & 0xfff;
342ece8a530Spatrick if (initialPageOff < 0xff8)
343ece8a530Spatrick off += 0xff8 - initialPageOff;
344ece8a530Spatrick
345ece8a530Spatrick bool optionalAllowed = limit - off > 12;
346ece8a530Spatrick if (off >= limit || limit - off < 12) {
347ece8a530Spatrick // Need at least 3 4-byte sized instructions to trigger erratum.
348ece8a530Spatrick off = limit;
349ece8a530Spatrick return 0;
350ece8a530Spatrick }
351ece8a530Spatrick
352ece8a530Spatrick uint64_t patchOff = 0;
353*dfe94b16Srobert const uint8_t *buf = isec->content().begin();
354ece8a530Spatrick const ulittle32_t *instBuf = reinterpret_cast<const ulittle32_t *>(buf + off);
355ece8a530Spatrick uint32_t instr1 = *instBuf++;
356ece8a530Spatrick uint32_t instr2 = *instBuf++;
357ece8a530Spatrick uint32_t instr3 = *instBuf++;
358ece8a530Spatrick if (is843419ErratumSequence(instr1, instr2, instr3)) {
359ece8a530Spatrick patchOff = off + 8;
360ece8a530Spatrick } else if (optionalAllowed && !isBranch(instr3)) {
361ece8a530Spatrick uint32_t instr4 = *instBuf++;
362ece8a530Spatrick if (is843419ErratumSequence(instr1, instr2, instr4))
363ece8a530Spatrick patchOff = off + 12;
364ece8a530Spatrick }
365ece8a530Spatrick if (((isecAddr + off) & 0xfff) == 0xff8)
366ece8a530Spatrick off += 4;
367ece8a530Spatrick else
368ece8a530Spatrick off += 0xffc;
369ece8a530Spatrick return patchOff;
370ece8a530Spatrick }
371ece8a530Spatrick
372*dfe94b16Srobert class elf::Patch843419Section final : public SyntheticSection {
373ece8a530Spatrick public:
374ece8a530Spatrick Patch843419Section(InputSection *p, uint64_t off);
375ece8a530Spatrick
376ece8a530Spatrick void writeTo(uint8_t *buf) override;
377ece8a530Spatrick
getSize() const378ece8a530Spatrick size_t getSize() const override { return 8; }
379ece8a530Spatrick
380ece8a530Spatrick uint64_t getLDSTAddr() const;
381ece8a530Spatrick
classof(const SectionBase * d)382ece8a530Spatrick static bool classof(const SectionBase *d) {
383ece8a530Spatrick return d->kind() == InputSectionBase::Synthetic && d->name == ".text.patch";
384ece8a530Spatrick }
385ece8a530Spatrick
386ece8a530Spatrick // The Section we are patching.
387ece8a530Spatrick const InputSection *patchee;
388ece8a530Spatrick // The offset of the instruction in the patchee section we are patching.
389ece8a530Spatrick uint64_t patcheeOffset;
390ece8a530Spatrick // A label for the start of the Patch that we can use as a relocation target.
391ece8a530Spatrick Symbol *patchSym;
392ece8a530Spatrick };
393ece8a530Spatrick
Patch843419Section(InputSection * p,uint64_t off)394ece8a530Spatrick Patch843419Section::Patch843419Section(InputSection *p, uint64_t off)
395ece8a530Spatrick : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 4,
396ece8a530Spatrick ".text.patch"),
397ece8a530Spatrick patchee(p), patcheeOffset(off) {
398ece8a530Spatrick this->parent = p->getParent();
399ece8a530Spatrick patchSym = addSyntheticLocal(
400*dfe94b16Srobert saver().save("__CortexA53843419_" + utohexstr(getLDSTAddr())), STT_FUNC,
401*dfe94b16Srobert 0, getSize(), *this);
402*dfe94b16Srobert addSyntheticLocal(saver().save("$x"), STT_NOTYPE, 0, 0, *this);
403ece8a530Spatrick }
404ece8a530Spatrick
getLDSTAddr() const405ece8a530Spatrick uint64_t Patch843419Section::getLDSTAddr() const {
406ece8a530Spatrick return patchee->getVA(patcheeOffset);
407ece8a530Spatrick }
408ece8a530Spatrick
writeTo(uint8_t * buf)409ece8a530Spatrick void Patch843419Section::writeTo(uint8_t *buf) {
410ece8a530Spatrick // Copy the instruction that we will be replacing with a branch in the
411ece8a530Spatrick // patchee Section.
412*dfe94b16Srobert write32le(buf, read32le(patchee->content().begin() + patcheeOffset));
413ece8a530Spatrick
414ece8a530Spatrick // Apply any relocation transferred from the original patchee section.
415*dfe94b16Srobert target->relocateAlloc(*this, buf);
416ece8a530Spatrick
417ece8a530Spatrick // Return address is the next instruction after the one we have just copied.
418ece8a530Spatrick uint64_t s = getLDSTAddr() + 4;
419ece8a530Spatrick uint64_t p = patchSym->getVA() + 4;
420bb684c34Spatrick target->relocateNoSym(buf + 4, R_AARCH64_JUMP26, s - p);
421ece8a530Spatrick }
422ece8a530Spatrick
init()423ece8a530Spatrick void AArch64Err843419Patcher::init() {
424ece8a530Spatrick // The AArch64 ABI permits data in executable sections. We must avoid scanning
425ece8a530Spatrick // this data as if it were instructions to avoid false matches. We use the
426ece8a530Spatrick // mapping symbols in the InputObjects to identify this data, caching the
427ece8a530Spatrick // results in sectionMap so we don't have to recalculate it each pass.
428ece8a530Spatrick
429ece8a530Spatrick // The ABI Section 4.5.4 Mapping symbols; defines local symbols that describe
430ece8a530Spatrick // half open intervals [Symbol Value, Next Symbol Value) of code and data
431ece8a530Spatrick // within sections. If there is no next symbol then the half open interval is
432ece8a530Spatrick // [Symbol Value, End of section). The type, code or data, is determined by
433ece8a530Spatrick // the mapping symbol name, $x for code, $d for data.
434ece8a530Spatrick auto isCodeMapSymbol = [](const Symbol *b) {
435ece8a530Spatrick return b->getName() == "$x" || b->getName().startswith("$x.");
436ece8a530Spatrick };
437ece8a530Spatrick auto isDataMapSymbol = [](const Symbol *b) {
438ece8a530Spatrick return b->getName() == "$d" || b->getName().startswith("$d.");
439ece8a530Spatrick };
440ece8a530Spatrick
441ece8a530Spatrick // Collect mapping symbols for every executable InputSection.
442*dfe94b16Srobert for (ELFFileBase *file : ctx.objectFiles) {
443*dfe94b16Srobert for (Symbol *b : file->getLocalSymbols()) {
444ece8a530Spatrick auto *def = dyn_cast<Defined>(b);
445ece8a530Spatrick if (!def)
446ece8a530Spatrick continue;
447ece8a530Spatrick if (!isCodeMapSymbol(def) && !isDataMapSymbol(def))
448ece8a530Spatrick continue;
449ece8a530Spatrick if (auto *sec = dyn_cast_or_null<InputSection>(def->section))
450ece8a530Spatrick if (sec->flags & SHF_EXECINSTR)
451ece8a530Spatrick sectionMap[sec].push_back(def);
452ece8a530Spatrick }
453ece8a530Spatrick }
454ece8a530Spatrick // For each InputSection make sure the mapping symbols are in sorted in
455ece8a530Spatrick // ascending order and free from consecutive runs of mapping symbols with
456ece8a530Spatrick // the same type. For example we must remove the redundant $d.1 from $x.0
457ece8a530Spatrick // $d.0 $d.1 $x.1.
458ece8a530Spatrick for (auto &kv : sectionMap) {
459ece8a530Spatrick std::vector<const Defined *> &mapSyms = kv.second;
460ece8a530Spatrick llvm::stable_sort(mapSyms, [](const Defined *a, const Defined *b) {
461ece8a530Spatrick return a->value < b->value;
462ece8a530Spatrick });
463ece8a530Spatrick mapSyms.erase(
464ece8a530Spatrick std::unique(mapSyms.begin(), mapSyms.end(),
465ece8a530Spatrick [=](const Defined *a, const Defined *b) {
466ece8a530Spatrick return isCodeMapSymbol(a) == isCodeMapSymbol(b);
467ece8a530Spatrick }),
468ece8a530Spatrick mapSyms.end());
469ece8a530Spatrick // Always start with a Code Mapping Symbol.
470ece8a530Spatrick if (!mapSyms.empty() && !isCodeMapSymbol(mapSyms.front()))
471ece8a530Spatrick mapSyms.erase(mapSyms.begin());
472ece8a530Spatrick }
473ece8a530Spatrick initialized = true;
474ece8a530Spatrick }
475ece8a530Spatrick
476ece8a530Spatrick // Insert the PatchSections we have created back into the
477ece8a530Spatrick // InputSectionDescription. As inserting patches alters the addresses of
478ece8a530Spatrick // InputSections that follow them, we try and place the patches after all the
479ece8a530Spatrick // executable sections, although we may need to insert them earlier if the
480ece8a530Spatrick // InputSectionDescription is larger than the maximum branch range.
insertPatches(InputSectionDescription & isd,std::vector<Patch843419Section * > & patches)481ece8a530Spatrick void AArch64Err843419Patcher::insertPatches(
482ece8a530Spatrick InputSectionDescription &isd, std::vector<Patch843419Section *> &patches) {
483ece8a530Spatrick uint64_t isecLimit;
484ece8a530Spatrick uint64_t prevIsecLimit = isd.sections.front()->outSecOff;
485ece8a530Spatrick uint64_t patchUpperBound = prevIsecLimit + target->getThunkSectionSpacing();
486ece8a530Spatrick uint64_t outSecAddr = isd.sections.front()->getParent()->addr;
487ece8a530Spatrick
488ece8a530Spatrick // Set the outSecOff of patches to the place where we want to insert them.
489ece8a530Spatrick // We use a similar strategy to Thunk placement. Place patches roughly
490ece8a530Spatrick // every multiple of maximum branch range.
491ece8a530Spatrick auto patchIt = patches.begin();
492ece8a530Spatrick auto patchEnd = patches.end();
493ece8a530Spatrick for (const InputSection *isec : isd.sections) {
494ece8a530Spatrick isecLimit = isec->outSecOff + isec->getSize();
495ece8a530Spatrick if (isecLimit > patchUpperBound) {
496ece8a530Spatrick while (patchIt != patchEnd) {
497ece8a530Spatrick if ((*patchIt)->getLDSTAddr() - outSecAddr >= prevIsecLimit)
498ece8a530Spatrick break;
499ece8a530Spatrick (*patchIt)->outSecOff = prevIsecLimit;
500ece8a530Spatrick ++patchIt;
501ece8a530Spatrick }
502ece8a530Spatrick patchUpperBound = prevIsecLimit + target->getThunkSectionSpacing();
503ece8a530Spatrick }
504ece8a530Spatrick prevIsecLimit = isecLimit;
505ece8a530Spatrick }
506ece8a530Spatrick for (; patchIt != patchEnd; ++patchIt) {
507ece8a530Spatrick (*patchIt)->outSecOff = isecLimit;
508ece8a530Spatrick }
509ece8a530Spatrick
510ece8a530Spatrick // Merge all patch sections. We use the outSecOff assigned above to
511ece8a530Spatrick // determine the insertion point. This is ok as we only merge into an
512ece8a530Spatrick // InputSectionDescription once per pass, and at the end of the pass
513ece8a530Spatrick // assignAddresses() will recalculate all the outSecOff values.
514*dfe94b16Srobert SmallVector<InputSection *, 0> tmp;
515ece8a530Spatrick tmp.reserve(isd.sections.size() + patches.size());
516ece8a530Spatrick auto mergeCmp = [](const InputSection *a, const InputSection *b) {
517ece8a530Spatrick if (a->outSecOff != b->outSecOff)
518ece8a530Spatrick return a->outSecOff < b->outSecOff;
519ece8a530Spatrick return isa<Patch843419Section>(a) && !isa<Patch843419Section>(b);
520ece8a530Spatrick };
521ece8a530Spatrick std::merge(isd.sections.begin(), isd.sections.end(), patches.begin(),
522ece8a530Spatrick patches.end(), std::back_inserter(tmp), mergeCmp);
523ece8a530Spatrick isd.sections = std::move(tmp);
524ece8a530Spatrick }
525ece8a530Spatrick
526ece8a530Spatrick // Given an erratum sequence that starts at address adrpAddr, with an
527ece8a530Spatrick // instruction that we need to patch at patcheeOffset from the start of
528ece8a530Spatrick // InputSection isec, create a Patch843419 Section and add it to the
529ece8a530Spatrick // Patches that we need to insert.
implementPatch(uint64_t adrpAddr,uint64_t patcheeOffset,InputSection * isec,std::vector<Patch843419Section * > & patches)530ece8a530Spatrick static void implementPatch(uint64_t adrpAddr, uint64_t patcheeOffset,
531ece8a530Spatrick InputSection *isec,
532ece8a530Spatrick std::vector<Patch843419Section *> &patches) {
533ece8a530Spatrick // There may be a relocation at the same offset that we are patching. There
534ece8a530Spatrick // are four cases that we need to consider.
535ece8a530Spatrick // Case 1: R_AARCH64_JUMP26 branch relocation. We have already patched this
536ece8a530Spatrick // instance of the erratum on a previous patch and altered the relocation. We
537ece8a530Spatrick // have nothing more to do.
538ece8a530Spatrick // Case 2: A TLS Relaxation R_RELAX_TLS_IE_TO_LE. In this case the ADRP that
539ece8a530Spatrick // we read will be transformed into a MOVZ later so we actually don't match
540ece8a530Spatrick // the sequence and have nothing more to do.
541ece8a530Spatrick // Case 3: A load/store register (unsigned immediate) class relocation. There
542ece8a530Spatrick // are two of these R_AARCH_LD64_ABS_LO12_NC and R_AARCH_LD64_GOT_LO12_NC and
543ece8a530Spatrick // they are both absolute. We need to add the same relocation to the patch,
544ece8a530Spatrick // and replace the relocation with a R_AARCH_JUMP26 branch relocation.
545ece8a530Spatrick // Case 4: No relocation. We must create a new R_AARCH64_JUMP26 branch
546ece8a530Spatrick // relocation at the offset.
547*dfe94b16Srobert auto relIt = llvm::find_if(isec->relocs(), [=](const Relocation &r) {
548ece8a530Spatrick return r.offset == patcheeOffset;
549ece8a530Spatrick });
550*dfe94b16Srobert if (relIt != isec->relocs().end() &&
551ece8a530Spatrick (relIt->type == R_AARCH64_JUMP26 || relIt->expr == R_RELAX_TLS_IE_TO_LE))
552ece8a530Spatrick return;
553ece8a530Spatrick
554ece8a530Spatrick log("detected cortex-a53-843419 erratum sequence starting at " +
555ece8a530Spatrick utohexstr(adrpAddr) + " in unpatched output.");
556ece8a530Spatrick
557ece8a530Spatrick auto *ps = make<Patch843419Section>(isec, patcheeOffset);
558ece8a530Spatrick patches.push_back(ps);
559ece8a530Spatrick
560ece8a530Spatrick auto makeRelToPatch = [](uint64_t offset, Symbol *patchSym) {
561ece8a530Spatrick return Relocation{R_PC, R_AARCH64_JUMP26, offset, 0, patchSym};
562ece8a530Spatrick };
563ece8a530Spatrick
564*dfe94b16Srobert if (relIt != isec->relocs().end()) {
565*dfe94b16Srobert ps->addReloc({relIt->expr, relIt->type, 0, relIt->addend, relIt->sym});
566ece8a530Spatrick *relIt = makeRelToPatch(patcheeOffset, ps->patchSym);
567ece8a530Spatrick } else
568*dfe94b16Srobert isec->addReloc(makeRelToPatch(patcheeOffset, ps->patchSym));
569ece8a530Spatrick }
570ece8a530Spatrick
571ece8a530Spatrick // Scan all the instructions in InputSectionDescription, for each instance of
572ece8a530Spatrick // the erratum sequence create a Patch843419Section. We return the list of
573ece8a530Spatrick // Patch843419Sections that need to be applied to the InputSectionDescription.
574ece8a530Spatrick std::vector<Patch843419Section *>
patchInputSectionDescription(InputSectionDescription & isd)575ece8a530Spatrick AArch64Err843419Patcher::patchInputSectionDescription(
576ece8a530Spatrick InputSectionDescription &isd) {
577ece8a530Spatrick std::vector<Patch843419Section *> patches;
578ece8a530Spatrick for (InputSection *isec : isd.sections) {
579ece8a530Spatrick // LLD doesn't use the erratum sequence in SyntheticSections.
580ece8a530Spatrick if (isa<SyntheticSection>(isec))
581ece8a530Spatrick continue;
582ece8a530Spatrick // Use sectionMap to make sure we only scan code and not inline data.
583ece8a530Spatrick // We have already sorted MapSyms in ascending order and removed consecutive
584ece8a530Spatrick // mapping symbols of the same type. Our range of executable instructions to
585ece8a530Spatrick // scan is therefore [codeSym->value, dataSym->value) or [codeSym->value,
586ece8a530Spatrick // section size).
587ece8a530Spatrick std::vector<const Defined *> &mapSyms = sectionMap[isec];
588ece8a530Spatrick
589ece8a530Spatrick auto codeSym = mapSyms.begin();
590ece8a530Spatrick while (codeSym != mapSyms.end()) {
591ece8a530Spatrick auto dataSym = std::next(codeSym);
592ece8a530Spatrick uint64_t off = (*codeSym)->value;
593*dfe94b16Srobert uint64_t limit = (dataSym == mapSyms.end()) ? isec->content().size()
594*dfe94b16Srobert : (*dataSym)->value;
595ece8a530Spatrick
596ece8a530Spatrick while (off < limit) {
597ece8a530Spatrick uint64_t startAddr = isec->getVA(off);
598ece8a530Spatrick if (uint64_t patcheeOffset =
599ece8a530Spatrick scanCortexA53Errata843419(isec, off, limit))
600ece8a530Spatrick implementPatch(startAddr, patcheeOffset, isec, patches);
601ece8a530Spatrick }
602ece8a530Spatrick if (dataSym == mapSyms.end())
603ece8a530Spatrick break;
604ece8a530Spatrick codeSym = std::next(dataSym);
605ece8a530Spatrick }
606ece8a530Spatrick }
607ece8a530Spatrick return patches;
608ece8a530Spatrick }
609ece8a530Spatrick
610ece8a530Spatrick // For each InputSectionDescription make one pass over the executable sections
611ece8a530Spatrick // looking for the erratum sequence; creating a synthetic Patch843419Section
612ece8a530Spatrick // for each instance found. We insert these synthetic patch sections after the
613ece8a530Spatrick // executable code in each InputSectionDescription.
614ece8a530Spatrick //
615ece8a530Spatrick // PreConditions:
616ece8a530Spatrick // The Output and Input Sections have had their final addresses assigned.
617ece8a530Spatrick //
618ece8a530Spatrick // PostConditions:
619ece8a530Spatrick // Returns true if at least one patch was added. The addresses of the
620ece8a530Spatrick // Output and Input Sections may have been changed.
621ece8a530Spatrick // Returns false if no patches were required and no changes were made.
createFixes()622ece8a530Spatrick bool AArch64Err843419Patcher::createFixes() {
623ece8a530Spatrick if (!initialized)
624ece8a530Spatrick init();
625ece8a530Spatrick
626ece8a530Spatrick bool addressesChanged = false;
627ece8a530Spatrick for (OutputSection *os : outputSections) {
628ece8a530Spatrick if (!(os->flags & SHF_ALLOC) || !(os->flags & SHF_EXECINSTR))
629ece8a530Spatrick continue;
630*dfe94b16Srobert for (SectionCommand *cmd : os->commands)
631*dfe94b16Srobert if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
632ece8a530Spatrick std::vector<Patch843419Section *> patches =
633ece8a530Spatrick patchInputSectionDescription(*isd);
634ece8a530Spatrick if (!patches.empty()) {
635ece8a530Spatrick insertPatches(*isd, patches);
636ece8a530Spatrick addressesChanged = true;
637ece8a530Spatrick }
638ece8a530Spatrick }
639ece8a530Spatrick }
640ece8a530Spatrick return addressesChanged;
641ece8a530Spatrick }
642