135c4bbdfSmrg/*	$OpenBSD: reallocarray.c,v 1.2 2014/12/08 03:45:00 bcook Exp $	*/
235c4bbdfSmrg/*
335c4bbdfSmrg * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
435c4bbdfSmrg *
535c4bbdfSmrg * Permission to use, copy, modify, and distribute this software for any
635c4bbdfSmrg * purpose with or without fee is hereby granted, provided that the above
735c4bbdfSmrg * copyright notice and this permission notice appear in all copies.
835c4bbdfSmrg *
935c4bbdfSmrg * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
1035c4bbdfSmrg * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1135c4bbdfSmrg * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
1235c4bbdfSmrg * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1335c4bbdfSmrg * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1435c4bbdfSmrg * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1535c4bbdfSmrg * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1635c4bbdfSmrg */
1735c4bbdfSmrg
1835c4bbdfSmrg#ifdef HAVE_DIX_CONFIG_H
1935c4bbdfSmrg#include <dix-config.h>
2035c4bbdfSmrg#endif
2135c4bbdfSmrg
2235c4bbdfSmrg#include <sys/types.h>
2335c4bbdfSmrg#include <errno.h>
2435c4bbdfSmrg#include <stdint.h>
2535c4bbdfSmrg#include <stdlib.h>
2635c4bbdfSmrg#include "os.h"
2735c4bbdfSmrg
2835c4bbdfSmrg/*
2935c4bbdfSmrg * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
3035c4bbdfSmrg * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
3135c4bbdfSmrg */
3235c4bbdfSmrg#define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))
3335c4bbdfSmrg
3435c4bbdfSmrgvoid *
3535c4bbdfSmrgreallocarray(void *optr, size_t nmemb, size_t size)
3635c4bbdfSmrg{
3735c4bbdfSmrg	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
3835c4bbdfSmrg	    nmemb > 0 && SIZE_MAX / nmemb < size) {
3935c4bbdfSmrg		errno = ENOMEM;
4035c4bbdfSmrg		return NULL;
4135c4bbdfSmrg	}
4235c4bbdfSmrg	return realloc(optr, size * nmemb);
4335c4bbdfSmrg}
44