summaryrefslogtreecommitdiff
path: root/apps/plugins/puzzles/rbmalloc.c
diff options
context:
space:
mode:
Diffstat (limited to 'apps/plugins/puzzles/rbmalloc.c')
-rw-r--r--apps/plugins/puzzles/rbmalloc.c93
1 files changed, 93 insertions, 0 deletions
diff --git a/apps/plugins/puzzles/rbmalloc.c b/apps/plugins/puzzles/rbmalloc.c
new file mode 100644
index 0000000000..5bf914ff87
--- /dev/null
+++ b/apps/plugins/puzzles/rbmalloc.c
@@ -0,0 +1,93 @@
1/*
2 * malloc.c: safe wrappers around malloc, realloc, free, strdup
3 */
4
5#include <stdlib.h>
6#include <string.h>
7#include "src/puzzles.h"
8
9/*
10 * smalloc should guarantee to return a useful pointer - Halibut
11 * can do nothing except die when it's out of memory anyway.
12 */
13
14int allocs = 0;
15int frees = 0;
16
17bool audiobuf_available =
18#ifndef COMBINED
19 true;
20#else
21 false;
22#endif
23
24static bool grab_audiobuf(void)
25{
26 if(!audiobuf_available)
27 return false;
28
29 if(rb->audio_status())
30 rb->audio_stop();
31
32 size_t sz, junk;
33 void *audiobuf = rb->plugin_get_audio_buffer(&sz);
34 extern char *giant_buffer;
35
36 add_new_area(audiobuf, sz, giant_buffer);
37 audiobuf_available = false;
38 return true;
39}
40
41void *smalloc(size_t size) {
42 void *p;
43 p = malloc(size);
44 LOGF("allocs: %d", ++allocs);
45 if (!p)
46 {
47 if(grab_audiobuf())
48 return smalloc(size);
49 fatal("out of memory");
50 }
51 return p;
52}
53
54/*
55 * sfree should guaranteeably deal gracefully with freeing NULL
56 */
57void sfree(void *p) {
58 if (p) {
59 ++frees;
60 LOGF("frees: %d, total outstanding: %d", frees, allocs - frees);
61 free(p);
62 }
63}
64
65/*
66 * srealloc should guaranteeably be able to realloc NULL
67 */
68void *srealloc(void *p, size_t size) {
69 void *q;
70 if (p) {
71 q = realloc(p, size);
72 } else {
73 LOGF("allocs: %d", ++allocs);
74 q = malloc(size);
75 }
76 if (!q)
77 {
78 if(grab_audiobuf())
79 return srealloc(p, size);
80 fatal("out of memory");
81 }
82 return q;
83}
84
85/*
86 * dupstr is like strdup, but with the never-return-NULL property
87 * of smalloc (and also reliably defined in all environments :-)
88 */
89char *dupstr(const char *s) {
90 char *r = smalloc(1+strlen(s));
91 strcpy(r,s);
92 return r;
93}