1 /*
2  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
3  * SPDX-License-Identifier: MIT
4  */
5 
6 #include <sys/types.h>
7 #include <errno.h>
8 #include <stdint.h>
9 #include <stdlib.h>
10 
11 #ifndef SIZE_MAX
12     #define SIZE_MAX     UINTPTR_MAX
13 #endif
14 
15 /*
16  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
17  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
18  */
19 #define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
20 
21 void *
openbsd_reallocarray(void * optr,size_t nmemb,size_t size)22 openbsd_reallocarray(void *optr, size_t nmemb, size_t size)
23 {
24 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
25 	    nmemb > 0 && SIZE_MAX / nmemb < size) {
26 		errno = ENOMEM;
27 		return NULL;
28 	}
29 	/*
30 	 * Head off variations in realloc behavior on different
31 	 * platforms (reported by MarkR <mrogers6@users.sf.net>)
32 	 *
33 	 * The behaviour of reallocarray is implementation-defined if
34 	 * nmemb or size is zero. It can return NULL or non-NULL
35 	 * depending on the platform.
36 	 * https://www.securecoding.cert.org/confluence/display/c/MEM04-C.Beware+of+zero-lengthallocations
37 	 *
38 	 * Here are some extracts from realloc man pages on different platforms.
39 	 *
40 	 * void realloc( void memblock, size_t size );
41 	 *
42 	 * Windows:
43 	 *
44 	 * If there is not enough available memory to expand the block
45 	 * to the given size, the original block is left unchanged,
46 	 * and NULL is returned.  If size is zero, then the block
47 	 * pointed to by memblock is freed; the return value is NULL,
48 	 * and memblock is left pointing at a freed block.
49 	 *
50 	 * OpenBSD:
51 	 *
52 	 * If size or nmemb is equal to 0, a unique pointer to an
53 	 * access protected, zero sized object is returned. Access via
54 	 * this pointer will generate a SIGSEGV exception.
55 	 *
56 	 * Linux:
57 	 *
58 	 * If size was equal to 0, either NULL or a pointer suitable
59 	 * to be passed to free() is returned.
60 	 *
61 	 * OS X:
62 	 *
63 	 * If size is zero and ptr is not NULL, a new, minimum sized
64 	 * object is allocated and the original object is freed.
65 	 *
66 	 * It looks like images with zero width or height can trigger
67 	 * this, and fuzzing behaviour will differ by platform, so
68 	 * fuzzing on one platform may not detect zero-size allocation
69 	 * problems on other platforms.
70 	 */
71 	if (size == 0 || nmemb == 0)
72 	    return NULL;
73 	return realloc(optr, size * nmemb);
74 }
75