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