safe-alloc: Take advantage of CHERI bounds-checking.
authorBruno Haible <bruno@clisp.org>
Sat, 11 Nov 2023 18:36:36 +0000 (19:36 +0100)
committerBruno Haible <bruno@clisp.org>
Sat, 11 Nov 2023 18:36:36 +0000 (19:36 +0100)
* lib/safe-alloc.h: Include <cheri.h>.
(safe_alloc_realloc_n): When count or size is 0, return a pointer whose
bounds are of size 0, not 1.

ChangeLog
lib/safe-alloc.h

index c166fae7153be479c381e03f82668bb619520b1e..1fd39a4a448b7cb780d5609c3d8b0238b7f956ec 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,10 @@
+2023-11-11  Bruno Haible  <bruno@clisp.org>
+
+       safe-alloc: Take advantage of CHERI bounds-checking.
+       * lib/safe-alloc.h: Include <cheri.h>.
+       (safe_alloc_realloc_n): When count or size is 0, return a pointer whose
+       bounds are of size 0, not 1.
+
 2023-11-11  Bruno Haible  <bruno@clisp.org>
 
        ialloc: Take advantage of CHERI bounds-checking.
index 46079d5c6917f66998a5699e917a676a1c10e1dc..27049d3836d6aa22b04aff8621e4f2ec53b30f38 100644 (file)
@@ -27,6 +27,9 @@
 #endif
 
 #include <stdlib.h>
+#if defined __CHERI__
+# include <cheri.h>
+#endif
 
 _GL_INLINE_HEADER_BEGIN
 #ifndef SAFE_ALLOC_INLINE
@@ -37,9 +40,16 @@ _GL_INLINE_HEADER_BEGIN
 SAFE_ALLOC_INLINE void *
 safe_alloc_realloc_n (void *ptr, size_t count, size_t size)
 {
+  size_t countx = count;
+  size_t sizex = size;
   if (count == 0 || size == 0)
-    count = size = 1;
-  return reallocarray (ptr, count, size);
+    countx = sizex = 1;
+  ptr = reallocarray (ptr, countx, sizex);
+#if defined __CHERI__
+  if (ptr != NULL && (count == 0 || size == 0))
+    ptr = cheri_bounds_set (ptr, 0);
+#endif
+  return ptr;
 }
 _GL_ATTRIBUTE_NODISCARD SAFE_ALLOC_INLINE int
 safe_alloc_check (void *ptr)