| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
#include <stdlib.h> |
| 31 |
#include <stdio.h> |
| 32 |
#include <stdarg.h> |
| 33 |
#include <string.h> |
| 34 |
|
| 35 |
#include "cil_log.h" |
| 36 |
|
| 37 |
__attribute__((noreturn)) void cil_default_mem_error_handler(void) |
| 38 |
{ |
| 39 |
cil_log(CIL_ERR, "Failed to allocate memory\n"); |
| 40 |
exit(1); |
| 41 |
} |
| 42 |
|
| 43 |
void (*cil_mem_error_handler)(void) = &cil_default_mem_error_handler; |
| 44 |
|
| 45 |
void cil_set_mem_error_handler(void (*handler)(void)) |
| 46 |
{ |
| 47 |
cil_mem_error_handler = handler; |
| 48 |
} |
| 49 |
|
| 50 |
void *cil_malloc(size_t size) |
| 51 |
{ |
| 52 |
void *mem = malloc(size); |
| 53 |
if (mem == NULL){ |
| 54 |
if (size == 0) { |
| 55 |
return NULL; |
| 56 |
} |
| 57 |
(*cil_mem_error_handler)(); |
| 58 |
} |
| 59 |
|
| 60 |
return mem; |
| 61 |
} |
| 62 |
|
| 63 |
void *cil_calloc(size_t num_elements, size_t element_size) |
| 64 |
{ |
| 65 |
void *mem = calloc(num_elements, element_size); |
| 66 |
if (mem == NULL){ |
| 67 |
(*cil_mem_error_handler)(); |
| 68 |
} |
| 69 |
|
| 70 |
return mem; |
| 71 |
} |
| 72 |
|
| 73 |
void *cil_realloc(void *ptr, size_t size) |
| 74 |
{ |
| 75 |
void *mem = realloc(ptr, size); |
| 76 |
if (mem == NULL){ |
| 77 |
if (size == 0) { |
| 78 |
return NULL; |
| 79 |
} |
| 80 |
(*cil_mem_error_handler)(); |
| 81 |
} |
| 82 |
|
| 83 |
return mem; |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
char *cil_strdup(const char *str) |
| 88 |
{ |
| 89 |
char *mem = NULL; |
| 90 |
|
| 91 |
if (str == NULL) { |
| 92 |
return NULL; |
| 93 |
} |
| 94 |
|
| 95 |
mem = strdup(str); |
| 96 |
if (mem == NULL) { |
| 97 |
(*cil_mem_error_handler)(); |
| 98 |
} |
| 99 |
|
| 100 |
return mem; |
| 101 |
} |
| 102 |
|
| 103 |
__attribute__ ((format (printf, 2, 3))) int cil_asprintf(char **strp, const char *fmt, ...) |
| 104 |
{ |
| 105 |
int rc; |
| 106 |
va_list ap; |
| 107 |
|
| 108 |
va_start(ap, fmt); |
| 109 |
rc = vasprintf(strp, fmt, ap); |
| 110 |
va_end(ap); |
| 111 |
|
| 112 |
if (rc == -1) { |
| 113 |
(*cil_mem_error_handler)(); |
| 114 |
} |
| 115 |
|
| 116 |
return rc; |
| 117 |
} |