• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "malloc_wrappers.h"
2 #include <stdint.h>
3 #include <assert.h>
4 #include <string.h>
5 
6 static size_t alloc_count = 0;
7 
8 /* Allocate memory and place check values before and after. */
malloc_with_check(size_t size)9 void* malloc_with_check(size_t size)
10 {
11     size_t size32 = (size + 3) / 4 + 3;
12     uint32_t *buf = malloc(size32 * sizeof(uint32_t));
13     buf[0] = size32;
14     buf[1] = 0xDEADBEEF;
15     buf[size32 - 1] = 0xBADBAD;
16     return buf + 2;
17 }
18 
19 /* Free memory allocated with malloc_with_check() and do the checks. */
free_with_check(void * mem)20 void free_with_check(void *mem)
21 {
22     uint32_t *buf = (uint32_t*)mem - 2;
23     assert(buf[1] == 0xDEADBEEF);
24     assert(buf[buf[0] - 1] == 0xBADBAD);
25     free(buf);
26 }
27 
28 /* Track memory usage */
counting_realloc(void * ptr,size_t size)29 void* counting_realloc(void *ptr, size_t size)
30 {
31     /* Don't allocate crazy amounts of RAM when fuzzing */
32     if (size > 1000000)
33         return NULL;
34 
35     if (!ptr && size)
36         alloc_count++;
37 
38     return realloc(ptr, size);
39 }
40 
counting_free(void * ptr)41 void counting_free(void *ptr)
42 {
43     if (ptr)
44     {
45         assert(alloc_count > 0);
46         alloc_count--;
47         free(ptr);
48     }
49 }
50 
get_alloc_count()51 size_t get_alloc_count()
52 {
53     return alloc_count;
54 }
55