185c70da7SMichael Jones //===-- Unittests for madvise ---------------------------------------------===//
285c70da7SMichael Jones //
385c70da7SMichael Jones // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
485c70da7SMichael Jones // See https://llvm.org/LICENSE.txt for license information.
585c70da7SMichael Jones // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
685c70da7SMichael Jones //
785c70da7SMichael Jones //===----------------------------------------------------------------------===//
885c70da7SMichael Jones
940c443e2SSiva Chandra Reddy #include "src/errno/libc_errno.h"
1085c70da7SMichael Jones #include "src/sys/mman/madvise.h"
1185c70da7SMichael Jones #include "src/sys/mman/mmap.h"
1285c70da7SMichael Jones #include "src/sys/mman/munmap.h"
134f1fe19dSSiva Chandra Reddy #include "test/UnitTest/ErrnoSetterMatcher.h"
14af1315c2SSiva Chandra Reddy #include "test/UnitTest/Test.h"
1585c70da7SMichael Jones
1685c70da7SMichael Jones #include <sys/mman.h>
1785c70da7SMichael Jones
18b6bc9d72SGuillaume Chatelet using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;
19b6bc9d72SGuillaume Chatelet using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;
2085c70da7SMichael Jones
TEST(LlvmLibcMadviseTest,NoError)2185c70da7SMichael Jones TEST(LlvmLibcMadviseTest, NoError) {
2285c70da7SMichael Jones size_t alloc_size = 128;
23*3eb1e6d8Smichaelrj-google LIBC_NAMESPACE::libc_errno = 0;
24b6bc9d72SGuillaume Chatelet void *addr = LIBC_NAMESPACE::mmap(nullptr, alloc_size, PROT_READ,
2585c70da7SMichael Jones MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
2628699e38Slntue ASSERT_ERRNO_SUCCESS();
2785c70da7SMichael Jones EXPECT_NE(addr, MAP_FAILED);
2885c70da7SMichael Jones
29b6bc9d72SGuillaume Chatelet EXPECT_THAT(LIBC_NAMESPACE::madvise(addr, alloc_size, MADV_RANDOM),
30b6bc9d72SGuillaume Chatelet Succeeds());
3185c70da7SMichael Jones
3285c70da7SMichael Jones int *array = reinterpret_cast<int *>(addr);
3385c70da7SMichael Jones // Reading from the memory should not crash the test.
3485c70da7SMichael Jones // Since we used the MAP_ANONYMOUS flag, the contents of the newly
3585c70da7SMichael Jones // allocated memory should be initialized to zero.
3685c70da7SMichael Jones EXPECT_EQ(array[0], 0);
37b6bc9d72SGuillaume Chatelet EXPECT_THAT(LIBC_NAMESPACE::munmap(addr, alloc_size), Succeeds());
3885c70da7SMichael Jones }
3985c70da7SMichael Jones
TEST(LlvmLibcMadviseTest,Error_BadPtr)4085c70da7SMichael Jones TEST(LlvmLibcMadviseTest, Error_BadPtr) {
41*3eb1e6d8Smichaelrj-google LIBC_NAMESPACE::libc_errno = 0;
42b6bc9d72SGuillaume Chatelet EXPECT_THAT(LIBC_NAMESPACE::madvise(nullptr, 8, MADV_SEQUENTIAL),
43b6bc9d72SGuillaume Chatelet Fails(ENOMEM));
4485c70da7SMichael Jones }
45