summaryrefslogtreecommitdiff
path: root/src/reallocarray.c
diff options
context:
space:
mode:
authorAlan Coopersmith <alan.coopersmith@oracle.com>2022-08-06 15:38:58 -0700
committerAlan Coopersmith <alan.coopersmith@oracle.com>2022-08-06 16:22:02 -0700
commit621f61f7d3f5955a84e6aa8b7458699870fdee45 (patch)
tree5125afc313de6f2494940a47a8ae1d9cb4163b06 /src/reallocarray.c
parent05ee465685aba409800523c6615392a867366818 (diff)
downloadxorg-lib-libXmu-621f61f7d3f5955a84e6aa8b7458699870fdee45.tar.gz
Import reallocarray() from libX11 (originally from OpenBSD)
Wrapper for realloc() that checks for overflow when multiplying arguments together, so we don't have to add overflow checks to every single call. For documentation on usage, see: http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man3/calloc.3 Signed-off-by: Alan Coopersmith <alan.coopersmith@oracle.com>
Diffstat (limited to 'src/reallocarray.c')
-rw-r--r--src/reallocarray.c43
1 files changed, 43 insertions, 0 deletions
diff --git a/src/reallocarray.c b/src/reallocarray.c
new file mode 100644
index 0000000..ade402c
--- /dev/null
+++ b/src/reallocarray.c
@@ -0,0 +1,43 @@
+/* $OpenBSD: reallocarray.c,v 1.2 2014/12/08 03:45:00 bcook Exp $ */
+/*
+ * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <sys/types.h>
+#include <errno.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include "Xmuint.h"
+
+/*
+ * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
+ * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
+ */
+#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
+
+void *
+Xmureallocarray(void *optr, size_t nmemb, size_t size)
+{
+ if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
+ nmemb > 0 && SIZE_MAX / nmemb < size) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ return realloc(optr, size * nmemb);
+}