]> code.delx.au - pulseaudio/blob - polyp/xmalloc.c
add simple hardware auto detection module
[pulseaudio] / polyp / xmalloc.c
1 /* $Id$ */
2
3 /***
4 This file is part of polypaudio.
5
6 polypaudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published
8 by the Free Software Foundation; either version 2 of the License,
9 or (at your option) any later version.
10
11 polypaudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with polypaudio; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19 USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <assert.h>
29 #include <unistd.h>
30
31 #include "memory.h"
32 #include "util.h"
33 #include "xmalloc.h"
34 #include "gccmacro.h"
35
36 /* Make sure not to allocate more than this much memory. */
37 #define MAX_ALLOC_SIZE (1024*1024*20) /* 20MB */
38
39 /* #undef malloc */
40 /* #undef free */
41 /* #undef realloc */
42 /* #undef strndup */
43 /* #undef strdup */
44
45 static void oom(void) PA_GCC_NORETURN;
46
47 /** called in case of an OOM situation. Prints an error message and
48 * exits */
49 static void oom(void) {
50 static const char e[] = "Not enough memory\n";
51 pa_loop_write(STDERR_FILENO, e, sizeof(e)-1);
52 #ifdef SIGQUIT
53 raise(SIGQUIT);
54 #endif
55 _exit(1);
56 }
57
58 void* pa_xmalloc(size_t size) {
59 void *p;
60 assert(size > 0);
61 assert(size < MAX_ALLOC_SIZE);
62
63 if (!(p = malloc(size)))
64 oom();
65
66 return p;
67 }
68
69 void* pa_xmalloc0(size_t size) {
70 void *p;
71 assert(size > 0);
72 assert(size < MAX_ALLOC_SIZE);
73
74 if (!(p = calloc(1, size)))
75 oom();
76
77 return p;
78 }
79
80 void *pa_xrealloc(void *ptr, size_t size) {
81 void *p;
82 assert(size > 0);
83 assert(size < MAX_ALLOC_SIZE);
84
85 if (!(p = realloc(ptr, size)))
86 oom();
87 return p;
88 }
89
90 void* pa_xmemdup(const void *p, size_t l) {
91 if (!p)
92 return NULL;
93 else {
94 char *r = pa_xmalloc(l);
95 memcpy(r, p, l);
96 return r;
97 }
98 }
99
100 char *pa_xstrdup(const char *s) {
101 if (!s)
102 return NULL;
103
104 return pa_xmemdup(s, strlen(s)+1);
105 }
106
107 char *pa_xstrndup(const char *s, size_t l) {
108 if (!s)
109 return NULL;
110 else {
111 char *r;
112 size_t t = strlen(s);
113
114 if (t > l)
115 t = l;
116
117 r = pa_xmemdup(s, t+1);
118 r[t] = 0;
119 return r;
120 }
121 }
122