Fix installation of header files; add smalloc() and friends.
[eruntime.git] / src / smalloc.c
blob97d2c605601c128f825edcb31d3f2f59084c52f9
1 #include <assert.h>
2 #include <errno.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include "smalloc.h"
8 #ifndef errno
9 extern into errno;
10 #endif
12 #define __noreturn __attribute__((__noreturn__))
13 static void __noreturn oom (oom_data_t *);
15 /* {{{ void *smalloc() */
16 void *
17 smalloc (size_t size)
19 void *p = NULL;
20 oom_data_t oom_data;
22 assert(size);
23 if (!size)
25 size = 1;
26 fprintf(stderr, "WARNING: %s() called with size argument of '0', "
27 "falling back to '1'", __FUNCTION__);
30 p = malloc(size);
31 if (p)
32 return p;
34 oom_data.caller = OOM_SMALLOC;
35 oom_data.a.size = size;
36 oom(&oom_data);
38 /* }}} */
40 /* {{{ void sfree() */
41 void
42 sfree (void *ptr)
44 if (!ptr)
45 return;
46 free(ptr);
48 /* }}} */
50 /* {{{ static void oom() */
51 static void
52 oom (oom_data_t *oom_data)
54 char buf[8] = {0}; /* strlen("realloc") + 1 */
56 assert(oom_data);
58 if (oom_data->caller == OOM_SMALLOC)
60 strcpy(buf, "malloc");
61 buf[6] = '\0';
63 else
65 fprintf(stderr, "ERROR: %s() called with invalid ->caller '%d'",
66 __FUNCTION__, oom_data->caller);
67 abort();
70 fprintf(stderr, "ERROR: Out Of Memory Condition; %s() aborting",
71 __FUNCTION__);
73 if (*buf)
74 fprintf(stderr, "ERROR: %s\n", buf);
75 if (errno)
76 fprintf(stderr, "ERROR: %s (errno %d)", strerror(errno), errno);
78 fflush(stdout);
79 fflush(stderr);
81 abort();
83 /* }}} */
86 * vim: ts=8 sw=8 noet fdm=marker tw=80