]>
git.cameronkatri.com Git - mandoc.git/blob - compat_recallocarray.c
1 /* $Id: compat_recallocarray.c,v 1.2 2020/06/15 01:37:15 schwarze Exp $ */
2 /* $OpenBSD: recallocarray.c,v 1.1 2017/03/06 18:44:21 otto Exp $ */
4 * Copyright (c) 2008, 2017 Otto Moerbeek <otto@drijf.net>
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.
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.
20 #include <sys/types.h>
27 * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
28 * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
30 #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
33 * Even though specified in POSIX, the PAGESIZE and PAGE_SIZE
34 * macros have very poor portability. Since we only use this
35 * to avoid free() overhead for small shrinking, simply pick
36 * an arbitrary number.
38 #define getpagesize() (1UL << 12)
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
);
88 * At this point, the OpenBSD implementation calls
89 * explicit_bzero() on the old memory before it is
90 * freed. Since explicit_bzero() is hard to implement
91 * portably and we don't handle confidential data in
92 * mandoc in the first place, simply free the memory
93 * without clearing it.