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