Path: blob/main/contrib/libcbor/test/test_allocator.c
39534 views
#include "test_allocator.h"12#ifdef HAS_EXECINFO3#include <execinfo.h>4#endif56// How many alloc calls we expect7int alloc_calls_expected;8// How many alloc calls we got9int alloc_calls;10// Array of booleans indicating whether to return a block or fail with NULL11call_expectation *expectations;1213void set_mock_malloc(int calls, ...) {14va_list args;15va_start(args, calls);16alloc_calls_expected = calls;17alloc_calls = 0;18expectations = calloc(calls, sizeof(expectations));19for (int i = 0; i < calls; i++) {20// Promotable types, baby21expectations[i] = va_arg(args, call_expectation);22}23va_end(args);24}2526void finalize_mock_malloc(void) {27assert_int_equal(alloc_calls, alloc_calls_expected);28free(expectations);29}3031void print_backtrace(void) {32#if HAS_EXECINFO33void *buffer[128];34int frames = backtrace(buffer, 128);35char **symbols = backtrace_symbols(buffer, frames);36// Skip this function and the caller37for (int i = 2; i < frames; ++i) {38printf("%s\n", symbols[i]);39}40free(symbols);41#endif42}4344void *instrumented_malloc(size_t size) {45if (alloc_calls >= alloc_calls_expected) {46goto error;47}4849if (expectations[alloc_calls] == MALLOC) {50alloc_calls++;51return malloc(size);52} else if (expectations[alloc_calls] == MALLOC_FAIL) {53alloc_calls++;54return NULL;55}5657error:58print_error(59"Unexpected call to malloc(%zu) at position %d of %d; expected %d\n",60size, alloc_calls, alloc_calls_expected,61alloc_calls < alloc_calls_expected ? expectations[alloc_calls] : -1);62print_backtrace();63fail();64return NULL;65}6667void *instrumented_realloc(void *ptr, size_t size) {68if (alloc_calls >= alloc_calls_expected) {69goto error;70}7172if (expectations[alloc_calls] == REALLOC) {73alloc_calls++;74return realloc(ptr, size);75} else if (expectations[alloc_calls] == REALLOC_FAIL) {76alloc_calls++;77return NULL;78}7980error:81print_error(82"Unexpected call to realloc(%zu) at position %d of %d; expected %d\n",83size, alloc_calls, alloc_calls_expected,84alloc_calls < alloc_calls_expected ? expectations[alloc_calls] : -1);85print_backtrace();86fail();87return NULL;88}899091