1 /*
2  * Copyright (C) 2024 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 "gtest/gtest.h"
18 
19 #include <cstddef>
20 #include <cstring>
21 
22 #include "berberis/guest_state/get_cpu_state_opaque.h"
23 #include "berberis/guest_state/guest_state_arch.h"
24 #include "native_bridge_support/guest_state_accessor/accessor.h"
25 
26 namespace berberis {
27 
28 namespace {
29 
TEST(GetArm64CpuStateTest,TestValuesSet)30 TEST(GetArm64CpuStateTest, TestValuesSet) {
31   NativeBridgeGuestRegs guest_regs{.guest_arch = NATIVE_BRIDGE_ARCH_ARM64};
32   CPUState cpu_state;
33   for (size_t off = 0; off < sizeof(CPUState); off++) {
34     auto val = off % 199;  // 199 is prime to avoid regularly repeating values in registers
35     memcpy(reinterpret_cast<char*>(&cpu_state) + off, &val, 1);
36   }
37 
38   EXPECT_EQ(GetCpuState(&guest_regs, &cpu_state), 0);
39 
40   for (std::size_t i = 0; i < 31; i++) {
41     EXPECT_EQ(guest_regs.regs_arm64.x[i], cpu_state.x[i]);
42   }
43   for (std::size_t i = 0; i < 32; i++) {
44     EXPECT_EQ(guest_regs.regs_arm64.v[i], cpu_state.v[i]);
45   }
46   EXPECT_EQ(guest_regs.regs_arm64.sp, cpu_state.sp);
47   EXPECT_EQ(guest_regs.regs_arm64.ip, cpu_state.insn_addr);
48 }
49 
TEST(GetArm64CpuStateTest,TestErrorSize)50 TEST(GetArm64CpuStateTest, TestErrorSize) {
51   NativeBridgeGuestRegs guest_regs{.guest_arch = NATIVE_BRIDGE_ARCH_ARM64};
52   int res = LoadGuestStateRegisters(nullptr, sizeof(ThreadState) - 1, &guest_regs);
53   EXPECT_EQ(res, NATIVE_BRIDGE_GUEST_STATE_ACCESSOR_ERROR_INVALID_STATE);
54 }
55 
TEST(GetArm64CpuStateTest,TestErrorArch)56 TEST(GetArm64CpuStateTest, TestErrorArch) {
57   NativeBridgeGuestRegs guest_regs{.guest_arch = NATIVE_BRIDGE_ARCH_RISCV64};
58   CPUState cpu_state;
59   int res = GetCpuState(&guest_regs, &cpu_state);
60   EXPECT_EQ(res, NATIVE_BRIDGE_GUEST_STATE_ACCESSOR_ERROR_UNSUPPORTED_ARCH);
61 }
62 
63 }  // namespace
64 
65 }  // namespace berberis