2 * Copyright (c) 2008, 2017 Otto Moerbeek <otto@drijf.net>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
25 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
27 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
30 * Even though specified in POSIX, the PAGESIZE and PAGE_SIZE
31 * macros have very poor portability. Since we only use this
32 * to avoid free() overhead for small shrinking, simply pick
33 * an arbitrary number.
35 #define getpagesize() (1UL << 12)
37 /* cheat: provide a prototype for explicit_bzero: if libc doesn't
38 * provide it, we will link to compat/explicit_bzero.c anyway. */
39 void explicit_bzero(void*, size_t);
42 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
44 size_t oldsize, newsize;
48 return calloc(newnmemb, size);
50 if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
51 newnmemb > 0 && SIZE_MAX / newnmemb < size) {
55 newsize = newnmemb * size;
57 if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
58 oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {
62 oldsize = oldnmemb * size;
65 * Don't bother too much if we're shrinking just a bit,
66 * we do not shrink for series of small steps, oh well.
68 if (newsize <= oldsize) {
69 size_t d = oldsize - newsize;
71 if (d < oldsize / 2 && d < getpagesize()) {
72 memset((char *)ptr + newsize, 0, d);
77 newptr = malloc(newsize);
81 if (newsize > oldsize) {
82 memcpy(newptr, ptr, oldsize);
83 memset((char *)newptr + oldsize, 0, newsize - oldsize);
85 memcpy(newptr, ptr, newsize);
87 explicit_bzero(ptr, oldsize);