xref: /OK3568_Linux_fs/external/xserver/os/reallocarray.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun /*	$OpenBSD: reallocarray.c,v 1.2 2014/12/08 03:45:00 bcook Exp $	*/
2*4882a593Smuzhiyun /*
3*4882a593Smuzhiyun  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
4*4882a593Smuzhiyun  *
5*4882a593Smuzhiyun  * Permission to use, copy, modify, and distribute this software for any
6*4882a593Smuzhiyun  * purpose with or without fee is hereby granted, provided that the above
7*4882a593Smuzhiyun  * copyright notice and this permission notice appear in all copies.
8*4882a593Smuzhiyun  *
9*4882a593Smuzhiyun  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10*4882a593Smuzhiyun  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11*4882a593Smuzhiyun  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12*4882a593Smuzhiyun  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13*4882a593Smuzhiyun  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14*4882a593Smuzhiyun  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15*4882a593Smuzhiyun  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16*4882a593Smuzhiyun  */
17*4882a593Smuzhiyun 
18*4882a593Smuzhiyun #ifdef HAVE_DIX_CONFIG_H
19*4882a593Smuzhiyun #include <dix-config.h>
20*4882a593Smuzhiyun #endif
21*4882a593Smuzhiyun 
22*4882a593Smuzhiyun #include <sys/types.h>
23*4882a593Smuzhiyun #include <errno.h>
24*4882a593Smuzhiyun #include <stdint.h>
25*4882a593Smuzhiyun #include <stdlib.h>
26*4882a593Smuzhiyun #include "os.h"
27*4882a593Smuzhiyun 
28*4882a593Smuzhiyun /*
29*4882a593Smuzhiyun  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
30*4882a593Smuzhiyun  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
31*4882a593Smuzhiyun  */
32*4882a593Smuzhiyun #define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
33*4882a593Smuzhiyun 
34*4882a593Smuzhiyun void *
reallocarray(void * optr,size_t nmemb,size_t size)35*4882a593Smuzhiyun reallocarray(void *optr, size_t nmemb, size_t size)
36*4882a593Smuzhiyun {
37*4882a593Smuzhiyun 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
38*4882a593Smuzhiyun 	    nmemb > 0 && SIZE_MAX / nmemb < size) {
39*4882a593Smuzhiyun 		errno = ENOMEM;
40*4882a593Smuzhiyun 		return NULL;
41*4882a593Smuzhiyun 	}
42*4882a593Smuzhiyun 	return realloc(optr, size * nmemb);
43*4882a593Smuzhiyun }
44