1e9bf778aSBaptiste Daroussin /* $Id: compat_reallocarray.c,v 1.5 2020/06/15 01:37:15 schwarze Exp $ */
2e9bf778aSBaptiste Daroussin /* $OpenBSD: reallocarray.c,v 1.3 2015/09/13 08:31:47 guenther Exp $ */
352c0e955SBaptiste Daroussin /*
452c0e955SBaptiste Daroussin * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
552c0e955SBaptiste Daroussin *
652c0e955SBaptiste Daroussin * Permission to use, copy, modify, and distribute this software for any
752c0e955SBaptiste Daroussin * purpose with or without fee is hereby granted, provided that the above
852c0e955SBaptiste Daroussin * copyright notice and this permission notice appear in all copies.
952c0e955SBaptiste Daroussin *
1052c0e955SBaptiste Daroussin * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
1152c0e955SBaptiste Daroussin * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1252c0e955SBaptiste Daroussin * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
1352c0e955SBaptiste Daroussin * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1452c0e955SBaptiste Daroussin * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1552c0e955SBaptiste Daroussin * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1652c0e955SBaptiste Daroussin * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1752c0e955SBaptiste Daroussin */
18e9bf778aSBaptiste Daroussin #include "config.h"
192612bc21SBaptiste Daroussin
2052c0e955SBaptiste Daroussin #include <sys/types.h>
2152c0e955SBaptiste Daroussin #include <errno.h>
2252c0e955SBaptiste Daroussin #include <stdint.h>
2352c0e955SBaptiste Daroussin #include <stdlib.h>
2452c0e955SBaptiste Daroussin
252612bc21SBaptiste Daroussin /*
262612bc21SBaptiste Daroussin * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
272612bc21SBaptiste Daroussin * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
282612bc21SBaptiste Daroussin */
292612bc21SBaptiste Daroussin #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
3052c0e955SBaptiste Daroussin
3152c0e955SBaptiste Daroussin void *
reallocarray(void * optr,size_t nmemb,size_t size)3252c0e955SBaptiste Daroussin reallocarray(void *optr, size_t nmemb, size_t size)
3352c0e955SBaptiste Daroussin {
3452c0e955SBaptiste Daroussin if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
3552c0e955SBaptiste Daroussin nmemb > 0 && SIZE_MAX / nmemb < size) {
3652c0e955SBaptiste Daroussin errno = ENOMEM;
3752c0e955SBaptiste Daroussin return NULL;
3852c0e955SBaptiste Daroussin }
3952c0e955SBaptiste Daroussin return realloc(optr, size * nmemb);
4052c0e955SBaptiste Daroussin }
41