xref: /aosp_15_r20/system/core/libcutils/ashmem_base_test.cpp (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
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 <unistd.h>
20 
21 #include <android-base/mapped_file.h>
22 #include <android-base/unique_fd.h>
23 #include <cutils/ashmem.h>
24 
25 /*
26  * Tests in AshmemBaseTest are designed to run on Android as well as host
27  * platforms (Linux, Mac, Windows).
28  */
29 
30 #if defined(_WIN32)
getpagesize()31 static inline size_t getpagesize() {
32     return 4096;
33 }
34 #endif
35 
36 using android::base::unique_fd;
37 
TEST(AshmemBaseTest,BasicTest)38 TEST(AshmemBaseTest, BasicTest) {
39     const size_t size = getpagesize();
40     std::vector<uint8_t> data(size);
41     std::generate(data.begin(), data.end(), [n = 0]() mutable { return n++ & 0xFF; });
42 
43     unique_fd fd = unique_fd(ashmem_create_region(nullptr, size));
44     ASSERT_TRUE(fd >= 0);
45     ASSERT_TRUE(ashmem_valid(fd));
46     ASSERT_EQ(size, static_cast<size_t>(ashmem_get_size_region(fd)));
47 
48     std::unique_ptr<android::base::MappedFile> mapped =
49             android::base::MappedFile::FromFd(fd, 0, size, PROT_READ | PROT_WRITE);
50     EXPECT_TRUE(mapped.get() != nullptr);
51     void* region1 = mapped->data();
52     EXPECT_TRUE(region1 != nullptr);
53 
54     memcpy(region1, data.data(), size);
55     ASSERT_EQ(0, memcmp(region1, data.data(), size));
56 
57     std::unique_ptr<android::base::MappedFile> mapped2 =
58             android::base::MappedFile::FromFd(fd, 0, size, PROT_READ | PROT_WRITE);
59     EXPECT_TRUE(mapped2.get() != nullptr);
60     void* region2 = mapped2->data();
61     EXPECT_TRUE(region2 != nullptr);
62     ASSERT_EQ(0, memcmp(region2, data.data(), size));
63 }
64