xref: /aosp_15_r20/external/llvm-libc/test/src/sys/mman/linux/madvise_test.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Unittests for madvise ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/errno/libc_errno.h"
10 #include "src/sys/mman/madvise.h"
11 #include "src/sys/mman/mmap.h"
12 #include "src/sys/mman/munmap.h"
13 #include "test/UnitTest/ErrnoSetterMatcher.h"
14 #include "test/UnitTest/Test.h"
15 
16 #include <sys/mman.h>
17 
18 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
19 using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
20 
TEST(LlvmLibcMadviseTest,NoError)21 TEST(LlvmLibcMadviseTest, NoError) {
22   size_t alloc_size = 128;
23   LIBC_NAMESPACE::libc_errno = 0;
24   void *addr = LIBC_NAMESPACE::mmap(nullptr, alloc_size, PROT_READ,
25                                     MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
26   ASSERT_ERRNO_SUCCESS();
27   EXPECT_NE(addr, MAP_FAILED);
28 
29   EXPECT_THAT(LIBC_NAMESPACE::madvise(addr, alloc_size, MADV_RANDOM),
30               Succeeds());
31 
32   int *array = reinterpret_cast<int *>(addr);
33   // Reading from the memory should not crash the test.
34   // Since we used the MAP_ANONYMOUS flag, the contents of the newly
35   // allocated memory should be initialized to zero.
36   EXPECT_EQ(array[0], 0);
37   EXPECT_THAT(LIBC_NAMESPACE::munmap(addr, alloc_size), Succeeds());
38 }
39 
TEST(LlvmLibcMadviseTest,Error_BadPtr)40 TEST(LlvmLibcMadviseTest, Error_BadPtr) {
41   LIBC_NAMESPACE::libc_errno = 0;
42   EXPECT_THAT(LIBC_NAMESPACE::madvise(nullptr, 8, MADV_SEQUENTIAL),
43               Fails(ENOMEM));
44 }
45