2 This file is part of GNUnet.
3 Copyright (C) 2001, 2002, 2003, 2005, 2006 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version.
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 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
22 * @file util/common_allocation.c
23 * @brief wrapper around malloc/free
24 * @author Christian Grothoff
27 #include "gnunet_crypto_lib.h"
31 #if HAVE_MALLOC_MALLOC_H
32 #include <malloc/malloc.h>
35 #define LOG(kind,...) GNUNET_log_from (kind, "util-common-allocation",__VA_ARGS__)
37 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-common-allocation", syscall)
40 #define INT_MAX 0x7FFFFFFF
44 #define W32_MEM_LIMIT 200000000
48 static LONG mem_used = 0;
52 * Allocate memory. Checks the return value, aborts if no more
53 * memory is available.
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
64 GNUNET_xmalloc_ (size_t size,
70 /* As a security precaution, we generally do not allow very large
71 * allocations using the default 'GNUNET_malloc()' macro */
72 GNUNET_assert_at (size <= GNUNET_MAX_MALLOC_CHECKED,
75 ret = GNUNET_xmalloc_unchecked_ (size,
80 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
89 * Allocate memory for a two dimensional array in one block
90 * and set up pointers. Aborts if no more memory is available.
91 * Don't use GNUNET_xnew_array_2d_ directly. Use the
92 * #GNUNET_new_array_2d macro.
93 * The memory of the elements will be zero'ed out.
95 * @param n size of the first dimension
96 * @param m size of the second dimension
97 * @param elementSize size of a single element in bytes
98 * @param filename where is this call being made (for debugging)
99 * @param linenumber line where this call is being made (for debugging)
100 * @return allocated memory, never NULL
103 GNUNET_xnew_array_2d_ (size_t n,
106 const char *filename,
109 /* use char pointer internally to avoid void pointer arithmetic warnings */
110 char **ret = GNUNET_xmalloc_ (n * sizeof (void *) + /* 1. dim header */
111 n * m * elementSize, /* element data */
112 filename, linenumber);
114 for (size_t i = 0; i < n; i++)
115 ret[i] = (char *)ret + /* base address */
116 n * sizeof (void *) + /* skip 1. dim header */
117 i * m * elementSize; /* skip to 2. dim row header */
123 * Allocate memory for a three dimensional array in one block
124 * and set up pointers. Aborts if no more memory is available.
125 * Don't use GNUNET_xnew_array_3d_ directly. Use the
126 * #GNUNET_new_array_3d macro.
127 * The memory of the elements will be zero'ed out.
129 * @param n size of the first dimension
130 * @param m size of the second dimension
131 * @param o size of the third dimension
132 * @param elementSize size of a single element in bytes
133 * @param filename where is this call being made (for debugging)
134 * @param linenumber line where this call is being made (for debugging)
135 * @return allocated memory, never NULL
138 GNUNET_xnew_array_3d_ (size_t n, size_t m, size_t o, size_t elementSize,
139 const char *filename, int linenumber)
141 /* use char pointer internally to avoid void pointer arithmetic warnings */
142 char ***ret = GNUNET_xmalloc_ (n * sizeof (void **) + /* 1. dim header */
143 n * m * sizeof (void *) + /* 2. dim header */
144 n * m * o * elementSize, /* element data */
145 filename, linenumber);
147 for (size_t i = 0; i < n; i++)
149 /* need to cast to (char *) temporarily for byte level acuracy */
150 ret[i] = (char **)((char *)ret + /* base address */
151 n * sizeof (void **) + /* skip 1. dim header */
152 i * m * sizeof (void *)); /* skip to 2. dim header */
153 for (size_t j = 0; j < m; j++)
154 ret[i][j] = (char *)ret + /* base address */
155 n * sizeof (void **) + /* skip 1. dim header */
156 n * m * sizeof (void *) + /* skip 2. dim header */
157 i * m * o * elementSize + /* skip to 2. dim part */
158 j * o * elementSize; /* skip to 3. dim row data */
160 return (void ***)ret;
165 * Allocate and initialize memory. Checks the return value, aborts if no more
166 * memory is available. Don't use #GNUNET_xmemdup_() directly. Use the
167 * GNUNET_memdup() macro.
169 * @param buf buffer to initialize from (must contain size bytes)
170 * @param size number of bytes to allocate
171 * @param filename where is this call being made (for debugging)
172 * @param linenumber line where this call is being made (for debugging)
173 * @return allocated memory, never NULL
176 GNUNET_xmemdup_ (const void *buf,
178 const char *filename,
183 /* As a security precaution, we generally do not allow very large
184 * allocations here */
185 GNUNET_assert_at (size <= GNUNET_MAX_MALLOC_CHECKED, filename, linenumber);
187 size += sizeof (size_t);
188 if (mem_used + size > W32_MEM_LIMIT)
191 GNUNET_assert_at (size < INT_MAX, filename, linenumber);
195 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "malloc");
199 *((size_t *) ret) = size;
200 ret = &((size_t *) ret)[1];
203 GNUNET_memcpy (ret, buf, size);
209 * Wrapper around malloc(). Allocates size bytes of memory.
210 * The memory will be zero'ed out.
212 * @param size the number of bytes to allocate
213 * @param filename where in the code was the call to GNUNET_malloc_unchecked()
214 * @param linenumber where in the code was the call to GNUNET_malloc_unchecked()
215 * @return pointer to size bytes of memory, NULL if we do not have enough memory
218 GNUNET_xmalloc_unchecked_ (size_t size,
219 const char *filename,
227 size += sizeof (size_t);
228 if (mem_used + size > W32_MEM_LIMIT)
232 result = malloc (size);
235 memset (result, 0, size);
238 *((size_t *) result) = size;
239 result = &((size_t *) result)[1];
248 * Reallocate memory. Checks the return value, aborts if no more
249 * memory is available.
250 * The content of the intersection of the new and old size will be unchanged.
252 * @param ptr the pointer to reallocate
253 * @param n how many bytes of memory to allocate
254 * @param filename where in the code was the call to GNUNET_realloc()
255 * @param linenumber where in the code was the call to GNUNET_realloc()
256 * @return pointer to size bytes of memory
259 GNUNET_xrealloc_ (void *ptr,
261 const char *filename,
268 n += sizeof (size_t);
269 ptr = &((size_t *) ptr)[-1];
270 mem_used = mem_used - *((size_t *) ptr) + n;
272 ptr = realloc (ptr, n);
273 if ((NULL == ptr) && (n > 0))
275 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR,
280 ptr = &((size_t *) ptr)[1];
286 # if __BYTE_ORDER == __LITTLE_ENDIAN
287 #define BAADFOOD_STR "\x0D\xF0\xAD\xBA"
289 # if __BYTE_ORDER == __BIG_ENDIAN
290 #define BAADFOOD_STR "\xBA\xAD\xF0\x0D"
294 #define M_SIZE(p) _msize (p)
297 #include <malloc_np.h>
299 #if HAVE_MALLOC_USABLE_SIZE
300 #define M_SIZE(p) malloc_usable_size (p)
301 #elif HAVE_MALLOC_SIZE
302 #define M_SIZE(p) malloc_size (p)
306 * Free memory. Merely a wrapper for the case that we
307 * want to keep track of allocations.
309 * @param ptr the pointer to free
310 * @param filename where in the code was the call to GNUNET_free
311 * @param linenumber where in the code was the call to GNUNET_free
314 GNUNET_xfree_ (void *ptr,
315 const char *filename,
318 GNUNET_assert_at (NULL != ptr,
322 ptr = &((size_t *) ptr)[-1];
323 mem_used -= *((size_t *) ptr);
328 const uint64_t baadfood = GNUNET_ntohll (0xBAADF00DBAADF00DLL);
329 uint64_t *base = ptr;
330 size_t s = M_SIZE (ptr);
335 GNUNET_memcpy (&base[s/8], &baadfood, s % 8);
344 * Dup a string (same semantics as strdup).
346 * @param str the string to dup
347 * @param filename where in the code was the call to GNUNET_strdup()
348 * @param linenumber where in the code was the call to GNUNET_strdup()
349 * @return `strdup(@a str)`
352 GNUNET_xstrdup_ (const char *str,
353 const char *filename,
359 GNUNET_assert_at (str != NULL,
362 slen = strlen (str) + 1;
363 res = GNUNET_xmalloc_ (slen,
375 strnlen (const char *s,
380 e = memchr (s, '\0', n);
389 * Dup partially a string (same semantics as strndup).
391 * @param str the string to dup
392 * @param len the length of the string to dup
393 * @param filename where in the code was the call to GNUNET_strndup()
394 * @param linenumber where in the code was the call to GNUNET_strndup()
395 * @return `strndup(@a str,@a len)`
398 GNUNET_xstrndup_ (const char *str,
400 const char *filename,
406 return GNUNET_strdup ("");
407 GNUNET_assert_at (NULL != str,
412 res = GNUNET_xmalloc_ (len + 1,
415 GNUNET_memcpy (res, str, len);
416 /* res[len] = '\0'; 'malloc' zeros out anyway */
422 * Grow an array. Grows old by (*oldCount-newCount)*elementSize bytes
423 * and sets *oldCount to newCount.
425 * @param old address of the pointer to the array
427 * @param elementSize the size of the elements of the array
428 * @param oldCount address of the number of elements in the *old array
429 * @param newCount number of elements in the new array, may be 0
430 * @param filename where in the code was the call to GNUNET_array_grow()
431 * @param linenumber where in the code was the call to GNUNET_array_grow()
434 GNUNET_xgrow_ (void **old,
436 unsigned int *oldCount,
437 unsigned int newCount,
438 const char *filename,
444 GNUNET_assert_at (INT_MAX / elementSize > newCount, filename, linenumber);
445 size = newCount * elementSize;
452 tmp = GNUNET_xmalloc_ (size, filename, linenumber);
455 GNUNET_memcpy (tmp, *old, elementSize * GNUNET_MIN(*oldCount, newCount));
461 GNUNET_xfree_ (*old, filename, linenumber);
464 *oldCount = newCount;
469 * Like asprintf(), just portable.
471 * @param buf set to a buffer of sufficient size (allocated, caller must free)
472 * @param format format string (see printf(), fprintf(), etc.)
473 * @param ... data for format string
474 * @return number of bytes in `*@a buf`, excluding 0-termination
477 GNUNET_asprintf (char **buf,
484 va_start (args, format);
485 ret = VSNPRINTF (NULL, 0, format, args);
487 GNUNET_assert (ret >= 0);
488 *buf = GNUNET_malloc (ret + 1);
489 va_start (args, format);
490 ret = VSPRINTF (*buf, format, args);
497 * Like snprintf(), just aborts if the buffer is of insufficient size.
499 * @param buf pointer to buffer that is written to
500 * @param size number of bytes in buf
501 * @param format format strings
502 * @param ... data for format string
503 * @return number of bytes written to buf or negative value on error
506 GNUNET_snprintf (char *buf,
508 const char *format, ...)
513 va_start (args, format);
514 ret = VSNPRINTF (buf,
519 GNUNET_assert ( (ret >= 0) &&
520 (((size_t) ret) < size) );
526 * Create a copy of the given message.
528 * @param msg message to copy
529 * @return duplicate of the message
531 struct GNUNET_MessageHeader *
532 GNUNET_copy_message (const struct GNUNET_MessageHeader *msg)
534 struct GNUNET_MessageHeader *ret;
537 msize = ntohs (msg->size);
538 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader));
539 ret = GNUNET_malloc (msize);
547 /* end of common_allocation.c */