| /* | |
| * Copyright 2026 The Android Open Source Project | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| #include <gtest/gtest.h> | |
| #include <sys/mman.h> | |
| #include <fcntl.h> | |
| #include <unistd.h> | |
| #include <android-base/unique_fd.h> | |
| TEST(MemfdTest, sealWriteAndMmapRead) { | |
| android::base::unique_fd fd(memfd_create("test_memfd", MFD_CLOEXEC | MFD_ALLOW_SEALING)); | |
| ASSERT_GE(fd.get(), 0); | |
| size_t size = getpagesize(); | |
| ASSERT_EQ(ftruncate(fd.get(), size), 0); | |
| // Write something to it | |
| char data[] = "test data"; | |
| ASSERT_EQ(write(fd.get(), data, sizeof(data)), sizeof(data)); | |
| // Seal it | |
| ASSERT_EQ(fcntl(fd.get(), F_ADD_SEALS, F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_WRITE), 0); | |
| // Mmap as read-only, shared | |
| void* addr = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd.get(), 0); | |
| ASSERT_NE(addr, MAP_FAILED); | |
| // Verify content | |
| EXPECT_STREQ(static_cast<char*>(addr), data); | |
| ASSERT_EQ(munmap(addr, size), 0); | |
| } |