Debian Codegraph @

dex2oat/linker/arm/relative_patcher_thumb2_test.cc

raw symbols SCIP
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/arm/relative_patcher_thumb2.h"
18
19 #include "arch/arm/instruction_set_features_arm.h"
20 #include "base/casts.h"
21 #include "driver/compiler_options.h"
22 #include "linker/relative_patcher_test.h"
23 #include "lock_word.h"
24 #include "mirror/array-inl.h"
25 #include "mirror/object.h"
26 #include "oat_quick_method_header.h"
27 #include "optimizing/code_generator_arm_vixl.h"
28 #include "optimizing/optimizing_unit_test.h"
29
30 namespace art {
31 namespace linker {
32
33 class Thumb2RelativePatcherTest : public RelativePatcherTest {
34 public:
35 Thumb2RelativePatcherTest() : RelativePatcherTest(InstructionSet::kThumb2, "default") { }
36
37 protected:
38 static const uint8_t kCallRawCode[];
39 static const ArrayRef<const uint8_t> kCallCode;
40 static const uint8_t kNopRawCode[];
41 static const ArrayRef<const uint8_t> kNopCode;
42 static const uint8_t kUnpatchedPcRelativeRawCode[];
43 static const ArrayRef<const uint8_t> kUnpatchedPcRelativeCode;
44 static const uint32_t kPcInsnOffset;
45
46 // The PC in Thumb mode is 4 bytes after the instruction location.
47 static constexpr uint32_t kPcAdjustment = 4u;
48
49 // Branches within range [-256, 256) can be created from these by adding the low 8 bits.
50 static constexpr uint32_t kBlPlus0 = 0xf000f800u;
51 static constexpr uint32_t kBlMinus256 = 0xf7ffff00u;
52
53 // Special BL values.
54 static constexpr uint32_t kBlPlusMax = 0xf3ffd7ffu;
55 static constexpr uint32_t kBlMinusMax = 0xf400d000u;
56
57 // BNE +0, 32-bit, encoding T3. Bits 0-10, 11, 13, 16-21, 26 are placeholder for target offset.
58 static constexpr uint32_t kBneWPlus0 = 0xf0408000u;
59
60 // LDR immediate, 16-bit, encoding T1. Bits 6-10 are imm5, 0-2 are Rt, 3-5 are Rn.
61 static constexpr uint32_t kLdrInsn = 0x6800u;
62
63 // LDR immediate, 32-bit, encoding T3. Bits 0-11 are offset, 12-15 are Rt, 16-20 are Rn.
64 static constexpr uint32_t kLdrWInsn = 0xf8d00000u;
65
66 // LDR immediate, negative offset, encoding T4. Bits 0-7 are the offset to subtract.
67 static constexpr uint32_t kLdrNegativeOffset = 0xf8500c00u;
68
69 // LDR register, lsl #2. Bits 4-5 are the imm2, i.e. the lsl shift.
70 static constexpr uint32_t kLdrRegLsl2 = 0xf8500020u;
71
72 // NOP instructions.
73 static constexpr uint32_t kNopInsn = 0xbf00u;
74 static constexpr uint32_t kNopWInsn = 0xf3af8000u;
75
76 void InsertInsn(std::vector<uint8_t>* code, size_t pos, uint32_t insn) {
77 CHECK_LE(pos, code->size());
78 if (IsUint<16>(insn)) {
79 const uint8_t insn_code[] = {
80 static_cast<uint8_t>(insn),
81 static_cast<uint8_t>(insn >> 8),
82 };
83 static_assert(sizeof(insn_code) == 2u, "Invalid sizeof(insn_code).");
84 code->insert(code->begin() + pos, insn_code, insn_code + sizeof(insn_code));
85 } else {
86 const uint8_t insn_code[] = {
87 static_cast<uint8_t>(insn >> 16),
88 static_cast<uint8_t>(insn >> 24),
89 static_cast<uint8_t>(insn),
90 static_cast<uint8_t>(insn >> 8),
91 };
92 static_assert(sizeof(insn_code) == 4u, "Invalid sizeof(insn_code).");
93 code->insert(code->begin() + pos, insn_code, insn_code + sizeof(insn_code));
94 }
95 }
96
97 void PushBackInsn(std::vector<uint8_t>* code, uint32_t insn) {
98 InsertInsn(code, code->size(), insn);
99 }
100
101 std::vector<uint8_t> GenNops(size_t num_nops) {
102 std::vector<uint8_t> result;
103 result.reserve(num_nops * 2u);
104 for (size_t i = 0; i != num_nops; ++i) {
105 PushBackInsn(&result, kNopInsn);
106 }
107 return result;
108 }
109
110 std::vector<uint8_t> RawCode(std::initializer_list<uint32_t> insns) {
111 std::vector<uint8_t> raw_code;
112 size_t number_of_16_bit_insns =
113 std::count_if(insns.begin(), insns.end(), [](uint32_t x) { return IsUint<16>(x); });
114 raw_code.reserve(insns.size() * 4u - number_of_16_bit_insns * 2u);
115 for (uint32_t insn : insns) {
116 PushBackInsn(&raw_code, insn);
117 }
118 return raw_code;
119 }
120
121 uint32_t BneWWithOffset(uint32_t bne_offset, uint32_t target_offset) {
122 if (!IsAligned<2u>(bne_offset)) {
123 LOG(ERROR) << "Unaligned bne_offset: " << bne_offset;
124 return 0xffffffffu; // Fails code diff later.
125 }
126 if (!IsAligned<2u>(target_offset)) {
127 LOG(ERROR) << "Unaligned target_offset: " << target_offset;
128 return 0xffffffffu; // Fails code diff later.
129 }
130 uint32_t diff = target_offset - bne_offset - kPcAdjustment;
131 DCHECK_ALIGNED(diff, 2u);
132 if ((diff >> 20) != 0 && (diff >> 20) != 0xfffu) {
133 LOG(ERROR) << "Target out of range: " << diff;
134 return 0xffffffffu; // Fails code diff later.
135 }
136 return kBneWPlus0 | ((diff >> 1) & 0x7ffu) // imm11
137 | (((diff >> 12) & 0x3fu) << 16) // imm6
138 | (((diff >> 18) & 1) << 13) // J1
139 | (((diff >> 19) & 1) << 11) // J2
140 | (((diff >> 20) & 1) << 26); // S
141 }
142
143 uint32_t Create2MethodsWithGap(const ArrayRef<const uint8_t>& method1_code,
144 const ArrayRef<const LinkerPatch>& method1_patches,
145 const ArrayRef<const uint8_t>& last_method_code,
146 const ArrayRef<const LinkerPatch>& last_method_patches,
147 uint32_t distance_without_thunks) {
148 CHECK_EQ(distance_without_thunks % kArmCodeAlignment, 0u);
149 uint32_t method1_offset =
150 kTrampolineSize + CodeAlignmentSize(kTrampolineSize) + sizeof(OatQuickMethodHeader);
151 AddCompiledMethod(MethodRef(1u), method1_code, method1_patches);
152 const uint32_t gap_start = method1_offset + method1_code.size();
153
154 // We want to put the last method at a very precise offset.
155 const uint32_t last_method_offset = method1_offset + distance_without_thunks;
156 CHECK_ALIGNED(last_method_offset, kArmCodeAlignment);
157 const uint32_t gap_end = last_method_offset - sizeof(OatQuickMethodHeader);
158
159 // Fill the gap with intermediate methods in chunks of 2MiB and the first in [2MiB, 4MiB).
160 // (This allows deduplicating the small chunks to avoid using 32MiB of memory for +-16MiB
161 // offsets by this test. Making the first chunk bigger makes it easy to give all intermediate
162 // methods the same alignment of the end, so the thunk insertion adds a predictable size as
163 // long as it's after the first chunk.)
164 uint32_t method_idx = 2u;
165 constexpr uint32_t kSmallChunkSize = 2 * MB;
166 std::vector<uint8_t> gap_code;
167 uint32_t gap_size = gap_end - gap_start;
168 uint32_t num_small_chunks = std::max(gap_size / kSmallChunkSize, 1u) - 1u;
169 uint32_t chunk_start = gap_start;
170 uint32_t chunk_size = gap_size - num_small_chunks * kSmallChunkSize;
171 for (uint32_t i = 0; i <= num_small_chunks; ++i) { // num_small_chunks+1 iterations.
172 uint32_t chunk_code_size =
173 chunk_size - CodeAlignmentSize(chunk_start) - sizeof(OatQuickMethodHeader);
174 gap_code.resize(chunk_code_size, 0u);
175 AddCompiledMethod(MethodRef(method_idx), ArrayRef<const uint8_t>(gap_code));
176 method_idx += 1u;
177 chunk_start += chunk_size;
178 chunk_size = kSmallChunkSize; // For all but the first chunk.
179 DCHECK_EQ(CodeAlignmentSize(gap_end), CodeAlignmentSize(chunk_start));
180 }
181
182 // Add the last method and link
183 AddCompiledMethod(MethodRef(method_idx), last_method_code, last_method_patches);
184 Link();
185
186 // Check assumptions.
187 CHECK_EQ(GetMethodOffset(1), method1_offset);
188 auto last_result = method_offset_map_.FindMethodOffset(MethodRef(method_idx));
189 CHECK(last_result.first);
190 // There may be a thunk before method2.
191 if (last_result.second != last_method_offset + 1 /* thumb mode */) {
192 // Thunk present. Check that there's only one.
193 uint32_t thunk_end =
194 CompiledCode::AlignCode(gap_end, InstructionSet::kThumb2) + MethodCallThunkSize();
195 uint32_t header_offset = thunk_end + CodeAlignmentSize(thunk_end);
196 CHECK_EQ(last_result.second,
197 header_offset + sizeof(OatQuickMethodHeader) + 1 /* thumb mode */);
198 }
199 return method_idx;
200 }
201
202 uint32_t GetMethodOffset(uint32_t method_idx) {
203 auto result = method_offset_map_.FindMethodOffset(MethodRef(method_idx));
204 CHECK(result.first);
205 CHECK_NE(result.second & 1u, 0u);
206 return result.second - 1 /* thumb mode */;
207 }
208
209 std::vector<uint8_t> CompileThunk(const LinkerPatch& patch,
210 /*out*/ std::string* debug_name = nullptr) {
211 OptimizingUnitTestHelper helper;
212 HGraph* graph = helper.CreateGraph();
213 CompilerOptions compiler_options;
214 arm::CodeGeneratorARMVIXL codegen(graph, compiler_options);
215 ArenaVector<uint8_t> code(helper.GetAllocator()->Adapter());
216 codegen.EmitThunkCode(patch, &code, debug_name);
217 return std::vector<uint8_t>(code.begin(), code.end());
218 }
219
220 void AddCompiledMethod(
221 MethodReference method_ref,
222 const ArrayRef<const uint8_t>& code,
223 const ArrayRef<const LinkerPatch>& patches = ArrayRef<const LinkerPatch>()) {
224 RelativePatcherTest::AddCompiledMethod(method_ref, code, patches);
225
226 // Make sure the ThunkProvider has all the necessary thunks.
227 for (const LinkerPatch& patch : patches) {
228 if (patch.GetType() == LinkerPatch::Type::kCallEntrypoint ||
229 patch.GetType() == LinkerPatch::Type::kBakerReadBarrierBranch ||
230 patch.GetType() == LinkerPatch::Type::kCallRelative) {
231 std::string debug_name;
232 std::vector<uint8_t> thunk_code = CompileThunk(patch, &debug_name);
233 thunk_provider_.SetThunkCode(patch, ArrayRef<const uint8_t>(thunk_code), debug_name);
234 }
235 }
236 }
237
238 std::vector<uint8_t> CompileMethodCallThunk() {
239 LinkerPatch patch = LinkerPatch::RelativeCodePatch(/* literal_offset */ 0u,
240 /* target_dex_file*/ nullptr,
241 /* target_method_idx */ 0u);
242 return CompileThunk(patch);
243 }
244
245 uint32_t MethodCallThunkSize() {
246 return CompileMethodCallThunk().size();
247 }
248
249 bool CheckThunk(uint32_t thunk_offset) {
250 const std::vector<uint8_t> expected_code = CompileMethodCallThunk();
251 if (output_.size() < thunk_offset + expected_code.size()) {
252 LOG(ERROR) << "output_.size() == " << output_.size() << " < "
253 << "thunk_offset + expected_code.size() == " << (thunk_offset + expected_code.size());
254 return false;
255 }
256 ArrayRef<const uint8_t> linked_code(&output_[thunk_offset], expected_code.size());
257 if (linked_code == ArrayRef<const uint8_t>(expected_code)) {
258 return true;
259 }
260 // Log failure info.
261 DumpDiff(ArrayRef<const uint8_t>(expected_code), linked_code);
262 return false;
263 }
264
265 std::vector<uint8_t> GenNopsAndBl(size_t num_nops, uint32_t bl) {
266 std::vector<uint8_t> result;
267 result.reserve(num_nops * 2u + 4u);
268 for (size_t i = 0; i != num_nops; ++i) {
269 PushBackInsn(&result, kNopInsn);
270 }
271 PushBackInsn(&result, bl);
272 return result;
273 }
274
275 void TestStringBssEntry(uint32_t bss_begin, uint32_t string_entry_offset);
276 void TestStringReference(uint32_t string_offset);
277 void CheckPcRelativePatch(const ArrayRef<const LinkerPatch>& patches, uint32_t target_offset);
278
279 static uint32_t EncodeBakerReadBarrierFieldData(uint32_t base_reg,
280 uint32_t holder_reg,
281 bool narrow) {
282 return arm::CodeGeneratorARMVIXL::EncodeBakerReadBarrierFieldData(base_reg, holder_reg, narrow);
283 }
284
285 static uint32_t EncodeBakerReadBarrierArrayData(uint32_t base_reg) {
286 return arm::CodeGeneratorARMVIXL::EncodeBakerReadBarrierArrayData(base_reg);
287 }
288
289 static uint32_t EncodeBakerReadBarrierGcRootData(uint32_t root_reg, bool narrow) {
290 return arm::CodeGeneratorARMVIXL::EncodeBakerReadBarrierGcRootData(root_reg, narrow);
291 }
292
293 std::vector<uint8_t> CompileBakerOffsetThunk(uint32_t base_reg,
294 uint32_t holder_reg,
295 bool narrow) {
296 const LinkerPatch patch = LinkerPatch::BakerReadBarrierBranchPatch(
297 /* literal_offset */ 0u, EncodeBakerReadBarrierFieldData(base_reg, holder_reg, narrow));
298 return CompileThunk(patch);
299 }
300
301 std::vector<uint8_t> CompileBakerArrayThunk(uint32_t base_reg) {
302 LinkerPatch patch = LinkerPatch::BakerReadBarrierBranchPatch(
303 /* literal_offset */ 0u, EncodeBakerReadBarrierArrayData(base_reg));
304 return CompileThunk(patch);
305 }
306
307 std::vector<uint8_t> CompileBakerGcRootThunk(uint32_t root_reg, bool narrow) {
308 LinkerPatch patch = LinkerPatch::BakerReadBarrierBranchPatch(
309 /* literal_offset */ 0u, EncodeBakerReadBarrierGcRootData(root_reg, narrow));
310 return CompileThunk(patch);
311 }
312
313 uint32_t GetOutputInsn32(uint32_t offset) {
314 CHECK_LE(offset, output_.size());
315 CHECK_GE(output_.size() - offset, 4u);
316 return (static_cast<uint32_t>(output_[offset]) << 16) |
317 (static_cast<uint32_t>(output_[offset + 1]) << 24) |
318 (static_cast<uint32_t>(output_[offset + 2]) << 0) |
319 (static_cast<uint32_t>(output_[offset + 3]) << 8);
320 }
321
322 uint16_t GetOutputInsn16(uint32_t offset) {
323 CHECK_LE(offset, output_.size());
324 CHECK_GE(output_.size() - offset, 2u);
325 return (static_cast<uint32_t>(output_[offset]) << 0) |
326 (static_cast<uint32_t>(output_[offset + 1]) << 8);
327 }
328
329 void TestBakerFieldWide(uint32_t offset, uint32_t ref_reg);
330 void TestBakerFieldNarrow(uint32_t offset, uint32_t ref_reg);
331 };
332
333 const uint8_t Thumb2RelativePatcherTest::kCallRawCode[] = {
334 0x00, 0xf0, 0x00, 0xf8
335 };
336
337 const ArrayRef<const uint8_t> Thumb2RelativePatcherTest::kCallCode(kCallRawCode);
338
339 const uint8_t Thumb2RelativePatcherTest::kNopRawCode[] = {
340 0x00, 0xbf
341 };
342
343 const ArrayRef<const uint8_t> Thumb2RelativePatcherTest::kNopCode(kNopRawCode);
344
345 const uint8_t Thumb2RelativePatcherTest::kUnpatchedPcRelativeRawCode[] = {
346 0x40, 0xf2, 0x00, 0x00, // MOVW r0, #0 (placeholder)
347 0xc0, 0xf2, 0x00, 0x00, // MOVT r0, #0 (placeholder)
348 0x78, 0x44, // ADD r0, pc
349 };
350 const ArrayRef<const uint8_t> Thumb2RelativePatcherTest::kUnpatchedPcRelativeCode(
351 kUnpatchedPcRelativeRawCode);
352 const uint32_t Thumb2RelativePatcherTest::kPcInsnOffset = 8u;
353
354 void Thumb2RelativePatcherTest::TestStringBssEntry(uint32_t bss_begin,
355 uint32_t string_entry_offset) {
356 constexpr uint32_t kStringIndex = 1u;
357 string_index_to_offset_map_.Put(kStringIndex, string_entry_offset);
358 bss_begin_ = bss_begin;
359 const LinkerPatch patches[] = {
360 LinkerPatch::StringBssEntryPatch(0u, nullptr, kPcInsnOffset, kStringIndex),
361 LinkerPatch::StringBssEntryPatch(4u, nullptr, kPcInsnOffset, kStringIndex),
362 };
363 CheckPcRelativePatch(ArrayRef<const LinkerPatch>(patches), bss_begin_ + string_entry_offset);
364 }
365
366 void Thumb2RelativePatcherTest::TestStringReference(uint32_t string_offset) {
367 constexpr uint32_t kStringIndex = 1u;
368 string_index_to_offset_map_.Put(kStringIndex, string_offset);
369 const LinkerPatch patches[] = {
370 LinkerPatch::RelativeStringPatch(0u, nullptr, kPcInsnOffset, kStringIndex),
371 LinkerPatch::RelativeStringPatch(4u, nullptr, kPcInsnOffset, kStringIndex),
372 };
373 CheckPcRelativePatch(ArrayRef<const LinkerPatch>(patches), string_offset);
374 }
375
376 void Thumb2RelativePatcherTest::CheckPcRelativePatch(const ArrayRef<const LinkerPatch>& patches,
377 uint32_t target_offset) {
378 AddCompiledMethod(MethodRef(1u), kUnpatchedPcRelativeCode, ArrayRef<const LinkerPatch>(patches));
379 Link();
380
381 uint32_t method1_offset = GetMethodOffset(1u);
382 uint32_t pc_base_offset = method1_offset + kPcInsnOffset + 4u /* PC adjustment */;
383 uint32_t diff = target_offset - pc_base_offset;
384 // Distribute the bits of the diff between the MOVW and MOVT:
385 uint32_t diffw = diff & 0xffffu;
386 uint32_t difft = diff >> 16;
387 uint32_t movw = 0xf2400000u | // MOVW r0, #0 (placeholder),
388 ((diffw & 0xf000u) << (16 - 12)) | // move imm4 from bits 12-15 to bits 16-19,
389 ((diffw & 0x0800u) << (26 - 11)) | // move imm from bit 11 to bit 26,
390 ((diffw & 0x0700u) << (12 - 8)) | // move imm3 from bits 8-10 to bits 12-14,
391 ((diffw & 0x00ffu)); // keep imm8 at bits 0-7.
392 uint32_t movt = 0xf2c00000u | // MOVT r0, #0 (placeholder),
393 ((difft & 0xf000u) << (16 - 12)) | // move imm4 from bits 12-15 to bits 16-19,
394 ((difft & 0x0800u) << (26 - 11)) | // move imm from bit 11 to bit 26,
395 ((difft & 0x0700u) << (12 - 8)) | // move imm3 from bits 8-10 to bits 12-14,
396 ((difft & 0x00ffu)); // keep imm8 at bits 0-7.
397 const uint8_t expected_code[] = {
398 static_cast<uint8_t>(movw >> 16), static_cast<uint8_t>(movw >> 24),
399 static_cast<uint8_t>(movw >> 0), static_cast<uint8_t>(movw >> 8),
400 static_cast<uint8_t>(movt >> 16), static_cast<uint8_t>(movt >> 24),
401 static_cast<uint8_t>(movt >> 0), static_cast<uint8_t>(movt >> 8),
402 0x78, 0x44,
403 };
404 EXPECT_TRUE(CheckLinkedMethod(MethodRef(1u), ArrayRef<const uint8_t>(expected_code)));
405 }
406
407 TEST_F(Thumb2RelativePatcherTest, CallSelf) {
408 const LinkerPatch patches[] = {
409 LinkerPatch::RelativeCodePatch(0u, nullptr, 1u),
410 };
411 AddCompiledMethod(MethodRef(1u), kCallCode, ArrayRef<const LinkerPatch>(patches));
412 Link();
413
414 static const uint8_t expected_code[] = {
415 0xff, 0xf7, 0xfe, 0xff
416 };
417 EXPECT_TRUE(CheckLinkedMethod(MethodRef(1u), ArrayRef<const uint8_t>(expected_code)));
418 }
419
420 TEST_F(Thumb2RelativePatcherTest, CallOther) {
421 const LinkerPatch method1_patches[] = {
422 LinkerPatch::RelativeCodePatch(0u, nullptr, 2u),
423 };
424 AddCompiledMethod(MethodRef(1u), kCallCode, ArrayRef<const LinkerPatch>(method1_patches));
425 const LinkerPatch method2_patches[] = {
426 LinkerPatch::RelativeCodePatch(0u, nullptr, 1u),
427 };
428 AddCompiledMethod(MethodRef(2u), kCallCode, ArrayRef<const LinkerPatch>(method2_patches));
429 Link();
430
431 uint32_t method1_offset = GetMethodOffset(1u);
432 uint32_t method2_offset = GetMethodOffset(2u);
433 uint32_t diff_after = method2_offset - (method1_offset + 4u /* PC adjustment */);
434 ASSERT_EQ(diff_after & 1u, 0u);
435 ASSERT_LT(diff_after >> 1, 1u << 8); // Simple encoding, (diff_after >> 1) fits into 8 bits.
436 static const uint8_t method1_expected_code[] = {
437 0x00, 0xf0, static_cast<uint8_t>(diff_after >> 1), 0xf8
438 };
439 EXPECT_TRUE(CheckLinkedMethod(MethodRef(1u), ArrayRef<const uint8_t>(method1_expected_code)));
440 uint32_t diff_before = method1_offset - (method2_offset + 4u /* PC adjustment */);
441 ASSERT_EQ(diff_before & 1u, 0u);
442 ASSERT_GE(diff_before, -1u << 9); // Simple encoding, -256 <= (diff >> 1) < 0.
443 auto method2_expected_code = GenNopsAndBl(0u, kBlMinus256 | ((diff_before >> 1) & 0xffu));
444 EXPECT_TRUE(CheckLinkedMethod(MethodRef(2u), ArrayRef<const uint8_t>(method2_expected_code)));
445 }
446
447 TEST_F(Thumb2RelativePatcherTest, CallTrampoline) {
448 const LinkerPatch patches[] = {
449 LinkerPatch::RelativeCodePatch(0u, nullptr, 2u),
450 };
451 AddCompiledMethod(MethodRef(1u), kCallCode, ArrayRef<const LinkerPatch>(patches));
452 Link();
453
454 uint32_t method1_offset = GetMethodOffset(1u);
455 uint32_t diff = kTrampolineOffset - (method1_offset + 4u);
456 ASSERT_EQ(diff & 1u, 0u);
457 ASSERT_GE(diff, -1u << 9); // Simple encoding, -256 <= (diff >> 1) < 0 (checked as unsigned).
458 auto expected_code = GenNopsAndBl(0u, kBlMinus256 | ((diff >> 1) & 0xffu));
459 EXPECT_TRUE(CheckLinkedMethod(MethodRef(1u), ArrayRef<const uint8_t>(expected_code)));
460 }
461
462 TEST_F(Thumb2RelativePatcherTest, CallTrampolineTooFar) {
463 constexpr uint32_t missing_method_index = 1024u;
464 auto last_method_raw_code = GenNopsAndBl(3u, kBlPlus0);
465 constexpr uint32_t bl_offset_in_last_method = 3u * 2u; // After NOPs.
466 ArrayRef<const uint8_t> last_method_code(last_method_raw_code);
467 ASSERT_EQ(bl_offset_in_last_method + 4u, last_method_code.size());
468 const LinkerPatch last_method_patches[] = {
469 LinkerPatch::RelativeCodePatch(bl_offset_in_last_method, nullptr, missing_method_index),
470 };
471
472 constexpr uint32_t just_over_max_negative_disp = 16 * MB + 2 - 4u /* PC adjustment */;
473 uint32_t last_method_idx = Create2MethodsWithGap(
474 kNopCode,
475 ArrayRef<const LinkerPatch>(),
476 last_method_code,
477 ArrayRef<const LinkerPatch>(last_method_patches),
478 just_over_max_negative_disp - bl_offset_in_last_method);
479 uint32_t method1_offset = GetMethodOffset(1u);
480 uint32_t last_method_offset = GetMethodOffset(last_method_idx);
481 ASSERT_EQ(method1_offset,
482 last_method_offset + bl_offset_in_last_method - just_over_max_negative_disp);
483 ASSERT_FALSE(method_offset_map_.FindMethodOffset(MethodRef(missing_method_index)).first);
484
485 // Check linked code.
486 uint32_t thunk_offset = CompiledCode::AlignCode(
487 last_method_offset + last_method_code.size(), InstructionSet::kThumb2);
488 uint32_t diff =
489 thunk_offset - (last_method_offset + bl_offset_in_last_method + 4u /* PC adjustment */);
490 ASSERT_TRUE(IsAligned<2u>(diff));
491 ASSERT_LT(diff >> 1, 1u << 8); // Simple encoding, (diff >> 1) fits into 8 bits.
492 auto expected_code = GenNopsAndBl(3u, kBlPlus0 | ((diff >> 1) & 0xffu));
493 EXPECT_TRUE(CheckLinkedMethod(MethodRef(last_method_idx),
494 ArrayRef<const uint8_t>(expected_code)));
495 EXPECT_TRUE(CheckThunk(thunk_offset));
496 }
497
498 TEST_F(Thumb2RelativePatcherTest, CallOtherAlmostTooFarAfter) {
499 auto method1_raw_code = GenNopsAndBl(3u, kBlPlus0);
500 constexpr uint32_t bl_offset_in_method1 = 3u * 2u; // After NOPs.
501 ArrayRef<const uint8_t> method1_code(method1_raw_code);
502 ASSERT_EQ(bl_offset_in_method1 + 4u, method1_code.size());
503 const uint32_t kExpectedLastMethodIdx = 9u; // Based on 2MiB chunks in Create2MethodsWithGap().
504 const LinkerPatch method1_patches[] = {
505 LinkerPatch::RelativeCodePatch(bl_offset_in_method1, nullptr, kExpectedLastMethodIdx),
506 };
507
508 constexpr uint32_t max_positive_disp = 16 * MB - 2u + 4u /* PC adjustment */;
509 uint32_t last_method_idx = Create2MethodsWithGap(method1_code,
510 ArrayRef<const LinkerPatch>(method1_patches),
511 kNopCode,
512 ArrayRef<const LinkerPatch>(),
513 bl_offset_in_method1 + max_positive_disp);
514 ASSERT_EQ(kExpectedLastMethodIdx, last_method_idx);
515
516 // Check linked code.
517 auto expected_code = GenNopsAndBl(3u, kBlPlusMax);
518 EXPECT_TRUE(CheckLinkedMethod(MethodRef(1u), ArrayRef<const uint8_t>(expected_code)));
519 }
520
521 TEST_F(Thumb2RelativePatcherTest, CallOtherAlmostTooFarBefore) {
522 auto last_method_raw_code = GenNopsAndBl(2u, kBlPlus0);
523 constexpr uint32_t bl_offset_in_last_method = 2u * 2u; // After NOPs.
524 ArrayRef<const uint8_t> last_method_code(last_method_raw_code);
525 ASSERT_EQ(bl_offset_in_last_method + 4u, last_method_code.size());
526 const LinkerPatch last_method_patches[] = {
527 LinkerPatch::RelativeCodePatch(bl_offset_in_last_method, nullptr, 1u),
528 };
529
530 constexpr uint32_t max_negative_disp = 16 * MB - 4u /* PC adjustment */;
531 uint32_t last_method_idx = Create2MethodsWithGap(kNopCode,
532 ArrayRef<const LinkerPatch>(),
533 last_method_code,
534 ArrayRef<const LinkerPatch>(last_method_patches),
535 max_negative_disp - bl_offset_in_last_method);
536 uint32_t method1_offset = GetMethodOffset(1u);
537 uint32_t last_method_offset = GetMethodOffset(last_method_idx);
538 ASSERT_EQ(method1_offset, last_method_offset + bl_offset_in_last_method - max_negative_disp);
539
540 // Check linked code.
541 auto expected_code = GenNopsAndBl(2u, kBlMinusMax);
542 EXPECT_TRUE(CheckLinkedMethod(MethodRef(last_method_idx),
543 ArrayRef<const uint8_t>(expected_code)));
544 }
545
546 TEST_F(Thumb2RelativePatcherTest, CallOtherJustTooFarAfter) {
547 auto method1_raw_code = GenNopsAndBl(2u, kBlPlus0);
548 constexpr uint32_t bl_offset_in_method1 = 2u * 2u; // After NOPs.
549 ArrayRef<const uint8_t> method1_code(method1_raw_code);
550 ASSERT_EQ(bl_offset_in_method1 + 4u, method1_code.size());
551 const uint32_t kExpectedLastMethodIdx = 9u; // Based on 2MiB chunks in Create2MethodsWithGap().
552 const LinkerPatch method1_patches[] = {
553 LinkerPatch::RelativeCodePatch(bl_offset_in_method1, nullptr, kExpectedLastMethodIdx),
554 };
555
556 constexpr uint32_t just_over_max_positive_disp = 16 * MB + 4u /* PC adjustment */;
557 uint32_t last_method_idx = Create2MethodsWithGap(
558 method1_code,
559 ArrayRef<const LinkerPatch>(method1_patches),
560 kNopCode,
561 ArrayRef<const LinkerPatch>(),
562 bl_offset_in_method1 + just_over_max_positive_disp);
563 ASSERT_EQ(kExpectedLastMethodIdx, last_method_idx);
564 uint32_t method_after_thunk_idx = last_method_idx;
565 if (sizeof(OatQuickMethodHeader) < kArmCodeAlignment) {
566 // The thunk needs to start on a kArmCodeAlignment-aligned address before the address where the
567 // last method would have been if there was no thunk. If the size of the OatQuickMethodHeader
568 // is at least kArmCodeAlignment, the thunk start shall fit between the previous filler method
569 // and that address. Otherwise, it shall be inserted before that filler method.
570 method_after_thunk_idx -= 1u;
571 }
572
573 uint32_t method1_offset = GetMethodOffset(1u);
574 uint32_t method_after_thunk_offset = GetMethodOffset(method_after_thunk_idx);
575 ASSERT_TRUE(IsAligned<kArmCodeAlignment>(method_after_thunk_offset));
576 uint32_t method_after_thunk_header_offset =
577 method_after_thunk_offset - sizeof(OatQuickMethodHeader);
578 uint32_t thunk_size = MethodCallThunkSize();
579 uint32_t thunk_offset =
580 RoundDown(method_after_thunk_header_offset - thunk_size, kArmCodeAlignment);
581 DCHECK_EQ(thunk_offset + thunk_size + CodeAlignmentSize(thunk_offset + thunk_size),
582 method_after_thunk_header_offset);
583 ASSERT_TRUE(IsAligned<kArmCodeAlignment>(thunk_offset));
584 uint32_t diff = thunk_offset - (method1_offset + bl_offset_in_method1 + 4u /* PC adjustment */);
585 ASSERT_TRUE(IsAligned<2u>(diff));
586 ASSERT_GE(diff, 16 * MB - (1u << 22)); // Simple encoding, unknown bits fit into imm10:imm11:0.
587 auto expected_code =
588 GenNopsAndBl(2u, 0xf000d000 | ((diff >> 1) & 0x7ffu) | (((diff >> 12) & 0x3ffu) << 16));
589 EXPECT_TRUE(CheckLinkedMethod(MethodRef(1u), ArrayRef<const uint8_t>(expected_code)));
590 CheckThunk(thunk_offset);
591 }
592
593 TEST_F(Thumb2RelativePatcherTest, CallOtherJustTooFarBefore) {
594 auto last_method_raw_code = GenNopsAndBl(3u, kBlPlus0);
595 constexpr uint32_t bl_offset_in_last_method = 3u * 2u; // After NOPs.
596 ArrayRef<const uint8_t> last_method_code(last_method_raw_code);
597 ASSERT_EQ(bl_offset_in_last_method + 4u, last_method_code.size());
598 const LinkerPatch last_method_patches[] = {
599 LinkerPatch::RelativeCodePatch(bl_offset_in_last_method, nullptr, 1u),
600 };
601
602 constexpr uint32_t just_over_max_negative_disp = 16 * MB + 2 - 4u /* PC adjustment */;
603 uint32_t last_method_idx = Create2MethodsWithGap(
604 kNopCode,
605 ArrayRef<const LinkerPatch>(),
606 last_method_code,
607 ArrayRef<const LinkerPatch>(last_method_patches),
608 just_over_max_negative_disp - bl_offset_in_last_method);
609 uint32_t method1_offset = GetMethodOffset(1u);
610 uint32_t last_method_offset = GetMethodOffset(last_method_idx);
611 ASSERT_EQ(method1_offset,
612 last_method_offset + bl_offset_in_last_method - just_over_max_negative_disp);
613
614 // Check linked code.
615 uint32_t thunk_offset = CompiledCode::AlignCode(
616 last_method_offset + last_method_code.size(), InstructionSet::kThumb2);
617 uint32_t diff =
618 thunk_offset - (last_method_offset + bl_offset_in_last_method + 4u /* PC adjustment */);
619 ASSERT_TRUE(IsAligned<2u>(diff));
620 ASSERT_LT(diff >> 1, 1u << 8); // Simple encoding, (diff >> 1) fits into 8 bits.
621 auto expected_code = GenNopsAndBl(3u, kBlPlus0 | ((diff >> 1) & 0xffu));
622 EXPECT_TRUE(CheckLinkedMethod(MethodRef(last_method_idx),
623 ArrayRef<const uint8_t>(expected_code)));
624 EXPECT_TRUE(CheckThunk(thunk_offset));
625 }
626
627 TEST_F(Thumb2RelativePatcherTest, StringBssEntry1) {
628 TestStringBssEntry(0x00ff0000u, 0x00fcu);
629 ASSERT_LT(GetMethodOffset(1u), 0xfcu);
630 }
631
632 TEST_F(Thumb2RelativePatcherTest, StringBssEntry2) {
633 TestStringBssEntry(0x02ff0000u, 0x05fcu);
634 ASSERT_LT(GetMethodOffset(1u), 0xfcu);
635 }
636
637 TEST_F(Thumb2RelativePatcherTest, StringBssEntry3) {
638 TestStringBssEntry(0x08ff0000u, 0x08fcu);
639 ASSERT_LT(GetMethodOffset(1u), 0xfcu);
640 }
641
642 TEST_F(Thumb2RelativePatcherTest, StringBssEntry4) {
643 TestStringBssEntry(0xd0ff0000u, 0x60fcu);
644 ASSERT_LT(GetMethodOffset(1u), 0xfcu);
645 }
646
647 TEST_F(Thumb2RelativePatcherTest, StringReference1) {
648 TestStringReference(0x00ff00fcu);
649 ASSERT_LT(GetMethodOffset(1u), 0xfcu);
650 }
651
652 TEST_F(Thumb2RelativePatcherTest, StringReference2) {
653 TestStringReference(0x02ff05fcu);
654 ASSERT_LT(GetMethodOffset(1u), 0xfcu);
655 }
656
657 TEST_F(Thumb2RelativePatcherTest, StringReference3) {
658 TestStringReference(0x08ff08fcu);
659 ASSERT_LT(GetMethodOffset(1u), 0xfcu);
660 }
661
662 TEST_F(Thumb2RelativePatcherTest, StringReference4) {
663 TestStringReference(0xd0ff60fcu);
664 ASSERT_LT(GetMethodOffset(1u), 0xfcu);
665 }
666
667 TEST_F(Thumb2RelativePatcherTest, EntrypointCall) {
668 constexpr uint32_t kEntrypointOffset = 512;
669 const LinkerPatch patches[] = {
670 LinkerPatch::CallEntrypointPatch(0u, kEntrypointOffset),
671 };
672 AddCompiledMethod(MethodRef(1u), kCallCode, ArrayRef<const LinkerPatch>(patches));
673 Link();
674
675 uint32_t method_offset = GetMethodOffset(1u);
676 uint32_t thunk_offset = CompiledCode::AlignCode(method_offset + kCallCode.size(),
677 InstructionSet::kThumb2);
678 uint32_t diff = thunk_offset - method_offset - kPcAdjustment;
679 ASSERT_TRUE(IsAligned<2u>(diff));
680 ASSERT_LT(diff >> 1, 1u << 8); // Simple encoding, (diff >> 1) fits into 8 bits.
681 auto expected_code = GenNopsAndBl(0u, kBlPlus0 | ((diff >> 1) & 0xffu));
682 EXPECT_TRUE(CheckLinkedMethod(MethodRef(1u), ArrayRef<const uint8_t>(expected_code)));
683
684 // Verify the thunk.
685 uint32_t ldr_pc_tr_offset =
686 0xf8d00000 | // LDR Rt, [Rn, #<imm12>]
687 (/* tr */ 9 << 16) | // Rn = TR
688 (/* pc */ 15 << 12) | // Rt = PC
689 kEntrypointOffset; // imm12
690 uint16_t bkpt = 0xbe00;
691 ASSERT_LE(6u, output_.size() - thunk_offset);
692 EXPECT_EQ(ldr_pc_tr_offset, GetOutputInsn32(thunk_offset));
693 EXPECT_EQ(bkpt, GetOutputInsn16(thunk_offset + 4u));
694 }
695
696 const uint32_t kBakerValidRegs[] = {
697 0, 1, 2, 3, 4, 5, 6, 7,
698 9, 10, 11, // r8 (rMR), IP, SP, LR and PC are reserved.
699 };
700
701 const uint32_t kBakerValidRegsNarrow[] = {
702 0, 1, 2, 3, 4, 5, 6, 7,
703 };
704
705 void Thumb2RelativePatcherTest::TestBakerFieldWide(uint32_t offset, uint32_t ref_reg) {
706 DCHECK_ALIGNED(offset, 4u);
707 DCHECK_LT(offset, 4 * KB);
708 constexpr size_t kMethodCodeSize = 8u;
709 constexpr size_t kLiteralOffset = 0u;
710 uint32_t method_idx = 0u;
711 for (uint32_t base_reg : kBakerValidRegs) {
712 for (uint32_t holder_reg : kBakerValidRegs) {
713 uint32_t ldr = kLdrWInsn | offset | (base_reg << 16) | (ref_reg << 12);
714 const std::vector<uint8_t> raw_code = RawCode({kBneWPlus0, ldr});
715 ASSERT_EQ(kMethodCodeSize, raw_code.size());
716 ArrayRef<const uint8_t> code(raw_code);
717 uint32_t encoded_data = EncodeBakerReadBarrierFieldData(
718 base_reg, holder_reg, /* narrow */ false);
719 const LinkerPatch patches[] = {
720 LinkerPatch::BakerReadBarrierBranchPatch(kLiteralOffset, encoded_data),
721 };
722 ++method_idx;
723 AddCompiledMethod(MethodRef(method_idx), code, ArrayRef<const LinkerPatch>(patches));
724 }
725 }
726 Link();
727
728 // All thunks are at the end.
729 uint32_t thunk_offset = GetMethodOffset(method_idx) + RoundUp(kMethodCodeSize, kArmCodeAlignment);
730 method_idx = 0u;
731 for (uint32_t base_reg : kBakerValidRegs) {
732 for (uint32_t holder_reg : kBakerValidRegs) {
733 ++method_idx;
734 uint32_t bne = BneWWithOffset(GetMethodOffset(method_idx) + kLiteralOffset, thunk_offset);
735 uint32_t ldr = kLdrWInsn | offset | (base_reg << 16) | (ref_reg << 12);
736 const std::vector<uint8_t> expected_code = RawCode({bne, ldr});
737 ASSERT_EQ(kMethodCodeSize, expected_code.size()) << "bne=0x" << std::hex << bne;
738 ASSERT_TRUE(
739 CheckLinkedMethod(MethodRef(method_idx), ArrayRef<const uint8_t>(expected_code)));
740
741 std::vector<uint8_t> expected_thunk =
742 CompileBakerOffsetThunk(base_reg, holder_reg, /* narrow */ false);
743 ASSERT_GT(output_.size(), thunk_offset);
744 ASSERT_GE(output_.size() - thunk_offset, expected_thunk.size());
745 ArrayRef<const uint8_t> compiled_thunk(output_.data() + thunk_offset,
746 expected_thunk.size());
747 if (ArrayRef<const uint8_t>(expected_thunk) != compiled_thunk) {
748 DumpDiff(ArrayRef<const uint8_t>(expected_thunk), compiled_thunk);
749 ASSERT_TRUE(false);
750 }
751
752 size_t gray_check_offset = thunk_offset;
753 if (holder_reg == base_reg) {
754 // Verify that the null-check uses the correct register, i.e. holder_reg.
755 if (holder_reg < 8) {
756 ASSERT_GE(output_.size() - gray_check_offset, 2u);
757 ASSERT_EQ(0xb100 | holder_reg, GetOutputInsn16(thunk_offset) & 0xfd07u);
758 gray_check_offset +=2u;
759 } else {
760 ASSERT_GE(output_.size() - gray_check_offset, 6u);
761 ASSERT_EQ(0xf1b00f00u | (holder_reg << 16), GetOutputInsn32(thunk_offset) & 0xfbff8f00u);
762 ASSERT_EQ(0xd000u, GetOutputInsn16(thunk_offset + 4u) & 0xff00u); // BEQ
763 gray_check_offset += 6u;
764 }
765 }
766 // Verify that the lock word for gray bit check is loaded from the holder address.
767 ASSERT_GE(output_.size() - gray_check_offset,
768 4u * /* 32-bit instructions */ 4u + 2u * /* 16-bit instructions */ 2u);
769 const uint32_t load_lock_word =
770 kLdrWInsn |
771 (holder_reg << 16) |
772 (/* IP */ 12 << 12) |
773 mirror::Object::MonitorOffset().Uint32Value();
774 ASSERT_EQ(load_lock_word, GetOutputInsn32(gray_check_offset));
775 // Verify the gray bit check.
776 DCHECK_GE(LockWord::kReadBarrierStateShift, 8u); // ROR modified immediate.
777 uint32_t ror_shift = 7 + (32 - LockWord::kReadBarrierStateShift);
778 const uint32_t tst_gray_bit_without_offset =
779 0xf0100f00 | (/* IP */ 12 << 16)
780 | (((ror_shift >> 4) & 1) << 26) // i
781 | (((ror_shift >> 1) & 7) << 12) // imm3
782 | ((ror_shift & 1) << 7); // imm8, ROR('1':imm8<7:0>, ror_shift).
783 EXPECT_EQ(tst_gray_bit_without_offset, GetOutputInsn32(gray_check_offset + 4u));
784 EXPECT_EQ(0xd100u, GetOutputInsn16(gray_check_offset + 8u) & 0xff00u); // BNE
785 // Verify the fake dependency (skip "ADD LR, LR, #ldr_offset").
786 const uint32_t fake_dependency =
787 0xeb000010 | // ADD Rd, Rn, Rm, LSR 32 (type=01, imm3=000, imm2=00)
788 (/* IP */ 12) | // Rm = IP
789 (base_reg << 16) | // Rn = base_reg
790 (base_reg << 8); // Rd = base_reg
791 EXPECT_EQ(fake_dependency, GetOutputInsn32(gray_check_offset + 14u));
792 // Do not check the rest of the implementation.
793
794 // The next thunk follows on the next aligned offset.
795 thunk_offset += RoundUp(expected_thunk.size(), kArmCodeAlignment);
796 }
797 }
798 }
799
800 void Thumb2RelativePatcherTest::TestBakerFieldNarrow(uint32_t offset, uint32_t ref_reg) {
801 DCHECK_ALIGNED(offset, 4u);
802 DCHECK_LT(offset, 32u);
803 constexpr size_t kMethodCodeSize = 6u;
804 constexpr size_t kLiteralOffset = 0u;
805 uint32_t method_idx = 0u;
806 for (uint32_t base_reg : kBakerValidRegs) {
807 if (base_reg >= 8u) {
808 continue;
809 }
810 for (uint32_t holder_reg : kBakerValidRegs) {
811 uint32_t ldr = kLdrInsn | (offset << (6 - 2)) | (base_reg << 3) | ref_reg;
812 const std::vector<uint8_t> raw_code = RawCode({kBneWPlus0, ldr});
813 ASSERT_EQ(kMethodCodeSize, raw_code.size());
814 ArrayRef<const uint8_t> code(raw_code);
815 uint32_t encoded_data = EncodeBakerReadBarrierFieldData(
816 base_reg, holder_reg, /* narrow */ true);
817 const LinkerPatch patches[] = {
818 LinkerPatch::BakerReadBarrierBranchPatch(kLiteralOffset, encoded_data),
819 };
820 ++method_idx;
821 AddCompiledMethod(MethodRef(method_idx), code, ArrayRef<const LinkerPatch>(patches));
822 }
823 }
824 Link();
825
826 // All thunks are at the end.
827 uint32_t thunk_offset = GetMethodOffset(method_idx) + RoundUp(kMethodCodeSize, kArmCodeAlignment);
828 method_idx = 0u;
829 for (uint32_t base_reg : kBakerValidRegs) {
830 if (base_reg >= 8u) {
831 continue;
832 }
833 for (uint32_t holder_reg : kBakerValidRegs) {
834 ++method_idx;
835 uint32_t bne = BneWWithOffset(GetMethodOffset(method_idx) + kLiteralOffset, thunk_offset);
836 uint32_t ldr = kLdrInsn | (offset << (6 - 2)) | (base_reg << 3) | ref_reg;
837 const std::vector<uint8_t> expected_code = RawCode({bne, ldr});
838 ASSERT_EQ(kMethodCodeSize, expected_code.size()) << "bne=0x" << std::hex << bne;
839 ASSERT_TRUE(
840 CheckLinkedMethod(MethodRef(method_idx), ArrayRef<const uint8_t>(expected_code)));
841
842 std::vector<uint8_t> expected_thunk =
843 CompileBakerOffsetThunk(base_reg, holder_reg, /* narrow */ true);
844 ASSERT_GT(output_.size(), thunk_offset);
845 ASSERT_GE(output_.size() - thunk_offset, expected_thunk.size());
846 ArrayRef<const uint8_t> compiled_thunk(output_.data() + thunk_offset,
847 expected_thunk.size());
848 if (ArrayRef<const uint8_t>(expected_thunk) != compiled_thunk) {
849 DumpDiff(ArrayRef<const uint8_t>(expected_thunk), compiled_thunk);
850 ASSERT_TRUE(false);
851 }
852
853 size_t gray_check_offset = thunk_offset;
854 if (holder_reg == base_reg) {
855 // Verify that the null-check uses the correct register, i.e. holder_reg.
856 if (holder_reg < 8) {
857 ASSERT_GE(output_.size() - gray_check_offset, 2u);
858 ASSERT_EQ(0xb100 | holder_reg, GetOutputInsn16(thunk_offset) & 0xfd07u);
859 gray_check_offset +=2u;
860 } else {
861 ASSERT_GE(output_.size() - gray_check_offset, 6u);
862 ASSERT_EQ(0xf1b00f00u | (holder_reg << 16), GetOutputInsn32(thunk_offset) & 0xfbff8f00u);
863 ASSERT_EQ(0xd000u, GetOutputInsn16(thunk_offset + 4u) & 0xff00u); // BEQ
864 gray_check_offset += 6u;
865 }
866 }
867 // Verify that the lock word for gray bit check is loaded from the holder address.
868 ASSERT_GE(output_.size() - gray_check_offset,
869 4u * /* 32-bit instructions */ 4u + 2u * /* 16-bit instructions */ 2u);
870 const uint32_t load_lock_word =
871 kLdrWInsn |
872 (holder_reg << 16) |
873 (/* IP */ 12 << 12) |
874 mirror::Object::MonitorOffset().Uint32Value();
875 ASSERT_EQ(load_lock_word, GetOutputInsn32(gray_check_offset));
876 // Verify the gray bit check.
877 DCHECK_GE(LockWord::kReadBarrierStateShift, 8u); // ROR modified immediate.
878 uint32_t ror_shift = 7 + (32 - LockWord::kReadBarrierStateShift);
879 const uint32_t tst_gray_bit_without_offset =
880 0xf0100f00 | (/* IP */ 12 << 16)
881 | (((ror_shift >> 4) & 1) << 26) // i
882 | (((ror_shift >> 1) & 7) << 12) // imm3
883 | ((ror_shift & 1) << 7); // imm8, ROR('1':imm8<7:0>, ror_shift).
884 EXPECT_EQ(tst_gray_bit_without_offset, GetOutputInsn32(gray_check_offset + 4u));
885 EXPECT_EQ(0xd100u, GetOutputInsn16(gray_check_offset + 8u) & 0xff00u); // BNE
886 // Verify the fake dependency (skip "ADD LR, LR, #ldr_offset").
887 const uint32_t fake_dependency =
888 0xeb000010 | // ADD Rd, Rn, Rm, LSR 32 (type=01, imm3=000, imm2=00)
889 (/* IP */ 12) | // Rm = IP
890 (base_reg << 16) | // Rn = base_reg
891 (base_reg << 8); // Rd = base_reg
892 EXPECT_EQ(fake_dependency, GetOutputInsn32(gray_check_offset + 14u));
893 // Do not check the rest of the implementation.
894
895 // The next thunk follows on the next aligned offset.
896 thunk_offset += RoundUp(expected_thunk.size(), kArmCodeAlignment);
897 }
898 }
899 }
900
901 TEST_F(Thumb2RelativePatcherTest, BakerOffsetWide) {
902 struct TestCase {
903 uint32_t offset;
904 uint32_t ref_reg;
905 };
906 static const TestCase test_cases[] = {
907 { 0u, 0u },
908 { 8u, 3u },
909 { 28u, 7u },
910 { 0xffcu, 11u },
911 };
912 for (const TestCase& test_case : test_cases) {
913 Reset();
914 TestBakerFieldWide(test_case.offset, test_case.ref_reg);
915 }
916 }
917
918 TEST_F(Thumb2RelativePatcherTest, BakerOffsetNarrow) {
919 struct TestCase {
920 uint32_t offset;
921 uint32_t ref_reg;
922 };
923 static const TestCase test_cases[] = {
924 { 0, 0u },
925 { 8, 3u },
926 { 28, 7u },
927 };
928 for (const TestCase& test_case : test_cases) {
929 Reset();
930 TestBakerFieldNarrow(test_case.offset, test_case.ref_reg);
931 }
932 }
933
934 TEST_F(Thumb2RelativePatcherTest, BakerOffsetThunkInTheMiddle) {
935 // One thunk in the middle with maximum distance branches to it from both sides.
936 // Use offset = 0, base_reg = 0, ref_reg = 0, the LDR is simply `kLdrWInsn`.
937 constexpr uint32_t kLiteralOffset1 = 6u;
938 const std::vector<uint8_t> raw_code1 = RawCode({kNopWInsn, kNopInsn, kBneWPlus0, kLdrWInsn});
939 ArrayRef<const uint8_t> code1(raw_code1);
940 uint32_t encoded_data = EncodeBakerReadBarrierFieldData(
941 /* base_reg */ 0, /* holder_reg */ 0, /* narrow */ false);
942 const LinkerPatch patches1[] = {
943 LinkerPatch::BakerReadBarrierBranchPatch(kLiteralOffset1, encoded_data),
944 };
945 AddCompiledMethod(MethodRef(1u), code1, ArrayRef<const LinkerPatch>(patches1));
946
947 constexpr uint32_t expected_thunk_offset =
948 kLiteralOffset1 + kPcAdjustment + /* kMaxBcondPositiveDisplacement */ ((1 << 20) - 2u);
949 static_assert(IsAligned<kArmCodeAlignment>(expected_thunk_offset),
950 "Target offset must be aligned.");
951 size_t filler1_size = expected_thunk_offset -
952 RoundUp(raw_code1.size() + sizeof(OatQuickMethodHeader), kArmCodeAlignment);
953 std::vector<uint8_t> raw_filler1_code = GenNops(filler1_size / 2u);
954 ArrayRef<const uint8_t> filler1_code(raw_filler1_code);
955 AddCompiledMethod(MethodRef(2u), filler1_code);
956
957 // Enforce thunk reservation with a tiny method.
958 AddCompiledMethod(MethodRef(3u), kNopCode);
959
960 constexpr uint32_t kLiteralOffset2 = 4;
961 static_assert(IsAligned<kArmCodeAlignment>(kLiteralOffset2 + kPcAdjustment),
962 "PC for BNE must be aligned.");
963
964 // Allow reaching the thunk from the very beginning of a method almost 1MiB away. Backward branch
965 // reaches the full 1MiB but we need to take PC adjustment into account. Things to subtract:
966 // - thunk size and method 3 pre-header, rounded up (padding in between if needed)
967 // - method 3 code and method 4 pre-header, rounded up (padding in between if needed)
968 // - method 4 header (let there be no padding between method 4 code and method 5 pre-header).
969 size_t thunk_size =
970 CompileBakerOffsetThunk(/* base_reg */ 0, /* holder_reg */ 0, /* narrow */ false).size();
971 size_t filler2_size =
972 1 * MB - (kLiteralOffset2 + kPcAdjustment)
973 - RoundUp(thunk_size + sizeof(OatQuickMethodHeader), kArmCodeAlignment)
974 - RoundUp(kNopCode.size() + sizeof(OatQuickMethodHeader), kArmCodeAlignment)
975 - sizeof(OatQuickMethodHeader);
976 std::vector<uint8_t> raw_filler2_code = GenNops(filler2_size / 2u);
977 ArrayRef<const uint8_t> filler2_code(raw_filler2_code);
978 AddCompiledMethod(MethodRef(4u), filler2_code);
979
980 const std::vector<uint8_t> raw_code2 = RawCode({kNopWInsn, kBneWPlus0, kLdrWInsn});
981 ArrayRef<const uint8_t> code2(raw_code2);
982 const LinkerPatch patches2[] = {
983 LinkerPatch::BakerReadBarrierBranchPatch(kLiteralOffset2, encoded_data),
984 };
985 AddCompiledMethod(MethodRef(5u), code2, ArrayRef<const LinkerPatch>(patches2));
986
987 Link();
988
989 uint32_t first_method_offset = GetMethodOffset(1u);
990 uint32_t last_method_offset = GetMethodOffset(5u);
991 EXPECT_EQ(2 * MB, last_method_offset - first_method_offset);
992
993 const uint32_t bne_max_forward = kBneWPlus0 | 0x003f2fff;
994 const uint32_t bne_max_backward = kBneWPlus0 | 0x04000000;
995 const std::vector<uint8_t> expected_code1 =
996 RawCode({kNopWInsn, kNopInsn, bne_max_forward, kLdrWInsn});
997 const std::vector<uint8_t> expected_code2 = RawCode({kNopWInsn, bne_max_backward, kLdrWInsn});
998 ASSERT_TRUE(CheckLinkedMethod(MethodRef(1), ArrayRef<const uint8_t>(expected_code1)));
999 ASSERT_TRUE(CheckLinkedMethod(MethodRef(5), ArrayRef<const uint8_t>(expected_code2)));
1000 }
1001
1002 TEST_F(Thumb2RelativePatcherTest, BakerOffsetThunkBeforeFiller) {
1003 // Based on the first part of BakerOffsetThunkInTheMiddle but the BNE is one instruction
1004 // earlier, so the thunk is emitted before the filler.
1005 // Use offset = 0, base_reg = 0, ref_reg = 0, the LDR is simply `kLdrWInsn`.
1006 constexpr uint32_t kLiteralOffset1 = 4u;
1007 const std::vector<uint8_t> raw_code1 = RawCode({kNopWInsn, kBneWPlus0, kLdrWInsn, kNopInsn});
1008 ArrayRef<const uint8_t> code1(raw_code1);
1009 uint32_t encoded_data = EncodeBakerReadBarrierFieldData(
1010 /* base_reg */ 0, /* holder_reg */ 0, /* narrow */ false);
1011 const LinkerPatch patches1[] = {
1012 LinkerPatch::BakerReadBarrierBranchPatch(kLiteralOffset1, encoded_data),
1013 };
1014 AddCompiledMethod(MethodRef(1u), code1, ArrayRef<const LinkerPatch>(patches1));
1015
1016 constexpr uint32_t expected_thunk_offset =
1017 kLiteralOffset1 + kPcAdjustment + /* kMaxBcondPositiveDisplacement + 2 */ (1u << 20);
1018 static_assert(IsAligned<kArmCodeAlignment>(expected_thunk_offset),
1019 "Target offset must be aligned.");
1020 size_t filler1_size = expected_thunk_offset -
1021 RoundUp(raw_code1.size() + sizeof(OatQuickMethodHeader), kArmCodeAlignment);
1022 std::vector<uint8_t> raw_filler1_code = GenNops(filler1_size / 2u);
1023 ArrayRef<const uint8_t> filler1_code(raw_filler1_code);
1024 AddCompiledMethod(MethodRef(2u), filler1_code);
1025
1026 Link();
1027
1028 const uint32_t bne =
1029 BneWWithOffset(kLiteralOffset1, RoundUp(raw_code1.size(), kArmCodeAlignment));
1030 const std::vector<uint8_t> expected_code1 = RawCode({kNopWInsn, bne, kLdrWInsn, kNopInsn});
1031 ASSERT_TRUE(CheckLinkedMethod(MethodRef(1), ArrayRef<const uint8_t>(expected_code1)));
1032 }
1033
1034 TEST_F(Thumb2RelativePatcherTest, BakerOffsetThunkInTheMiddleUnreachableFromLast) {
1035 // Based on the BakerOffsetThunkInTheMiddle but the BNE in the last method is preceded
1036 // by NOP and cannot reach the thunk in the middle, so we emit an extra thunk at the end.
1037 // Use offset = 0, base_reg = 0, ref_reg = 0, the LDR is simply `kLdrWInsn`.
1038 constexpr uint32_t kLiteralOffset1 = 6u;
1039 const std::vector<uint8_t> raw_code1 = RawCode({kNopWInsn, kNopInsn, kBneWPlus0, kLdrWInsn});
1040 ArrayRef<const uint8_t> code1(raw_code1);
1041 uint32_t encoded_data = EncodeBakerReadBarrierFieldData(
1042 /* base_reg */ 0, /* holder_reg */ 0, /* narrow */ false);
1043 const LinkerPatch patches1[] = {
1044 LinkerPatch::BakerReadBarrierBranchPatch(kLiteralOffset1, encoded_data),
1045 };
1046 AddCompiledMethod(MethodRef(1u), code1, ArrayRef<const LinkerPatch>(patches1));
1047
1048 constexpr uint32_t expected_thunk_offset =
1049 kLiteralOffset1 + kPcAdjustment + /* kMaxBcondPositiveDisplacement */ ((1 << 20) - 2u);
1050 static_assert(IsAligned<kArmCodeAlignment>(expected_thunk_offset),
1051 "Target offset must be aligned.");
1052 size_t filler1_size = expected_thunk_offset -
1053 RoundUp(raw_code1.size() + sizeof(OatQuickMethodHeader), kArmCodeAlignment);
1054 std::vector<uint8_t> raw_filler1_code = GenNops(filler1_size / 2u);
1055 ArrayRef<const uint8_t> filler1_code(raw_filler1_code);
1056 AddCompiledMethod(MethodRef(2u), filler1_code);
1057
1058 // Enforce thunk reservation with a tiny method.
1059 AddCompiledMethod(MethodRef(3u), kNopCode);
1060
1061 constexpr uint32_t kReachableFromOffset2 = 4;
1062 constexpr uint32_t kLiteralOffset2 = kReachableFromOffset2 + 2;
1063 static_assert(IsAligned<kArmCodeAlignment>(kReachableFromOffset2 + kPcAdjustment),
1064 "PC for BNE must be aligned.");
1065
1066 // If not for the extra NOP, this would allow reaching the thunk from the BNE
1067 // of a method 1MiB away. Backward branch reaches the full 1MiB but we need to take
1068 // PC adjustment into account. Things to subtract:
1069 // - thunk size and method 3 pre-header, rounded up (padding in between if needed)
1070 // - method 3 code and method 4 pre-header, rounded up (padding in between if needed)
1071 // - method 4 header (let there be no padding between method 4 code and method 5 pre-header).
1072 size_t thunk_size =
1073 CompileBakerOffsetThunk(/* base_reg */ 0, /* holder_reg */ 0, /* narrow */ false).size();
1074 size_t filler2_size =
1075 1 * MB - (kReachableFromOffset2 + kPcAdjustment)
1076 - RoundUp(thunk_size + sizeof(OatQuickMethodHeader), kArmCodeAlignment)
1077 - RoundUp(kNopCode.size() + sizeof(OatQuickMethodHeader), kArmCodeAlignment)
1078 - sizeof(OatQuickMethodHeader);
1079 std::vector<uint8_t> raw_filler2_code = GenNops(filler2_size / 2u);
1080 ArrayRef<const uint8_t> filler2_code(raw_filler2_code);
1081 AddCompiledMethod(MethodRef(4u), filler2_code);
1082
1083 // Extra 16-bit NOP compared to BakerOffsetThunkInTheMiddle.
1084 const std::vector<uint8_t> raw_code2 = RawCode({kNopWInsn, kNopInsn, kBneWPlus0, kLdrWInsn});
1085 ArrayRef<const uint8_t> code2(raw_code2);
1086 const LinkerPatch patches2[] = {
1087 LinkerPatch::BakerReadBarrierBranchPatch(kLiteralOffset2, encoded_data),
1088 };
1089 AddCompiledMethod(MethodRef(5u), code2, ArrayRef<const LinkerPatch>(patches2));
1090
1091 Link();
1092
1093 uint32_t first_method_offset = GetMethodOffset(1u);
1094 uint32_t last_method_offset = GetMethodOffset(5u);
1095 EXPECT_EQ(2 * MB, last_method_offset - first_method_offset);
1096
1097 const uint32_t bne_max_forward = kBneWPlus0 | 0x003f2fff;
1098 const uint32_t bne_last =
1099 BneWWithOffset(kLiteralOffset2, RoundUp(raw_code2.size(), kArmCodeAlignment));
1100 const std::vector<uint8_t> expected_code1 =
1101 RawCode({kNopWInsn, kNopInsn, bne_max_forward, kLdrWInsn});
1102 const std::vector<uint8_t> expected_code2 =
1103 RawCode({kNopWInsn, kNopInsn, bne_last, kLdrWInsn});
1104 ASSERT_TRUE(CheckLinkedMethod(MethodRef(1), ArrayRef<const uint8_t>(expected_code1)));
1105 ASSERT_TRUE(CheckLinkedMethod(MethodRef(5), ArrayRef<const uint8_t>(expected_code2)));
1106 }
1107
1108 TEST_F(Thumb2RelativePatcherTest, BakerArray) {
1109 auto ldr = [](uint32_t base_reg) {
1110 uint32_t index_reg = (base_reg == 0u) ? 1u : 0u;
1111 uint32_t ref_reg = (base_reg == 2) ? 3u : 2u;
1112 return kLdrRegLsl2 | index_reg | (base_reg << 16) | (ref_reg << 12);
1113 };
1114 constexpr size_t kMethodCodeSize = 8u;
1115 constexpr size_t kLiteralOffset = 0u;
1116 uint32_t method_idx = 0u;
1117 for (uint32_t base_reg : kBakerValidRegs) {
1118 ++method_idx;
1119 const std::vector<uint8_t> raw_code = RawCode({kBneWPlus0, ldr(base_reg)});
1120 ASSERT_EQ(kMethodCodeSize, raw_code.size());
1121 ArrayRef<const uint8_t> code(raw_code);
1122 const LinkerPatch patches[] = {
1123 LinkerPatch::BakerReadBarrierBranchPatch(
1124 kLiteralOffset, EncodeBakerReadBarrierArrayData(base_reg)),
1125 };
1126 AddCompiledMethod(MethodRef(method_idx), code, ArrayRef<const LinkerPatch>(patches));
1127 }
1128 Link();
1129
1130 // All thunks are at the end.
1131 uint32_t thunk_offset = GetMethodOffset(method_idx) + RoundUp(kMethodCodeSize, kArmCodeAlignment);
1132 method_idx = 0u;
1133 for (uint32_t base_reg : kBakerValidRegs) {
1134 ++method_idx;
1135 uint32_t bne = BneWWithOffset(GetMethodOffset(method_idx) + kLiteralOffset, thunk_offset);
1136 const std::vector<uint8_t> expected_code = RawCode({bne, ldr(base_reg)});
1137 ASSERT_EQ(kMethodCodeSize, expected_code.size());
1138 EXPECT_TRUE(CheckLinkedMethod(MethodRef(method_idx), ArrayRef<const uint8_t>(expected_code)));
1139
1140 std::vector<uint8_t> expected_thunk = CompileBakerArrayThunk(base_reg);
1141 ASSERT_GT(output_.size(), thunk_offset);
1142 ASSERT_GE(output_.size() - thunk_offset, expected_thunk.size());
1143 ArrayRef<const uint8_t> compiled_thunk(output_.data() + thunk_offset,
1144 expected_thunk.size());
1145 if (ArrayRef<const uint8_t>(expected_thunk) != compiled_thunk) {
1146 DumpDiff(ArrayRef<const uint8_t>(expected_thunk), compiled_thunk);
1147 ASSERT_TRUE(false);
1148 }
1149
1150 // Verify that the lock word for gray bit check is loaded from the correct address
1151 // before the base_reg which points to the array data.
1152 ASSERT_GE(output_.size() - thunk_offset,
1153 4u * /* 32-bit instructions */ 4u + 2u * /* 16-bit instructions */ 2u);
1154 int32_t data_offset =
1155 mirror::Array::DataOffset(Primitive::ComponentSize(Primitive::kPrimNot)).Int32Value();
1156 int32_t offset = mirror::Object::MonitorOffset().Int32Value() - data_offset;
1157 ASSERT_LT(offset, 0);
1158 ASSERT_GT(offset, -256);
1159 const uint32_t load_lock_word =
1160 kLdrNegativeOffset |
1161 (-offset & 0xffu) |
1162 (base_reg << 16) |
1163 (/* IP */ 12 << 12);
1164 EXPECT_EQ(load_lock_word, GetOutputInsn32(thunk_offset));
1165 // Verify the gray bit check.
1166 DCHECK_GE(LockWord::kReadBarrierStateShift, 8u); // ROR modified immediate.
1167 uint32_t ror_shift = 7 + (32 - LockWord::kReadBarrierStateShift);
1168 const uint32_t tst_gray_bit_without_offset =
1169 0xf0100f00 | (/* IP */ 12 << 16)
1170 | (((ror_shift >> 4) & 1) << 26) // i
1171 | (((ror_shift >> 1) & 7) << 12) // imm3
1172 | ((ror_shift & 1) << 7); // imm8, ROR('1':imm8<7:0>, ror_shift).
1173 EXPECT_EQ(tst_gray_bit_without_offset, GetOutputInsn32(thunk_offset + 4u));
1174 EXPECT_EQ(0xd100u, GetOutputInsn16(thunk_offset + 8u) & 0xff00u); // BNE
1175 // Verify the fake dependency.
1176 const uint32_t fake_dependency =
1177 0xeb000010 | // ADD Rd, Rn, Rm, LSR 32 (type=01, imm3=000, imm2=00)
1178 (/* IP */ 12) | // Rm = IP
1179 (base_reg << 16) | // Rn = base_reg
1180 (base_reg << 8); // Rd = base_reg
1181 EXPECT_EQ(fake_dependency, GetOutputInsn32(thunk_offset + 14u));
1182 // Do not check the rest of the implementation.
1183
1184 // The next thunk follows on the next aligned offset.
1185 thunk_offset += RoundUp(expected_thunk.size(), kArmCodeAlignment);
1186 }
1187 }
1188
1189 TEST_F(Thumb2RelativePatcherTest, BakerGcRootWide) {
1190 constexpr size_t kMethodCodeSize = 8u;
1191 constexpr size_t kLiteralOffset = 4u;
1192 uint32_t method_idx = 0u;
1193 for (uint32_t root_reg : kBakerValidRegs) {
1194 ++method_idx;
1195 uint32_t ldr = kLdrWInsn | (/* offset */ 8) | (/* base_reg */ 0 << 16) | (root_reg << 12);
1196 const std::vector<uint8_t> raw_code = RawCode({ldr, kBneWPlus0});
1197 ASSERT_EQ(kMethodCodeSize, raw_code.size());
1198 ArrayRef<const uint8_t> code(raw_code);
1199 const LinkerPatch patches[] = {
1200 LinkerPatch::BakerReadBarrierBranchPatch(
1201 kLiteralOffset, EncodeBakerReadBarrierGcRootData(root_reg, /* narrow */ false)),
1202 };
1203 AddCompiledMethod(MethodRef(method_idx), code, ArrayRef<const LinkerPatch>(patches));
1204 }
1205 Link();
1206
1207 // All thunks are at the end.
1208 uint32_t thunk_offset = GetMethodOffset(method_idx) + RoundUp(kMethodCodeSize, kArmCodeAlignment);
1209 method_idx = 0u;
1210 for (uint32_t root_reg : kBakerValidRegs) {
1211 ++method_idx;
1212 uint32_t bne = BneWWithOffset(GetMethodOffset(method_idx) + kLiteralOffset, thunk_offset);
1213 uint32_t ldr = kLdrWInsn | (/* offset */ 8) | (/* base_reg */ 0 << 16) | (root_reg << 12);
1214 const std::vector<uint8_t> expected_code = RawCode({ldr, bne});
1215 ASSERT_EQ(kMethodCodeSize, expected_code.size());
1216 EXPECT_TRUE(CheckLinkedMethod(MethodRef(method_idx), ArrayRef<const uint8_t>(expected_code)));
1217
1218 std::vector<uint8_t> expected_thunk = CompileBakerGcRootThunk(root_reg, /* narrow */ false);
1219 ASSERT_GT(output_.size(), thunk_offset);
1220 ASSERT_GE(output_.size() - thunk_offset, expected_thunk.size());
1221 ArrayRef<const uint8_t> compiled_thunk(output_.data() + thunk_offset,
1222 expected_thunk.size());
1223 if (ArrayRef<const uint8_t>(expected_thunk) != compiled_thunk) {
1224 DumpDiff(ArrayRef<const uint8_t>(expected_thunk), compiled_thunk);
1225 ASSERT_TRUE(false);
1226 }
1227
1228 // Verify that the fast-path null-check uses the correct register, i.e. root_reg.
1229 if (root_reg < 8) {
1230 ASSERT_GE(output_.size() - thunk_offset, 2u);
1231 ASSERT_EQ(0xb100 | root_reg, GetOutputInsn16(thunk_offset) & 0xfd07u);
1232 } else {
1233 ASSERT_GE(output_.size() - thunk_offset, 6u);
1234 ASSERT_EQ(0xf1b00f00u | (root_reg << 16), GetOutputInsn32(thunk_offset) & 0xfbff8f00u);
1235 ASSERT_EQ(0xd000u, GetOutputInsn16(thunk_offset + 4u) & 0xff00u); // BEQ
1236 }
1237 // Do not check the rest of the implementation.
1238
1239 // The next thunk follows on the next aligned offset.
1240 thunk_offset += RoundUp(expected_thunk.size(), kArmCodeAlignment);
1241 }
1242 }
1243
1244 TEST_F(Thumb2RelativePatcherTest, BakerGcRootNarrow) {
1245 constexpr size_t kMethodCodeSize = 6u;
1246 constexpr size_t kLiteralOffset = 2u;
1247 uint32_t method_idx = 0u;
1248 for (uint32_t root_reg : kBakerValidRegsNarrow) {
1249 ++method_idx;
1250 uint32_t ldr = kLdrInsn | (/* offset */ 8 << (6 - 2)) | (/* base_reg */ 0 << 3) | root_reg;
1251 const std::vector<uint8_t> raw_code = RawCode({ldr, kBneWPlus0});
1252 ASSERT_EQ(kMethodCodeSize, raw_code.size());
1253 ArrayRef<const uint8_t> code(raw_code);
1254 const LinkerPatch patches[] = {
1255 LinkerPatch::BakerReadBarrierBranchPatch(
1256 kLiteralOffset, EncodeBakerReadBarrierGcRootData(root_reg, /* narrow */ true)),
1257 };
1258 AddCompiledMethod(MethodRef(method_idx), code, ArrayRef<const LinkerPatch>(patches));
1259 }
1260 Link();
1261
1262 // All thunks are at the end.
1263 uint32_t thunk_offset = GetMethodOffset(method_idx) + RoundUp(kMethodCodeSize, kArmCodeAlignment);
1264 method_idx = 0u;
1265 for (uint32_t root_reg : kBakerValidRegsNarrow) {
1266 ++method_idx;
1267 uint32_t bne = BneWWithOffset(GetMethodOffset(method_idx) + kLiteralOffset, thunk_offset);
1268 uint32_t ldr = kLdrInsn | (/* offset */ 8 << (6 - 2)) | (/* base_reg */ 0 << 3) | root_reg;
1269 const std::vector<uint8_t> expected_code = RawCode({ldr, bne});
1270 ASSERT_EQ(kMethodCodeSize, expected_code.size());
1271 EXPECT_TRUE(CheckLinkedMethod(MethodRef(method_idx), ArrayRef<const uint8_t>(expected_code)));
1272
1273 std::vector<uint8_t> expected_thunk = CompileBakerGcRootThunk(root_reg, /* narrow */ true);
1274 ASSERT_GT(output_.size(), thunk_offset);
1275 ASSERT_GE(output_.size() - thunk_offset, expected_thunk.size());
1276 ArrayRef<const uint8_t> compiled_thunk(output_.data() + thunk_offset,
1277 expected_thunk.size());
1278 if (ArrayRef<const uint8_t>(expected_thunk) != compiled_thunk) {
1279 DumpDiff(ArrayRef<const uint8_t>(expected_thunk), compiled_thunk);
1280 ASSERT_TRUE(false);
1281 }
1282
1283 // Verify that the fast-path null-check CBZ uses the correct register, i.e. root_reg.
1284 ASSERT_GE(output_.size() - thunk_offset, 2u);
1285 ASSERT_EQ(0xb100 | root_reg, GetOutputInsn16(thunk_offset) & 0xfd07u);
1286 // Do not check the rest of the implementation.
1287
1288 // The next thunk follows on the next aligned offset.
1289 thunk_offset += RoundUp(expected_thunk.size(), kArmCodeAlignment);
1290 }
1291 }
1292
1293 TEST_F(Thumb2RelativePatcherTest, BakerGcRootOffsetBits) {
1294 // Test 1MiB of patches to the same thunk to stress-test different large offsets.
1295 // (The low bits are not that important but the location of the high bits is easy to get wrong.)
1296 std::vector<uint8_t> code;
1297 code.reserve(1 * MB);
1298 const size_t num_patches = 1 * MB / 8u;
1299 std::vector<LinkerPatch> patches;
1300 patches.reserve(num_patches);
1301 const uint32_t ldr =
1302 kLdrWInsn | (/* offset */ 8) | (/* base_reg */ 0 << 16) | (/* root_reg */ 0 << 12);
1303 uint32_t encoded_data = EncodeBakerReadBarrierGcRootData(/* root_reg */ 0, /* narrow */ false);
1304 for (size_t i = 0; i != num_patches; ++i) {
1305 PushBackInsn(&code, ldr);
1306 PushBackInsn(&code, kBneWPlus0);
1307 patches.push_back(LinkerPatch::BakerReadBarrierBranchPatch(8u * i + 4u, encoded_data));
1308 }
1309 ASSERT_EQ(1 * MB, code.size());
1310 ASSERT_EQ(num_patches, patches.size());
1311 AddCompiledMethod(MethodRef(1u),
1312 ArrayRef<const uint8_t>(code),
1313 ArrayRef<const LinkerPatch>(patches));
1314 Link();
1315
1316 // The thunk is right after the method code.
1317 DCHECK_ALIGNED(1 * MB, kArmCodeAlignment);
1318 std::vector<uint8_t> expected_code;
1319 for (size_t i = 0; i != num_patches; ++i) {
1320 PushBackInsn(&expected_code, ldr);
1321 PushBackInsn(&expected_code, BneWWithOffset(8u * i + 4u, 1 * MB));
1322 patches.push_back(LinkerPatch::BakerReadBarrierBranchPatch(8u * i + 4u, encoded_data));
1323 }
1324 EXPECT_TRUE(CheckLinkedMethod(MethodRef(1u), ArrayRef<const uint8_t>(expected_code)));
1325 }
1326
1327 TEST_F(Thumb2RelativePatcherTest, BakerAndMethodCallInteraction) {
1328 // During development, there was a `DCHECK_LE(MaxNextOffset(), next_thunk.MaxNextOffset());`
1329 // in `ArmBaseRelativePatcher::ThunkData::MakeSpaceBefore()` which does not necessarily
1330 // hold when we're reserving thunks of different sizes. This test exposes the situation
1331 // by using Baker thunks and a method call thunk.
1332
1333 // Add a method call patch that can reach to method 1 offset + 16MiB.
1334 uint32_t method_idx = 0u;
1335 constexpr size_t kMethodCallLiteralOffset = 2u;
1336 constexpr uint32_t kMissingMethodIdx = 2u;
1337 const std::vector<uint8_t> raw_code1 = RawCode({kNopInsn, kBlPlus0});
1338 const LinkerPatch method1_patches[] = {
1339 LinkerPatch::RelativeCodePatch(kMethodCallLiteralOffset, nullptr, 2u),
1340 };
1341 ArrayRef<const uint8_t> code1(raw_code1);
1342 ++method_idx;
1343 AddCompiledMethod(MethodRef(1u), code1, ArrayRef<const LinkerPatch>(method1_patches));
1344
1345 // Skip kMissingMethodIdx.
1346 ++method_idx;
1347 ASSERT_EQ(kMissingMethodIdx, method_idx);
1348 // Add a method with the right size that the method code for the next one starts 1MiB
1349 // after code for method 1.
1350 size_t filler_size =
1351 1 * MB - RoundUp(raw_code1.size() + sizeof(OatQuickMethodHeader), kArmCodeAlignment)
1352 - sizeof(OatQuickMethodHeader);
1353 std::vector<uint8_t> filler_code = GenNops(filler_size / 2u);
1354 ++method_idx;
1355 AddCompiledMethod(MethodRef(method_idx), ArrayRef<const uint8_t>(filler_code));
1356 // Add 14 methods with 1MiB code+header, making the code for the next method start 1MiB
1357 // before the currently scheduled MaxNextOffset() for the method call thunk.
1358 for (uint32_t i = 0; i != 14; ++i) {
1359 filler_size = 1 * MB - sizeof(OatQuickMethodHeader);
1360 filler_code = GenNops(filler_size / 2u);
1361 ++method_idx;
1362 AddCompiledMethod(MethodRef(method_idx), ArrayRef<const uint8_t>(filler_code));
1363 }
1364
1365 // Add 2 Baker GC root patches to the last method, one that would allow the thunk at
1366 // 1MiB + kArmCodeAlignment, i.e. kArmCodeAlignment after the method call thunk, and the
1367 // second that needs it kArmCodeAlignment after that. Given the size of the GC root thunk
1368 // is more than the space required by the method call thunk plus kArmCodeAlignment,
1369 // this pushes the first GC root thunk's pending MaxNextOffset() before the method call
1370 // thunk's pending MaxNextOffset() which needs to be adjusted.
1371 ASSERT_LT(RoundUp(CompileMethodCallThunk().size(), kArmCodeAlignment) + kArmCodeAlignment,
1372 CompileBakerGcRootThunk(/* root_reg */ 0, /* narrow */ false).size());
1373 static_assert(kArmCodeAlignment == 8, "Code below assumes kArmCodeAlignment == 8");
1374 constexpr size_t kBakerLiteralOffset1 = kArmCodeAlignment + 2u - kPcAdjustment;
1375 constexpr size_t kBakerLiteralOffset2 = kBakerLiteralOffset1 + kArmCodeAlignment;
1376 // Use offset = 0, base_reg = 0, the LDR is simply `kLdrWInsn | (root_reg << 12)`.
1377 const uint32_t ldr1 = kLdrWInsn | (/* root_reg */ 1 << 12);
1378 const uint32_t ldr2 = kLdrWInsn | (/* root_reg */ 2 << 12);
1379 const std::vector<uint8_t> last_method_raw_code = RawCode({
1380 kNopInsn, // Padding before first GC root read barrier.
1381 ldr1, kBneWPlus0, // First GC root LDR with read barrier.
1382 ldr2, kBneWPlus0, // Second GC root LDR with read barrier.
1383 });
1384 uint32_t encoded_data1 = EncodeBakerReadBarrierGcRootData(/* root_reg */ 1, /* narrow */ false);
1385 uint32_t encoded_data2 = EncodeBakerReadBarrierGcRootData(/* root_reg */ 2, /* narrow */ false);
1386 const LinkerPatch last_method_patches[] = {
1387 LinkerPatch::BakerReadBarrierBranchPatch(kBakerLiteralOffset1, encoded_data1),
1388 LinkerPatch::BakerReadBarrierBranchPatch(kBakerLiteralOffset2, encoded_data2),
1389 };
1390 ++method_idx;
1391 AddCompiledMethod(MethodRef(method_idx),
1392 ArrayRef<const uint8_t>(last_method_raw_code),
1393 ArrayRef<const LinkerPatch>(last_method_patches));
1394
1395 // The main purpose of the test is to check that Link() does not cause a crash.
1396 Link();
1397
1398 ASSERT_EQ(15 * MB, GetMethodOffset(method_idx) - GetMethodOffset(1u));
1399 }
1400
1401 } // namespace linker
1402 } // namespace art