1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "linker/arm64/relative_patcher_arm64.h"
18
19 #include "arch/arm64/instruction_set_features_arm64.h"
20 #include "art_method.h"
21 #include "compiled_method.h"
22 #include "driver/compiler_driver.h"
23 #include "linker/output_stream.h"
24 #include "oat.h"
25 #include "oat_quick_method_header.h"
26 #include "utils/arm64/assembler_arm64.h"
27
28 namespace art {
29 namespace linker {
30
31 namespace {
32
IsAdrpPatch(const LinkerPatch & patch)33 inline bool IsAdrpPatch(const LinkerPatch& patch) {
34 LinkerPatch::Type type = patch.GetType();
35 return
36 (type == LinkerPatch::Type::kStringRelative || type == LinkerPatch::Type::kDexCacheArray) &&
37 patch.LiteralOffset() == patch.PcInsnOffset();
38 }
39
40 } // anonymous namespace
41
Arm64RelativePatcher(RelativePatcherTargetProvider * provider,const Arm64InstructionSetFeatures * features)42 Arm64RelativePatcher::Arm64RelativePatcher(RelativePatcherTargetProvider* provider,
43 const Arm64InstructionSetFeatures* features)
44 : ArmBaseRelativePatcher(provider, kArm64, CompileThunkCode(),
45 kMaxPositiveDisplacement, kMaxNegativeDisplacement),
46 fix_cortex_a53_843419_(features->NeedFixCortexA53_843419()),
47 reserved_adrp_thunks_(0u),
48 processed_adrp_thunks_(0u) {
49 if (fix_cortex_a53_843419_) {
50 adrp_thunk_locations_.reserve(16u);
51 current_method_thunks_.reserve(16u * kAdrpThunkSize);
52 }
53 }
54
ReserveSpace(uint32_t offset,const CompiledMethod * compiled_method,MethodReference method_ref)55 uint32_t Arm64RelativePatcher::ReserveSpace(uint32_t offset,
56 const CompiledMethod* compiled_method,
57 MethodReference method_ref) {
58 if (!fix_cortex_a53_843419_) {
59 DCHECK(adrp_thunk_locations_.empty());
60 return ReserveSpaceInternal(offset, compiled_method, method_ref, 0u);
61 }
62
63 // Add thunks for previous method if any.
64 if (reserved_adrp_thunks_ != adrp_thunk_locations_.size()) {
65 size_t num_adrp_thunks = adrp_thunk_locations_.size() - reserved_adrp_thunks_;
66 offset = CompiledMethod::AlignCode(offset, kArm64) + kAdrpThunkSize * num_adrp_thunks;
67 reserved_adrp_thunks_ = adrp_thunk_locations_.size();
68 }
69
70 // Count the number of ADRP insns as the upper bound on the number of thunks needed
71 // and use it to reserve space for other linker patches.
72 size_t num_adrp = 0u;
73 DCHECK(compiled_method != nullptr);
74 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
75 if (IsAdrpPatch(patch)) {
76 ++num_adrp;
77 }
78 }
79 offset = ReserveSpaceInternal(offset, compiled_method, method_ref, kAdrpThunkSize * num_adrp);
80 if (num_adrp == 0u) {
81 return offset;
82 }
83
84 // Now that we have the actual offset where the code will be placed, locate the ADRP insns
85 // that actually require the thunk.
86 uint32_t quick_code_offset = compiled_method->AlignCode(offset) + sizeof(OatQuickMethodHeader);
87 ArrayRef<const uint8_t> code = compiled_method->GetQuickCode();
88 uint32_t thunk_offset = compiled_method->AlignCode(quick_code_offset + code.size());
89 DCHECK(compiled_method != nullptr);
90 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
91 if (IsAdrpPatch(patch)) {
92 uint32_t patch_offset = quick_code_offset + patch.LiteralOffset();
93 if (NeedsErratum843419Thunk(code, patch.LiteralOffset(), patch_offset)) {
94 adrp_thunk_locations_.emplace_back(patch_offset, thunk_offset);
95 thunk_offset += kAdrpThunkSize;
96 }
97 }
98 }
99 return offset;
100 }
101
ReserveSpaceEnd(uint32_t offset)102 uint32_t Arm64RelativePatcher::ReserveSpaceEnd(uint32_t offset) {
103 if (!fix_cortex_a53_843419_) {
104 DCHECK(adrp_thunk_locations_.empty());
105 } else {
106 // Add thunks for the last method if any.
107 if (reserved_adrp_thunks_ != adrp_thunk_locations_.size()) {
108 size_t num_adrp_thunks = adrp_thunk_locations_.size() - reserved_adrp_thunks_;
109 offset = CompiledMethod::AlignCode(offset, kArm64) + kAdrpThunkSize * num_adrp_thunks;
110 reserved_adrp_thunks_ = adrp_thunk_locations_.size();
111 }
112 }
113 return ArmBaseRelativePatcher::ReserveSpaceEnd(offset);
114 }
115
WriteThunks(OutputStream * out,uint32_t offset)116 uint32_t Arm64RelativePatcher::WriteThunks(OutputStream* out, uint32_t offset) {
117 if (fix_cortex_a53_843419_) {
118 if (!current_method_thunks_.empty()) {
119 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, kArm64);
120 if (kIsDebugBuild) {
121 CHECK_ALIGNED(current_method_thunks_.size(), kAdrpThunkSize);
122 size_t num_thunks = current_method_thunks_.size() / kAdrpThunkSize;
123 CHECK_LE(num_thunks, processed_adrp_thunks_);
124 for (size_t i = 0u; i != num_thunks; ++i) {
125 const auto& entry = adrp_thunk_locations_[processed_adrp_thunks_ - num_thunks + i];
126 CHECK_EQ(entry.second, aligned_offset + i * kAdrpThunkSize);
127 }
128 }
129 uint32_t aligned_code_delta = aligned_offset - offset;
130 if (aligned_code_delta != 0u && !WriteCodeAlignment(out, aligned_code_delta)) {
131 return 0u;
132 }
133 if (!WriteMiscThunk(out, ArrayRef<const uint8_t>(current_method_thunks_))) {
134 return 0u;
135 }
136 offset = aligned_offset + current_method_thunks_.size();
137 current_method_thunks_.clear();
138 }
139 }
140 return ArmBaseRelativePatcher::WriteThunks(out, offset);
141 }
142
PatchCall(std::vector<uint8_t> * code,uint32_t literal_offset,uint32_t patch_offset,uint32_t target_offset)143 void Arm64RelativePatcher::PatchCall(std::vector<uint8_t>* code,
144 uint32_t literal_offset,
145 uint32_t patch_offset, uint32_t
146 target_offset) {
147 DCHECK_LE(literal_offset + 4u, code->size());
148 DCHECK_EQ(literal_offset & 3u, 0u);
149 DCHECK_EQ(patch_offset & 3u, 0u);
150 DCHECK_EQ(target_offset & 3u, 0u);
151 uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u);
152 DCHECK_EQ(displacement & 3u, 0u);
153 DCHECK((displacement >> 27) == 0u || (displacement >> 27) == 31u); // 28-bit signed.
154 uint32_t insn = (displacement & 0x0fffffffu) >> 2;
155 insn |= 0x94000000; // BL
156
157 // Check that we're just overwriting an existing BL.
158 DCHECK_EQ(GetInsn(code, literal_offset) & 0xfc000000u, 0x94000000u);
159 // Write the new BL.
160 SetInsn(code, literal_offset, insn);
161 }
162
PatchPcRelativeReference(std::vector<uint8_t> * code,const LinkerPatch & patch,uint32_t patch_offset,uint32_t target_offset)163 void Arm64RelativePatcher::PatchPcRelativeReference(std::vector<uint8_t>* code,
164 const LinkerPatch& patch,
165 uint32_t patch_offset,
166 uint32_t target_offset) {
167 DCHECK_EQ(patch_offset & 3u, 0u);
168 DCHECK_EQ(target_offset & 3u, 0u);
169 uint32_t literal_offset = patch.LiteralOffset();
170 uint32_t insn = GetInsn(code, literal_offset);
171 uint32_t pc_insn_offset = patch.PcInsnOffset();
172 uint32_t disp = target_offset - ((patch_offset - literal_offset + pc_insn_offset) & ~0xfffu);
173 bool wide = (insn & 0x40000000) != 0;
174 uint32_t shift = wide ? 3u : 2u;
175 if (literal_offset == pc_insn_offset) {
176 // Check it's an ADRP with imm == 0 (unset).
177 DCHECK_EQ((insn & 0xffffffe0u), 0x90000000u)
178 << literal_offset << ", " << pc_insn_offset << ", 0x" << std::hex << insn;
179 if (fix_cortex_a53_843419_ && processed_adrp_thunks_ != adrp_thunk_locations_.size() &&
180 adrp_thunk_locations_[processed_adrp_thunks_].first == patch_offset) {
181 DCHECK(NeedsErratum843419Thunk(ArrayRef<const uint8_t>(*code),
182 literal_offset, patch_offset));
183 uint32_t thunk_offset = adrp_thunk_locations_[processed_adrp_thunks_].second;
184 uint32_t adrp_disp = target_offset - (thunk_offset & ~0xfffu);
185 uint32_t adrp = PatchAdrp(insn, adrp_disp);
186
187 uint32_t out_disp = thunk_offset - patch_offset;
188 DCHECK_EQ(out_disp & 3u, 0u);
189 DCHECK((out_disp >> 27) == 0u || (out_disp >> 27) == 31u); // 28-bit signed.
190 insn = (out_disp & 0x0fffffffu) >> shift;
191 insn |= 0x14000000; // B <thunk>
192
193 uint32_t back_disp = -out_disp;
194 DCHECK_EQ(back_disp & 3u, 0u);
195 DCHECK((back_disp >> 27) == 0u || (back_disp >> 27) == 31u); // 28-bit signed.
196 uint32_t b_back = (back_disp & 0x0fffffffu) >> 2;
197 b_back |= 0x14000000; // B <back>
198 size_t thunks_code_offset = current_method_thunks_.size();
199 current_method_thunks_.resize(thunks_code_offset + kAdrpThunkSize);
200 SetInsn(¤t_method_thunks_, thunks_code_offset, adrp);
201 SetInsn(¤t_method_thunks_, thunks_code_offset + 4u, b_back);
202 static_assert(kAdrpThunkSize == 2 * 4u, "thunk has 2 instructions");
203
204 processed_adrp_thunks_ += 1u;
205 } else {
206 insn = PatchAdrp(insn, disp);
207 }
208 // Write the new ADRP (or B to the erratum 843419 thunk).
209 SetInsn(code, literal_offset, insn);
210 } else {
211 if ((insn & 0xfffffc00) == 0x91000000) {
212 // ADD immediate, 64-bit with imm12 == 0 (unset).
213 DCHECK(patch.GetType() == LinkerPatch::Type::kStringRelative) << patch.GetType();
214 shift = 0u; // No shift for ADD.
215 } else {
216 // LDR 32-bit or 64-bit with imm12 == 0 (unset).
217 DCHECK(patch.GetType() == LinkerPatch::Type::kDexCacheArray) << patch.GetType();
218 DCHECK_EQ(insn & 0xbffffc00, 0xb9400000) << std::hex << insn;
219 }
220 if (kIsDebugBuild) {
221 uint32_t adrp = GetInsn(code, pc_insn_offset);
222 if ((adrp & 0x9f000000u) != 0x90000000u) {
223 CHECK(fix_cortex_a53_843419_);
224 CHECK_EQ(adrp & 0xfc000000u, 0x14000000u); // B <thunk>
225 CHECK_ALIGNED(current_method_thunks_.size(), kAdrpThunkSize);
226 size_t num_thunks = current_method_thunks_.size() / kAdrpThunkSize;
227 CHECK_LE(num_thunks, processed_adrp_thunks_);
228 uint32_t b_offset = patch_offset - literal_offset + pc_insn_offset;
229 for (size_t i = processed_adrp_thunks_ - num_thunks; ; ++i) {
230 CHECK_NE(i, processed_adrp_thunks_);
231 if (adrp_thunk_locations_[i].first == b_offset) {
232 size_t idx = num_thunks - (processed_adrp_thunks_ - i);
233 adrp = GetInsn(¤t_method_thunks_, idx * kAdrpThunkSize);
234 break;
235 }
236 }
237 }
238 CHECK_EQ(adrp & 0x9f00001fu, // Check that pc_insn_offset points
239 0x90000000 | ((insn >> 5) & 0x1fu)); // to ADRP with matching register.
240 }
241 uint32_t imm12 = (disp & 0xfffu) >> shift;
242 insn = (insn & ~(0xfffu << 10)) | (imm12 << 10);
243 SetInsn(code, literal_offset, insn);
244 }
245 }
246
CompileThunkCode()247 std::vector<uint8_t> Arm64RelativePatcher::CompileThunkCode() {
248 // The thunk just uses the entry point in the ArtMethod. This works even for calls
249 // to the generic JNI and interpreter trampolines.
250 ArenaPool pool;
251 ArenaAllocator arena(&pool);
252 arm64::Arm64Assembler assembler(&arena);
253 Offset offset(ArtMethod::EntryPointFromQuickCompiledCodeOffset(
254 kArm64PointerSize).Int32Value());
255 assembler.JumpTo(ManagedRegister(arm64::X0), offset, ManagedRegister(arm64::IP0));
256 // Ensure we emit the literal pool.
257 assembler.FinalizeCode();
258 std::vector<uint8_t> thunk_code(assembler.CodeSize());
259 MemoryRegion code(thunk_code.data(), thunk_code.size());
260 assembler.FinalizeInstructions(code);
261 return thunk_code;
262 }
263
PatchAdrp(uint32_t adrp,uint32_t disp)264 uint32_t Arm64RelativePatcher::PatchAdrp(uint32_t adrp, uint32_t disp) {
265 return (adrp & 0x9f00001fu) | // Clear offset bits, keep ADRP with destination reg.
266 // Bottom 12 bits are ignored, the next 2 lowest bits are encoded in bits 29-30.
267 ((disp & 0x00003000u) << (29 - 12)) |
268 // The next 16 bits are encoded in bits 5-22.
269 ((disp & 0xffffc000u) >> (12 + 2 - 5)) |
270 // Since the target_offset is based on the beginning of the oat file and the
271 // image space precedes the oat file, the target_offset into image space will
272 // be negative yet passed as uint32_t. Therefore we limit the displacement
273 // to +-2GiB (rather than the maximim +-4GiB) and determine the sign bit from
274 // the highest bit of the displacement. This is encoded in bit 23.
275 ((disp & 0x80000000u) >> (31 - 23));
276 }
277
NeedsErratum843419Thunk(ArrayRef<const uint8_t> code,uint32_t literal_offset,uint32_t patch_offset)278 bool Arm64RelativePatcher::NeedsErratum843419Thunk(ArrayRef<const uint8_t> code,
279 uint32_t literal_offset,
280 uint32_t patch_offset) {
281 DCHECK_EQ(patch_offset & 0x3u, 0u);
282 if ((patch_offset & 0xff8) == 0xff8) { // ...ff8 or ...ffc
283 uint32_t adrp = GetInsn(code, literal_offset);
284 DCHECK_EQ(adrp & 0x9f000000, 0x90000000);
285 uint32_t next_offset = patch_offset + 4u;
286 uint32_t next_insn = GetInsn(code, literal_offset + 4u);
287
288 // Below we avoid patching sequences where the adrp is followed by a load which can easily
289 // be proved to be aligned.
290
291 // First check if the next insn is the LDR using the result of the ADRP.
292 // LDR <Wt>, [<Xn>, #pimm], where <Xn> == ADRP destination reg.
293 if ((next_insn & 0xffc00000) == 0xb9400000 &&
294 (((next_insn >> 5) ^ adrp) & 0x1f) == 0) {
295 return false;
296 }
297
298 // And since LinkerPatch::Type::kStringRelative is using the result of the ADRP
299 // for an ADD immediate, check for that as well. We generalize a bit to include
300 // ADD/ADDS/SUB/SUBS immediate that either uses the ADRP destination or stores
301 // the result to a different register.
302 if ((next_insn & 0x1f000000) == 0x11000000 &&
303 ((((next_insn >> 5) ^ adrp) & 0x1f) == 0 || ((next_insn ^ adrp) & 0x1f) != 0)) {
304 return false;
305 }
306
307 // LDR <Wt>, <label> is always aligned and thus it doesn't cause boundary crossing.
308 if ((next_insn & 0xff000000) == 0x18000000) {
309 return false;
310 }
311
312 // LDR <Xt>, <label> is aligned iff the pc + displacement is a multiple of 8.
313 if ((next_insn & 0xff000000) == 0x58000000) {
314 bool is_aligned_load = (((next_offset >> 2) ^ (next_insn >> 5)) & 1) == 0;
315 return !is_aligned_load;
316 }
317
318 // LDR <Wt>, [SP, #<pimm>] and LDR <Xt>, [SP, #<pimm>] are always aligned loads, as SP is
319 // guaranteed to be 128-bits aligned and <pimm> is multiple of the load size.
320 if ((next_insn & 0xbfc003e0) == 0xb94003e0) {
321 return false;
322 }
323 return true;
324 }
325 return false;
326 }
327
SetInsn(std::vector<uint8_t> * code,uint32_t offset,uint32_t value)328 void Arm64RelativePatcher::SetInsn(std::vector<uint8_t>* code, uint32_t offset, uint32_t value) {
329 DCHECK_LE(offset + 4u, code->size());
330 DCHECK_EQ(offset & 3u, 0u);
331 uint8_t* addr = &(*code)[offset];
332 addr[0] = (value >> 0) & 0xff;
333 addr[1] = (value >> 8) & 0xff;
334 addr[2] = (value >> 16) & 0xff;
335 addr[3] = (value >> 24) & 0xff;
336 }
337
GetInsn(ArrayRef<const uint8_t> code,uint32_t offset)338 uint32_t Arm64RelativePatcher::GetInsn(ArrayRef<const uint8_t> code, uint32_t offset) {
339 DCHECK_LE(offset + 4u, code.size());
340 DCHECK_EQ(offset & 3u, 0u);
341 const uint8_t* addr = &code[offset];
342 return
343 (static_cast<uint32_t>(addr[0]) << 0) +
344 (static_cast<uint32_t>(addr[1]) << 8) +
345 (static_cast<uint32_t>(addr[2]) << 16)+
346 (static_cast<uint32_t>(addr[3]) << 24);
347 }
348
349 template <typename Alloc>
GetInsn(std::vector<uint8_t,Alloc> * code,uint32_t offset)350 uint32_t Arm64RelativePatcher::GetInsn(std::vector<uint8_t, Alloc>* code, uint32_t offset) {
351 return GetInsn(ArrayRef<const uint8_t>(*code), offset);
352 }
353
354 } // namespace linker
355 } // namespace art
356