aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md2
-rw-r--r--debug.h3
-rw-r--r--xmalloc.c15
-rw-r--r--xmalloc.h2
4 files changed, 14 insertions, 8 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d180857f..0617d0ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -119,6 +119,8 @@
([#2397][2397]).
* Incorrect word boundary detection when selection words with a
multi-column character in the last column ([#2411][2411]).
+* `reallocarray()` is no longer required, so as to support platforms
+ where libc doesn't include it (e.g. Termux + Android API < 29).
[2353]: https://codeberg.org/dnkl/foot/issues/2353
[2352]: https://codeberg.org/dnkl/foot/issues/2352
diff --git a/debug.h b/debug.h
index 92a0e091..29ff9606 100644
--- a/debug.h
+++ b/debug.h
@@ -2,7 +2,8 @@
#include "macros.h"
-#define FATAL_ERROR(...) fatal_error(__FILE__, __LINE__, __VA_ARGS__)
+#define FATAL_ERROR(msg, err) fatal_error(__FILE__, __LINE__, msg, err)
+#define FATAL_ERROR_ON(cond, err) if (unlikely(cond)) FATAL_ERROR(__func__, err)
#ifdef NDEBUG
#define BUG(...) UNREACHABLE()
diff --git a/xmalloc.c b/xmalloc.c
index ccfb5c48..e7693d3a 100644
--- a/xmalloc.c
+++ b/xmalloc.c
@@ -1,4 +1,5 @@
#include <errno.h>
+#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "xmalloc.h"
@@ -33,16 +34,18 @@ void *
xrealloc(void *ptr, size_t size)
{
xassert(size != 0);
- void *alloc = realloc(ptr, size);
- return check_alloc(alloc);
+ return check_alloc(realloc(ptr, size));
}
+// reallocarray(3) was only added to POSIX in Issue 8 (2024) and isn't
+// present on some platforms (e.g. Android API levels < 29), so this
+// function is both for portability and ENOMEM handling.
void *
-xreallocarray(void *ptr, size_t n, size_t size)
+xreallocarray(void *ptr, size_t nmemb, size_t size)
{
- xassert(n != 0 && size != 0);
- void *alloc = reallocarray(ptr, n, size);
- return check_alloc(alloc);
+ FATAL_ERROR_ON(nmemb == 0 || size == 0, EINVAL);
+ FATAL_ERROR_ON(size > SIZE_MAX / nmemb, EOVERFLOW);
+ return xrealloc(ptr, nmemb * size);
}
char *
diff --git a/xmalloc.h b/xmalloc.h
index 03e6eb0d..33a17ca5 100644
--- a/xmalloc.h
+++ b/xmalloc.h
@@ -12,7 +12,7 @@
void *xmalloc(size_t size) XMALLOC;
void *xcalloc(size_t nmemb, size_t size) XMALLOC;
void *xrealloc(void *ptr, size_t size);
-void *xreallocarray(void *ptr, size_t n, size_t size);
+void *xreallocarray(void *ptr, size_t nmemb, size_t size);
char *xstrdup(const char *str) XSTRDUP;
char *xstrndup(const char *str, size_t n) XSTRDUP;
char *xasprintf(const char *format, ...) PRINTF(1) XMALLOC;