xref: /openbsd-src/libexec/ld.so/reallocarray.c (revision b722ba42570161220f25c5d789b5bec8a0166743)
1*b722ba42Sguenther /*	$OpenBSD: reallocarray.c,v 1.3 2022/01/08 06:49:41 guenther Exp $	*/
2c827e20bSotto /*
3c827e20bSotto  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
4c827e20bSotto  *
5c827e20bSotto  * Permission to use, copy, modify, and distribute this software for any
6c827e20bSotto  * purpose with or without fee is hereby granted, provided that the above
7c827e20bSotto  * copyright notice and this permission notice appear in all copies.
8c827e20bSotto  *
9c827e20bSotto  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10c827e20bSotto  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11c827e20bSotto  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12c827e20bSotto  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13c827e20bSotto  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14c827e20bSotto  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15c827e20bSotto  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16c827e20bSotto  */
17c827e20bSotto 
18c827e20bSotto #include <sys/types.h>
19c827e20bSotto #include <stdint.h>
20*b722ba42Sguenther 
21*b722ba42Sguenther #include "util.h"
22c827e20bSotto 
23c827e20bSotto /*
24c827e20bSotto  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
25c827e20bSotto  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
26c827e20bSotto  */
27c827e20bSotto #define MUL_NO_OVERFLOW	(1UL << (sizeof(size_t) * 4))
28c827e20bSotto 
29c827e20bSotto void *
_dl_reallocarray(void * optr,size_t nmemb,size_t size)30c827e20bSotto _dl_reallocarray(void *optr, size_t nmemb, size_t size)
31c827e20bSotto {
32c827e20bSotto 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
333b50b772Sguenther 	    nmemb > 0 && SIZE_MAX / nmemb < size)
343b50b772Sguenther 		_dl_die("reallocarray overflow");
35c827e20bSotto 	return _dl_realloc(optr, size * nmemb);
36c827e20bSotto }
37