• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Unittests for memset ----------------------------------------------===//
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 "memory_utils/memory_check_utils.h"
10 #include "src/__support/macros/properties/os.h" // LIBC_TARGET_OS_IS_LINUX
11 #include "src/string/memset.h"
12 #include "test/UnitTest/Test.h"
13 
14 #if !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
15 #include "memory_utils/protected_pages.h"
16 #endif // !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
17 
18 namespace LIBC_NAMESPACE {
19 
20 // Adapt CheckMemset signature to memset.
Adaptor(cpp::span<char> p1,uint8_t value,size_t size)21 static inline void Adaptor(cpp::span<char> p1, uint8_t value, size_t size) {
22   LIBC_NAMESPACE::memset(p1.begin(), value, size);
23 }
24 
TEST(LlvmLibcMemsetTest,SizeSweep)25 TEST(LlvmLibcMemsetTest, SizeSweep) {
26   static constexpr size_t kMaxSize = 400;
27   Buffer DstBuffer(kMaxSize);
28   for (size_t size = 0; size < kMaxSize; ++size) {
29     const char value = size % 10;
30     auto dst = DstBuffer.span().subspan(0, size);
31     ASSERT_TRUE((CheckMemset<Adaptor>(dst, value, size)));
32   }
33 }
34 
35 #if !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
36 
TEST(LlvmLibcMemsetTest,CheckAccess)37 TEST(LlvmLibcMemsetTest, CheckAccess) {
38   static constexpr size_t MAX_SIZE = 1024;
39   LIBC_ASSERT(MAX_SIZE < GetPageSize());
40   ProtectedPages pages;
41   const Page write_buffer = pages.GetPageA().WithAccess(PROT_WRITE);
42   const cpp::array<int, 2> fill_chars = {0, 0x7F};
43   for (int fill_char : fill_chars) {
44     for (size_t size = 0; size < MAX_SIZE; ++size) {
45       // We cross-check the function with two destinations.
46       // - The first of them (bottom) is always page aligned and faults when
47       //   accessing bytes before it.
48       // - The second one (top) is not necessarily aligned and faults when
49       //   accessing bytes after it.
50       uint8_t *destinations[2] = {write_buffer.bottom(size),
51                                   write_buffer.top(size)};
52       for (uint8_t *dst : destinations) {
53         LIBC_NAMESPACE::memset(dst, fill_char, size);
54       }
55     }
56   }
57 }
58 
59 #endif // !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
60 
61 } // namespace LIBC_NAMESPACE
62