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 "../config.h"
19 #include <errno.h>
20 #include <stdlib.h>
21 #include <stdint.h>
22 #include <string.h>
23 #include <unistd.h>
25 /*
26 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
27 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
28 */
29 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
31 /*
32 * Even though specified in POSIX, the PAGESIZE and PAGE_SIZE
33 * macros have very poor portability. Since we only use this
34 * to avoid free() overhead for small shrinking, simply pick
35 * an arbitrary number.
36 */
37 #define getpagesize() (1UL << 12)
39 void *
40 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
41 {
42 size_t oldsize, newsize;
43 void *newptr;
45 if (ptr == NULL)
46 return calloc(newnmemb, size);
48 if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
49 newnmemb > 0 && SIZE_MAX / newnmemb < size) {
50 errno = ENOMEM;
51 return NULL;
52 }
53 newsize = newnmemb * size;
55 if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
56 oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {
57 errno = EINVAL;
58 return NULL;
59 }
60 oldsize = oldnmemb * size;
62 /*
63 * Don't bother too much if we're shrinking just a bit,
64 * we do not shrink for series of small steps, oh well.
65 */
66 if (newsize <= oldsize) {
67 size_t d = oldsize - newsize;
69 if (d < oldsize / 2 && d < getpagesize()) {
70 memset((char *)ptr + newsize, 0, d);
71 return ptr;
72 }
73 }
75 newptr = malloc(newsize);
76 if (newptr == NULL)
77 return NULL;
79 if (newsize > oldsize) {
80 memcpy(newptr, ptr, oldsize);
81 memset((char *)newptr + oldsize, 0, newsize - oldsize);
82 } else
83 memcpy(newptr, ptr, newsize);
85 explicit_bzero(ptr, oldsize);
86 free(ptr);
88 return newptr;
89 }