- dont run regex test until mesh_new is made default
[oweals/gnunet.git] / src / util / common_allocation.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2005, 2006 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/common_allocation.c
23  * @brief wrapper around malloc/free
24  * @author Christian Grothoff
25  */
26
27 #include "platform.h"
28 #include "gnunet_common.h"
29
30 #define LOG(kind,...) GNUNET_log_from (kind, "util",__VA_ARGS__)
31
32 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
33
34 #ifndef INT_MAX
35 #define INT_MAX 0x7FFFFFFF
36 #endif
37
38 #if 0
39 #define W32_MEM_LIMIT 200000000
40 #endif
41
42 #ifdef W32_MEM_LIMIT
43 static LONG mem_used = 0;
44 #endif
45
46 /**
47  * Allocate memory. Checks the return value, aborts if no more
48  * memory is available.
49  *
50  * @param size how many bytes of memory to allocate, do NOT use
51  *  this function (or GNUNET_malloc) to allocate more than several MB
52  *  of memory, if you are possibly needing a very large chunk use
53  *  GNUNET_xmalloc_unchecked_ instead.
54  * @param filename where in the code was the call to GNUNET_malloc
55  * @param linenumber where in the code was the call to GNUNET_malloc
56  * @return pointer to size bytes of memory
57  */
58 void *
59 GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber)
60 {
61   void *ret;
62
63   /* As a security precaution, we generally do not allow very large
64    * allocations using the default 'GNUNET_malloc' macro */
65   GNUNET_assert_at (size <= GNUNET_MAX_MALLOC_CHECKED, filename, linenumber);
66   ret = GNUNET_xmalloc_unchecked_ (size, filename, linenumber);
67   if (ret == NULL)
68   {
69     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "malloc");
70     GNUNET_abort ();
71   }
72   return ret;
73 }
74
75
76 /**
77  * Allocate and initialize memory. Checks the return value, aborts if no more
78  * memory is available.  Don't use GNUNET_xmemdup_ directly. Use the
79  * GNUNET_memdup macro.
80  *
81  * @param buf buffer to initialize from (must contain size bytes)
82  * @param size number of bytes to allocate
83  * @param filename where is this call being made (for debugging)
84  * @param linenumber line where this call is being made (for debugging)
85  * @return allocated memory, never NULL
86  */
87 void *
88 GNUNET_xmemdup_ (const void *buf, size_t size, const char *filename,
89                  int linenumber)
90 {
91   void *ret;
92
93   /* As a security precaution, we generally do not allow very large
94    * allocations here */
95   GNUNET_assert_at (size <= GNUNET_MAX_MALLOC_CHECKED, filename, linenumber);
96 #ifdef W32_MEM_LIMIT
97   size += sizeof (size_t);
98   if (mem_used + size > W32_MEM_LIMIT)
99     return NULL;
100 #endif
101   GNUNET_assert_at (size < INT_MAX, filename, linenumber);
102   ret = malloc (size);
103   if (ret == NULL)
104   {
105     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "malloc");
106     GNUNET_abort ();
107   }
108 #ifdef W32_MEM_LIMIT
109   *((size_t *) ret) = size;
110   ret = &((size_t *) ret)[1];
111   mem_used += size;
112 #endif
113   memcpy (ret, buf, size);
114   return ret;
115 }
116
117
118
119 /**
120  * Wrapper around malloc. Allocates size bytes of memory.
121  * The memory will be zero'ed out.
122  *
123  * @param size the number of bytes to allocate
124  * @param filename where in the code was the call to GNUNET_malloc_large
125  * @param linenumber where in the code was the call to GNUNET_malloc_large
126  * @return pointer to size bytes of memory, NULL if we do not have enough memory
127  */
128 void *
129 GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber)
130 {
131   void *result;
132
133 #ifdef W32_MEM_LIMIT
134   size += sizeof (size_t);
135   if (mem_used + size > W32_MEM_LIMIT)
136     return NULL;
137 #endif
138
139   result = malloc (size);
140   if (result == NULL)
141     return NULL;
142   memset (result, 0, size);
143
144 #ifdef W32_MEM_LIMIT
145   *((size_t *) result) = size;
146   result = &((size_t *) result)[1];
147   mem_used += size;
148 #endif
149
150   return result;
151 }
152
153
154 /**
155  * Reallocate memory. Checks the return value, aborts if no more
156  * memory is available.
157  *
158  * @param ptr the pointer to reallocate
159  * @param n how many bytes of memory to allocate
160  * @param filename where in the code was the call to GNUNET_realloc
161  * @param linenumber where in the code was the call to GNUNET_realloc
162  * @return pointer to size bytes of memory
163  */
164 void *
165 GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber)
166 {
167 #ifdef W32_MEM_LIMIT
168   n += sizeof (size_t);
169   ptr = &((size_t *) ptr)[-1];
170   mem_used = mem_used - *((size_t *) ptr) + n;
171 #endif
172   ptr = realloc (ptr, n);
173   if ((NULL == ptr) && (n > 0))
174   {
175     LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "realloc");
176     GNUNET_abort ();
177   }
178 #ifdef W32_MEM_LIMIT
179   ptr = &((size_t *) ptr)[1];
180 #endif
181   return ptr;
182 }
183
184
185 # if __BYTE_ORDER == __LITTLE_ENDIAN
186 #define BAADFOOD_STR "\x0D\xF0\xAD\xBA"
187 #endif
188 # if __BYTE_ORDER == __BIG_ENDIAN
189 #define BAADFOOD_STR "\xBA\xAD\xF0\x0D"
190 #endif
191
192 #if WINDOWS
193 #define MSIZE(p) _msize (p)
194 #endif
195 #if LINUX
196 /* FIXME: manpage claims that this function is a GNU extension,
197  * but googling shows that it is available on many platforms via
198  * inclusion of various headers. For now let's make it Linux-only.
199  */
200 #define MSIZE(p) malloc_usable_size (p)
201 #endif
202
203 /**
204  * Free memory. Merely a wrapper for the case that we
205  * want to keep track of allocations.
206  *
207  * @param ptr the pointer to free
208  * @param filename where in the code was the call to GNUNET_array_grow
209  * @param linenumber where in the code was the call to GNUNET_array_grow
210  */
211 void
212 GNUNET_xfree_ (void *ptr, const char *filename, int linenumber)
213 {
214   GNUNET_assert_at (ptr != NULL, filename, linenumber);
215 #ifdef W32_MEM_LIMIT
216   ptr = &((size_t *) ptr)[-1];
217   mem_used -= *((size_t *) ptr);
218 #endif
219 #if defined(MSIZE)
220 #if ENABLE_POISONING
221   {
222     size_t i;
223     char baadfood[5] = BAADFOOD_STR;
224     size_t s = MSIZE (ptr);
225     for (i = 0; i < s; i++)
226       ((char *) ptr)[i] = baadfood[i % 4];
227   }
228 #endif
229 #endif
230   free (ptr);
231 }
232
233 /**
234  * Dup a string (same semantics as strdup).
235  *
236  * @param str the string to dup
237  * @param filename where in the code was the call to GNUNET_strdup
238  * @param linenumber where in the code was the call to GNUNET_strdup
239  * @return strdup(str)
240  */
241 char *
242 GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber)
243 {
244   char *res;
245
246   GNUNET_assert_at (str != NULL, filename, linenumber);
247   res = GNUNET_xmalloc_ (strlen (str) + 1, filename, linenumber);
248   memcpy (res, str, strlen (str) + 1);
249   return res;
250 }
251
252
253 /**
254  * Dup partially a string (same semantics as strndup).
255  *
256  * @param str the string to dup
257  * @param len the length of the string to dup
258  * @param filename where in the code was the call to GNUNET_strndup
259  * @param linenumber where in the code was the call to GNUNET_strndup
260  * @return strndup(str,len)
261  */
262 char *
263 GNUNET_xstrndup_ (const char *str, size_t len, const char *filename,
264                   int linenumber)
265 {
266   char *res;
267
268   GNUNET_assert_at (str != NULL, filename, linenumber);
269   len = GNUNET_MIN (len, strlen (str));
270   res = GNUNET_xmalloc_ (len + 1, filename, linenumber);
271   memcpy (res, str, len);
272   /* res[len] = '\0'; 'malloc' zeros out anyway */
273   return res;
274 }
275
276
277 /**
278  * Grow an array.  Grows old by (*oldCount-newCount)*elementSize bytes
279  * and sets *oldCount to newCount.
280  *
281  * @param old address of the pointer to the array
282  *        *old may be NULL
283  * @param elementSize the size of the elements of the array
284  * @param oldCount address of the number of elements in the *old array
285  * @param newCount number of elements in the new array, may be 0
286  * @param filename where in the code was the call to GNUNET_array_grow
287  * @param linenumber where in the code was the call to GNUNET_array_grow
288  */
289 void
290 GNUNET_xgrow_ (void **old, size_t elementSize, unsigned int *oldCount,
291                unsigned int newCount, const char *filename, int linenumber)
292 {
293   void *tmp;
294   size_t size;
295
296   GNUNET_assert_at (INT_MAX / elementSize > newCount, filename, linenumber);
297   size = newCount * elementSize;
298   if (size == 0)
299   {
300     tmp = NULL;
301   }
302   else
303   {
304     tmp = GNUNET_xmalloc_ (size, filename, linenumber);
305     memset (tmp, 0, size);      /* client code should not rely on this, though... */
306     if (*oldCount > newCount)
307       *oldCount = newCount;     /* shrink is also allowed! */
308     memcpy (tmp, *old, elementSize * (*oldCount));
309   }
310
311   if (*old != NULL)
312   {
313     GNUNET_xfree_ (*old, filename, linenumber);
314   }
315   *old = tmp;
316   *oldCount = newCount;
317 }
318
319
320 /**
321  * Like asprintf, just portable.
322  *
323  * @param buf set to a buffer of sufficient size (allocated, caller must free)
324  * @param format format string (see printf, fprintf, etc.)
325  * @param ... data for format string
326  * @return number of bytes in "*buf" excluding 0-termination
327  */
328 int
329 GNUNET_asprintf (char **buf, const char *format, ...)
330 {
331   int ret;
332   va_list args;
333
334   va_start (args, format);
335   ret = VSNPRINTF (NULL, 0, format, args);
336   va_end (args);
337   *buf = GNUNET_malloc (ret + 1);
338   va_start (args, format);
339   ret = VSPRINTF (*buf, format, args);
340   va_end (args);
341   return ret;
342 }
343
344
345 /**
346  * Like snprintf, just aborts if the buffer is of insufficient size.
347  *
348  * @param buf pointer to buffer that is written to
349  * @param size number of bytes in buf
350  * @param format format strings
351  * @param ... data for format string
352  * @return number of bytes written to buf or negative value on error
353  */
354 int
355 GNUNET_snprintf (char *buf, size_t size, const char *format, ...)
356 {
357   int ret;
358   va_list args;
359
360   va_start (args, format);
361   ret = VSNPRINTF (buf, size, format, args);
362   va_end (args);
363   GNUNET_assert (ret <= size);
364   return ret;
365 }
366
367
368 /**
369  * Create a copy of the given message.
370  *
371  * @param msg message to copy
372  * @return duplicate of the message
373  */
374 struct GNUNET_MessageHeader *
375 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg)
376 {
377   struct GNUNET_MessageHeader *ret;
378   uint16_t msize;
379
380   msize = ntohs (msg->size);
381   GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
382   ret = GNUNET_malloc (msize);
383   memcpy (ret, msg, msize);
384   return ret;
385 }
386
387
388 /* end of common_allocation.c */