Blob


1 /*
2 * Copyright (c) 2008, 2017 Otto Moerbeek <otto@drijf.net>
3 *
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.
7 *
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.
15 */
17 #include <errno.h>
18 #include <stdlib.h>
19 #include <stdint.h>
20 #include <string.h>
21 #include <unistd.h>
23 /*
24 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
25 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
26 */
27 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
29 /*
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.
34 */
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);
41 void *
42 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
43 {
44 size_t oldsize, newsize;
45 void *newptr;
47 if (ptr == NULL)
48 return calloc(newnmemb, size);
50 if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
51 newnmemb > 0 && SIZE_MAX / newnmemb < size) {
52 errno = ENOMEM;
53 return NULL;
54 }
55 newsize = newnmemb * size;
57 if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
58 oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {
59 errno = EINVAL;
60 return NULL;
61 }
62 oldsize = oldnmemb * size;
64 /*
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.
67 */
68 if (newsize <= oldsize) {
69 size_t d = oldsize - newsize;
71 if (d < oldsize / 2 && d < getpagesize()) {
72 memset((char *)ptr + newsize, 0, d);
73 return ptr;
74 }
75 }
77 newptr = malloc(newsize);
78 if (newptr == NULL)
79 return NULL;
81 if (newsize > oldsize) {
82 memcpy(newptr, ptr, oldsize);
83 memset((char *)newptr + oldsize, 0, newsize - oldsize);
84 } else
85 memcpy(newptr, ptr, newsize);
87 explicit_bzero(ptr, oldsize);
88 free(ptr);
90 return newptr;
91 }