1*6d38604fSBaptiste Daroussin /* $Id: compat_reallocarray.c,v 1.5 2020/06/15 01:37:15 schwarze Exp $ */
2*6d38604fSBaptiste Daroussin /* $OpenBSD: reallocarray.c,v 1.3 2015/09/13 08:31:47 guenther Exp $ */
361d06d6bSBaptiste Daroussin /*
461d06d6bSBaptiste Daroussin * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
561d06d6bSBaptiste Daroussin *
661d06d6bSBaptiste Daroussin * Permission to use, copy, modify, and distribute this software for any
761d06d6bSBaptiste Daroussin * purpose with or without fee is hereby granted, provided that the above
861d06d6bSBaptiste Daroussin * copyright notice and this permission notice appear in all copies.
961d06d6bSBaptiste Daroussin *
1061d06d6bSBaptiste Daroussin * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
1161d06d6bSBaptiste Daroussin * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1261d06d6bSBaptiste Daroussin * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
1361d06d6bSBaptiste Daroussin * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1461d06d6bSBaptiste Daroussin * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1561d06d6bSBaptiste Daroussin * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1661d06d6bSBaptiste Daroussin * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1761d06d6bSBaptiste Daroussin */
18*6d38604fSBaptiste Daroussin #include "config.h"
1961d06d6bSBaptiste Daroussin
2061d06d6bSBaptiste Daroussin #include <sys/types.h>
2161d06d6bSBaptiste Daroussin #include <errno.h>
2261d06d6bSBaptiste Daroussin #include <stdint.h>
2361d06d6bSBaptiste Daroussin #include <stdlib.h>
2461d06d6bSBaptiste Daroussin
2561d06d6bSBaptiste Daroussin /*
2661d06d6bSBaptiste Daroussin * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
2761d06d6bSBaptiste Daroussin * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
2861d06d6bSBaptiste Daroussin */
2961d06d6bSBaptiste Daroussin #define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
3061d06d6bSBaptiste Daroussin
3161d06d6bSBaptiste Daroussin void *
reallocarray(void * optr,size_t nmemb,size_t size)3261d06d6bSBaptiste Daroussin reallocarray(void *optr, size_t nmemb, size_t size)
3361d06d6bSBaptiste Daroussin {
3461d06d6bSBaptiste Daroussin if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
3561d06d6bSBaptiste Daroussin nmemb > 0 && SIZE_MAX / nmemb < size) {
3661d06d6bSBaptiste Daroussin errno = ENOMEM;
3761d06d6bSBaptiste Daroussin return NULL;
3861d06d6bSBaptiste Daroussin }
3961d06d6bSBaptiste Daroussin return realloc(optr, size * nmemb);
4061d06d6bSBaptiste Daroussin }
41