]> git.saurik.com Git - apple/xnu.git/blob - tests/safe_allocation_src/test_utils.h
xnu-7195.101.1.tar.gz
[apple/xnu.git] / tests / safe_allocation_src / test_utils.h
1 #ifndef TESTS_SAFE_ALLOCATION_TEST_UTILS_H
2 #define TESTS_SAFE_ALLOCATION_TEST_UTILS_H
3
4 #include <libkern/c++/bounded_ptr.h>
5 #include <libkern/c++/safe_allocation.h>
6 #include <darwintest_utils.h>
7 #include <cassert>
8 #include <cstddef>
9 #include <cstdlib>
10
11 namespace {
12 struct assert_trapping_policy {
13 static void
14 trap(char const*)
15 {
16 assert(false);
17 }
18 };
19
20 struct malloc_allocator {
21 static void*
22 allocate(size_t n)
23 {
24 return std::malloc(n);
25 }
26
27 static void
28 deallocate(void* p, size_t n)
29 {
30 std::free(p);
31 }
32 };
33
34 struct tracking_allocator {
35 static void
36 reset()
37 {
38 allocated_size = 0;
39 deallocated_size = 0;
40 did_allocate = false;
41 did_deallocate = false;
42 }
43 static std::size_t allocated_size;
44 static std::size_t deallocated_size;
45 static bool did_allocate;
46 static bool did_deallocate;
47
48 static void*
49 allocate(std::size_t n)
50 {
51 did_allocate = true;
52 allocated_size = n;
53 return std::malloc(n);
54 }
55
56 static void
57 deallocate(void* p, std::size_t n)
58 {
59 did_deallocate = true;
60 deallocated_size = n;
61 std::free(p);
62 }
63 };
64
65 std::size_t tracking_allocator::allocated_size = 0;
66 std::size_t tracking_allocator::deallocated_size = 0;
67 bool tracking_allocator::did_allocate = false;
68 bool tracking_allocator::did_deallocate = false;
69
70 struct tracking_trapping_policy {
71 static void
72 reset()
73 {
74 did_trap = false;
75 }
76 static bool did_trap;
77 static void
78 trap(char const*)
79 {
80 did_trap = true;
81 }
82 };
83 bool tracking_trapping_policy::did_trap = false;
84
85 template <typename T>
86 using test_safe_allocation = libkern::safe_allocation<T, malloc_allocator, assert_trapping_policy>;
87
88 template <typename T>
89 using tracked_safe_allocation = libkern::safe_allocation<T, tracking_allocator, assert_trapping_policy>;
90
91 template <typename T>
92 using test_bounded_ptr = libkern::bounded_ptr<T, assert_trapping_policy>;
93 } // end anonymous namespace
94
95 #define CHECK(...) T_ASSERT_TRUE((__VA_ARGS__), # __VA_ARGS__)
96
97 #endif // !TESTS_SAFE_ALLOCATION_TEST_UTILS_H