A modern Music Player Daemon based on Rockbox open source high quality audio player
libadwaita
audio
rust
zig
deno
mpris
rockbox
mpd
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
17/* We don't load as an overlay anymore, so the audiobuf should always
18 * be available. */
19bool audiobuf_available = true;
20
21static bool grab_audiobuf(void)
22{
23 if(!audiobuf_available)
24 return false;
25
26 if(rb->audio_status())
27 rb->audio_stop();
28
29 size_t sz;
30
31 void *audiobuf = rb->plugin_get_audio_buffer(&sz);
32 extern char *giant_buffer;
33
34#if 0
35 /* Try aligning if tlsf crashes in add_new_area(). This is
36 * disabled now since things seem to work without it. */
37 void *old = audiobuf;
38
39 /* I'm sorry. */
40 audiobuf = (void*)((int) audiobuf & ~0xff);
41 audiobuf += 0x100;
42
43 sz -= audiobuf - old;
44#endif
45
46 add_new_area(audiobuf, sz, giant_buffer);
47 audiobuf_available = false;
48 return true;
49}
50
51void *smalloc(size_t size) {
52 void *p;
53 p = malloc(size);
54 //LOGF("allocs: %d", ++allocs);
55 if (!p)
56 {
57 if(grab_audiobuf())
58 return smalloc(size);
59 fatal("out of memory");
60 }
61 return p;
62}
63
64/*
65 * sfree should guaranteeably deal gracefully with freeing NULL
66 */
67void sfree(void *p) {
68 if (p) {
69 ++frees;
70 //LOGF("frees: %d, total outstanding: %d", frees, allocs - frees);
71 free(p);
72 }
73}
74
75/*
76 * srealloc should guaranteeably be able to realloc NULL
77 */
78void *srealloc(void *p, size_t size) {
79 void *q;
80 if (p) {
81 q = realloc(p, size);
82 } else {
83 //LOGF("allocs: %d", ++allocs);
84 q = malloc(size);
85 }
86 if (!q)
87 {
88 if(grab_audiobuf())
89 return srealloc(p, size);
90 fatal("out of memory");
91 }
92 return q;
93}
94
95/*
96 * dupstr is like strdup, but with the never-return-NULL property
97 * of smalloc (and also reliably defined in all environments :-)
98 */
99char *dupstr(const char *s) {
100 char *r = smalloc(1+strlen(s));
101 strcpy(r,s);
102 return r;
103}