From aa4ce6623ca357c592cf602b197900207ee38062 Mon Sep 17 00:00:00 2001 From: Bruno Haible Date: Sat, 11 Nov 2023 19:34:26 +0100 Subject: [PATCH] ialloc: Take advantage of CHERI bounds-checking. * lib/ialloc.h: Include . (irealloc): When s is 0, return a pointer whose bounds are of size 0, not 1. (ireallocarray): When n or s is 0, return a pointer whose bounds are of size 0, not 1. --- ChangeLog | 9 +++++++++ lib/ialloc.h | 43 +++++++++++++++++++++++++++++++++---------- 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/ChangeLog b/ChangeLog index 60aea347a3..c166fae715 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,12 @@ +2023-11-11 Bruno Haible + + ialloc: Take advantage of CHERI bounds-checking. + * lib/ialloc.h: Include . + (irealloc): When s is 0, return a pointer whose bounds are of size 0, + not 1. + (ireallocarray): When n or s is 0, return a pointer whose bounds are of + size 0, not 1. + 2023-11-11 Bruno Haible eealloc: Take advantage of CHERI bounds-checking. diff --git a/lib/ialloc.h b/lib/ialloc.h index 22f57a47d8..527b1f48be 100644 --- a/lib/ialloc.h +++ b/lib/ialloc.h @@ -29,6 +29,9 @@ #include #include #include +#if defined __CHERI__ +# include +#endif _GL_INLINE_HEADER_BEGIN #ifndef IALLOC_INLINE @@ -65,9 +68,19 @@ IALLOC_INLINE void * irealloc (void *p, idx_t s) { - /* Work around GNU realloc glitch by treating a zero size as if it - were 1, so that returning NULL is equivalent to failing. */ - return s <= SIZE_MAX ? realloc (p, s | !s) : _gl_alloc_nomem (); + if (s <= SIZE_MAX) + { + /* Work around GNU realloc glitch by treating a zero size as if it + were 1, so that returning NULL is equivalent to failing. */ + p = realloc (p, s | !s); +#if defined __CHERI__ + if (p != NULL) + p = cheri_bounds_set (p, s); +#endif + return p; + } + else + return _gl_alloc_nomem (); } /* icalloc (num, size) is like calloc (num, size). @@ -99,13 +112,23 @@ icalloc (idx_t n, idx_t s) IALLOC_INLINE void * ireallocarray (void *p, idx_t n, idx_t s) { - /* Work around GNU reallocarray glitch by treating a zero size as if - it were 1, so that returning NULL is equivalent to failing. */ - if (n == 0 || s == 0) - n = s = 1; - return (n <= SIZE_MAX && s <= SIZE_MAX - ? reallocarray (p, n, s) - : _gl_alloc_nomem ()); + if (n <= SIZE_MAX && s <= SIZE_MAX) + { + /* Work around GNU reallocarray glitch by treating a zero size as if + it were 1, so that returning NULL is equivalent to failing. */ + size_t nx = n; + size_t sx = s; + if (n == 0 || s == 0) + nx = sx = 1; + p = reallocarray (p, nx, sx); +#if defined __CHERI__ + if (p != NULL && (n == 0 || s == 0)) + p = cheri_bounds_set (p, 0); +#endif + return p; + } + else + return _gl_alloc_nomem (); } #ifdef __cplusplus -- 2.39.5