]> Savannah Git Hosting - gnulib.git/commitdiff
xalloc: port to Cheri, strict C23, realloc null
authorPaul Eggert <eggert@cs.ucla.edu>
Fri, 25 Oct 2024 04:52:19 +0000 (21:52 -0700)
committerPaul Eggert <eggert@cs.ucla.edu>
Fri, 25 Oct 2024 04:57:18 +0000 (21:57 -0700)
* lib/xmalloc.c [__CHERI_PURE_CAPABILITY__]: Include <cheri.h>.
(xrealloc, xreallocarray): Support Cheri.  Avoid undefined
behavior in strict C23.  Work better on platforms where
realloc (p, 0) returns a null pointer

ChangeLog
lib/xmalloc.c

index 9226a54c1866e2157aa63014f9a31664511d9e7e..dad59adfe967cdcc46c98a9ee88e2ac70cdabe2e 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,11 @@
 2024-10-24  Paul Eggert  <eggert@cs.ucla.edu>
 
+       xalloc: port to Cheri, strict C23, realloc null
+       * lib/xmalloc.c [__CHERI_PURE_CAPABILITY__]: Include <cheri.h>.
+       (xrealloc, xreallocarray): Support Cheri.  Avoid undefined
+       behavior in strict C23.  Work better on platforms where
+       realloc (p, 0) returns a null pointer
+
        reallocarray: simplify
        * lib/reallocarray.c (reallocarray): Use simpler workaround
        for realloc glitch, which does not involve malloc.
index 5befdab77cfdbb7d4b909ecf96cdd78aa7938680..71332bbea63434a6978a7c05aa16a38dc9ba0bcf 100644 (file)
 #include <stdint.h>
 #include <string.h>
 
+#ifdef __CHERI_PURE_CAPABILITY__
+# include <cheri.h>
+#endif
+
 static void * _GL_ATTRIBUTE_PURE
 check_nonnull (void *p)
 {
@@ -63,9 +67,15 @@ xcharalloc (size_t n)
 void *
 xrealloc (void *p, size_t s)
 {
-  void *r = realloc (p, s);
-  if (!r && (!p || s))
+  /* Work around realloc glitch by treating a 0 size as if it were 1,
+     to avoid undefined behavior in strict C23 platforms,
+     so that returning NULL is equivalent to failing.  */
+  void *r = realloc (p, s ? s : 1);
+  if (!r)
     xalloc_die ();
+#ifdef __CHERI_PURE_CAPABILITY__
+  r = cheri_bounds_set (r, s);
+#endif
   return r;
 }
 
@@ -81,9 +91,19 @@ xirealloc (void *p, idx_t s)
 void *
 xreallocarray (void *p, size_t n, size_t s)
 {
-  void *r = reallocarray (p, n, s);
-  if (!r && (!p || (n && s)))
+  /* Work around reallocarray glitch by treating a 0 size as if it were 1,
+     so that returning NULL is equivalent to failing.  */
+  size_t nx = n;
+  size_t sx = s;
+  if (!n || !s)
+    nx = sx = 1;
+  void *r = reallocarray (p, nx, sx);
+  if (!r)
     xalloc_die ();
+#ifdef __CHERI_PURE_CAPABILITY__
+  if (!n || !s)
+    r = cheri_bounds_set (r, 0);
+#endif
   return r;
 }