xref: /openbsd-src/gnu/llvm/compiler-rt/lib/gwp_asan/tests/basic.cpp (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 //===-- basic.cpp -----------------------------------------------*- C++ -*-===//
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 "gwp_asan/tests/harness.h"
10 
11 TEST_F(CustomGuardedPoolAllocator, BasicAllocation) {
12   InitNumSlots(1);
13   void *Ptr = GPA.allocate(1);
14   EXPECT_NE(nullptr, Ptr);
15   EXPECT_TRUE(GPA.pointerIsMine(Ptr));
16   EXPECT_EQ(1u, GPA.getSize(Ptr));
17   GPA.deallocate(Ptr);
18 }
19 
20 TEST_F(DefaultGuardedPoolAllocator, NullptrIsNotMine) {
21   EXPECT_FALSE(GPA.pointerIsMine(nullptr));
22 }
23 
24 TEST_F(CustomGuardedPoolAllocator, SizedAllocations) {
25   InitNumSlots(1);
26 
27   std::size_t MaxAllocSize = GPA.getAllocatorState()->maximumAllocationSize();
28   EXPECT_TRUE(MaxAllocSize > 0);
29 
30   for (unsigned AllocSize = 1; AllocSize <= MaxAllocSize; AllocSize <<= 1) {
31     void *Ptr = GPA.allocate(AllocSize);
32     EXPECT_NE(nullptr, Ptr);
33     EXPECT_TRUE(GPA.pointerIsMine(Ptr));
34     EXPECT_EQ(AllocSize, GPA.getSize(Ptr));
35     GPA.deallocate(Ptr);
36   }
37 }
38 
39 TEST_F(DefaultGuardedPoolAllocator, TooLargeAllocation) {
40   EXPECT_EQ(nullptr,
41             GPA.allocate(GPA.getAllocatorState()->maximumAllocationSize() + 1));
42 }
43 
44 TEST_F(CustomGuardedPoolAllocator, AllocAllSlots) {
45   constexpr unsigned kNumSlots = 128;
46   InitNumSlots(kNumSlots);
47   void *Ptrs[kNumSlots];
48   for (unsigned i = 0; i < kNumSlots; ++i) {
49     Ptrs[i] = GPA.allocate(1);
50     EXPECT_NE(nullptr, Ptrs[i]);
51     EXPECT_TRUE(GPA.pointerIsMine(Ptrs[i]));
52   }
53 
54   // This allocation should fail as all the slots are used.
55   void *Ptr = GPA.allocate(1);
56   EXPECT_EQ(nullptr, Ptr);
57   EXPECT_FALSE(GPA.pointerIsMine(nullptr));
58 
59   for (unsigned i = 0; i < kNumSlots; ++i)
60     GPA.deallocate(Ptrs[i]);
61 }
62