5 * Copyright 2006-2009 Wincent Colaiuta.
13 /*! Wrappers for memory allocation functions which can be used to simulate out-of-memory conditions for testing purposes. There are two ways of simulating failures:
15 1. set an environment variable to provoke failures (other vars can be used to control when: always, randomly etc)
16 2. use macros to pass an extra "forced failure" parameter
18 Environment variables:
20 WOMallocFailAlways set to 1 to always fail, 0 to not force failure
22 WOMallocFailRandomly (set to value between 0 and 1 indicating desired frequency of failures; 0 is equivalent to no forced failures, 1 is equivalent to "fail always")
24 If set WOMallocFailAlways overrides WOMallocFailRandomly
29 #pragma mark Variadic macros
34 These variadic macros wrap the wrapper functions in such a way that the caller can optionally specify an extra "true" or "false" parameter to force an allocation to fail for testing purposes. One way to do this would be to code in C++ or Objective-C++ and overload the functions so as to provide alternative versions with and without the forced failure flags. An alternative approach has been taken here and that is to use variadic macros and some helper functions which do not require function overloading and can therefore be used in normal C code.
39 #define WO_MALLOC(size, ...) WOMallocFailv(size, ## __VAR_ARGS__)
41 #define WO_CALLOC(count, size, ...) WOCallocFailv\
42 (count, size, ## __VAR_ARGS__)
44 #define WO_VALLOC(size, ...) WOVallocFailv(size, ## __VAR_ARGS__)
46 #define WO_REALLOC(ptr, size, ...) WOReallocFailv\
47 (ptr, size, ## __VAR_ARGS__)
49 #define WO_REALLOCF(ptr, size, ...) WOReallocfFailv\
50 (ptr, size, ## __VAR_ARGS__)
55 #pragma mark Base wrapper functions
57 void * WOMalloc(size_t size);
59 void * WOCalloc(size_t count, size_t size);
61 void * WOValloc(size_t size);
63 void * WORealloc(void *ptr, size_t size);
65 void * WOReallocf(void *ptr, size_t size);
68 #pragma mark Wrapper functions with forced failure control
70 void * WOMallocFail(size_t size, _Bool fail);
72 void * WOCallocFail(size_t count, size_t size, _Bool fail);
74 void * WOVallocFail(size_t size, _Bool fail);
76 void * WOReallocFail(void *ptr, size_t size, _Bool fail);
78 void * WOReallocfFail(void *ptr, size_t size, _Bool fail);
81 #pragma mark Variadic helper function prototypes
83 void * WOMallocFailv(size_t size, ...);
85 void * WOCallocFailv(size_t count, size_t size, ...);
87 void * WOVallocFailv(size_t size, ...);
89 void * WOReallocFailv(void *ptr, size_t size, ...);
91 void * WOReallocfFailv(void *ptr, size_t size, ...);