xref: /freebsd/contrib/libcbor/test/test_allocator.h (revision b5b9517bfe394e55088f5a05882eabae7e9b7b29)
1 #ifndef TEST_ALLOCATOR_H_
2 #define TEST_ALLOCATOR_H_
3 
4 #include "assertions.h"
5 #include "cbor.h"
6 
7 // Harness for mocking `malloc` and `realloc`
8 
9 typedef enum call_expectation {
10   // Call malloc and return a pointer
11   MALLOC,
12   // Pretend call malloc, but return NULL (fail)
13   MALLOC_FAIL,
14   // Call realloc and return a pointer
15   REALLOC,
16   // Pretend call realloc, but return NULL (fail)
17   REALLOC_FAIL
18 } call_expectation;
19 
20 void set_mock_malloc(int calls, ...);
21 
22 void finalize_mock_malloc(void);
23 
24 void* instrumented_malloc(size_t size);
25 
26 void* instrumented_realloc(void* ptr, size_t size);
27 
28 #define WITH_MOCK_MALLOC(block, malloc_calls, ...)                    \
29   do {                                                                \
30     cbor_set_allocs(instrumented_malloc, instrumented_realloc, free); \
31     set_mock_malloc(malloc_calls, __VA_ARGS__);                       \
32     block;                                                            \
33     finalize_mock_malloc();                                           \
34     cbor_set_allocs(malloc, realloc, free);                           \
35   } while (0)
36 
37 #define WITH_FAILING_MALLOC(block) WITH_MOCK_MALLOC(block, 1, MALLOC_FAIL)
38 
39 #endif  // TEST_ALLOCATOR_H_
40