xref: /aosp_15_r20/system/unwinding/libunwindstack/tests/MemoryLocalUnsafeTest.cpp (revision eb293b8f56ee8303637c5595cfcdeef8039e85c6)
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 <stdint.h>
18 #include <string.h>
19 #include <sys/mman.h>
20 
21 #include <vector>
22 
23 #include <android-base/silent_death_test.h>
24 #include <gtest/gtest.h>
25 
26 #include "MemoryLocalUnsafe.h"
27 
28 namespace unwindstack {
29 
TEST(MemoryLocalUnsafeTest,read_smoke)30 TEST(MemoryLocalUnsafeTest, read_smoke) {
31   std::vector<uint8_t> src(1024);
32   memset(src.data(), 0x4c, 1024);
33 
34   auto local = Memory::CreateProcessMemoryLocalUnsafe();
35 
36   std::vector<uint8_t> dst(1024);
37   ASSERT_TRUE(local->ReadFully(reinterpret_cast<uint64_t>(src.data()), dst.data(), 1024));
38   ASSERT_EQ(0, memcmp(src.data(), dst.data(), 1024));
39   for (size_t i = 0; i < 1024; i++) {
40     ASSERT_EQ(0x4cU, dst[i]);
41   }
42 
43   memset(src.data(), 0x23, 512);
44   ASSERT_TRUE(local->ReadFully(reinterpret_cast<uint64_t>(src.data()), dst.data(), 1024));
45   ASSERT_EQ(0, memcmp(src.data(), dst.data(), 1024));
46   for (size_t i = 0; i < 512; i++) {
47     ASSERT_EQ(0x23U, dst[i]);
48   }
49   for (size_t i = 512; i < 1024; i++) {
50     ASSERT_EQ(0x4cU, dst[i]);
51   }
52 }
53 
54 using MemoryLocalUnsafeDeathTest = SilentDeathTest;
TEST_F(MemoryLocalUnsafeDeathTest,read_crash)55 TEST_F(MemoryLocalUnsafeDeathTest, read_crash) {
56   void* mapping =
57       mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
58   ASSERT_NE(MAP_FAILED, mapping);
59 
60   mprotect(mapping, getpagesize(), PROT_NONE);
61 
62   auto local = Memory::CreateProcessMemoryLocalUnsafe();
63   std::vector<uint8_t> buffer(100);
64   ASSERT_DEATH(local->Read(reinterpret_cast<uint64_t>(mapping), buffer.data(), buffer.size()), "");
65 }
66 
67 }  // namespace unwindstack
68