1 /* $OpenBSD: recallocarray.c,v 1.1 2017/03/06 18:44:21 otto Exp $ */
2
3 /*
4 * Copyright (c) 2008, 2017 Otto Moerbeek <otto@drijf.net>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 /* OPENBSD ORIGINAL: lib/libc/stdlib/recallocarray.c */
20
21 #include "includes.h"
22 #ifndef HAVE_RECALLOCARRAY
23
24 #include <errno.h>
25 #include <stdlib.h>
26 #ifdef HAVE_STDINT_H
27 #include <stdint.h>
28 #endif
29 #include <string.h>
30 #include <unistd.h>
31
32 /*
33 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
34 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
35 */
36 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
37
38 void *
recallocarray(void * ptr,size_t oldnmemb,size_t newnmemb,size_t size)39 recallocarray(void *ptr, size_t oldnmemb, size_t newnmemb, size_t size)
40 {
41 size_t oldsize, newsize;
42 void *newptr;
43
44 if (ptr == NULL)
45 return calloc(newnmemb, size);
46
47 if ((newnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
48 newnmemb > 0 && SIZE_MAX / newnmemb < size) {
49 errno = ENOMEM;
50 return NULL;
51 }
52 newsize = newnmemb * size;
53
54 if ((oldnmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
55 oldnmemb > 0 && SIZE_MAX / oldnmemb < size) {
56 errno = EINVAL;
57 return NULL;
58 }
59 oldsize = oldnmemb * size;
60
61 /*
62 * Don't bother too much if we're shrinking just a bit,
63 * we do not shrink for series of small steps, oh well.
64 */
65 if (newsize <= oldsize) {
66 size_t d = oldsize - newsize;
67
68 if (d < oldsize / 2 && d < (size_t)getpagesize()) {
69 memset((char *)ptr + newsize, 0, d);
70 return ptr;
71 }
72 }
73
74 newptr = malloc(newsize);
75 if (newptr == NULL)
76 return NULL;
77
78 if (newsize > oldsize) {
79 memcpy(newptr, ptr, oldsize);
80 memset((char *)newptr + oldsize, 0, newsize - oldsize);
81 } else
82 memcpy(newptr, ptr, newsize);
83
84 explicit_bzero(ptr, oldsize);
85 free(ptr);
86
87 return newptr;
88 }
89 /* DEF_WEAK(recallocarray); */
90
91 #endif /* HAVE_RECALLOCARRAY */
92