50 lines · cpp
1//===-- Unittests for posix_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-exception6//7//===----------------------------------------------------------------------===//8 9#include "src/sys/mman/mmap.h"10#include "src/sys/mman/munmap.h"11#include "src/sys/mman/posix_madvise.h"12#include "test/UnitTest/ErrnoCheckingTest.h"13#include "test/UnitTest/ErrnoSetterMatcher.h"14#include "test/UnitTest/Test.h"15 16#include <sys/mman.h>17 18using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Fails;19using LIBC_NAMESPACE::testing::ErrnoSetterMatcher::Succeeds;20using LlvmLibcPosixMadviseTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;21 22TEST_F(LlvmLibcPosixMadviseTest, NoError) {23 size_t alloc_size = 128;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_EQ(LIBC_NAMESPACE::posix_madvise(addr, alloc_size, POSIX_MADV_RANDOM),30 0);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 newly35 // 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 40TEST_F(LlvmLibcPosixMadviseTest, Error_BadPtr) {41 // posix_madvise is a no-op on DONTNEED, so it shouldn't fail even with the42 // nullptr.43 EXPECT_EQ(LIBC_NAMESPACE::posix_madvise(nullptr, 8, POSIX_MADV_DONTNEED), 0);44 45 // posix_madvise doesn't set errno, but the return value is actually the error46 // code.47 EXPECT_EQ(LIBC_NAMESPACE::posix_madvise(nullptr, 8, POSIX_MADV_SEQUENTIAL),48 ENOMEM);49}50