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