[PATCH] tools: Fix use-after-free for realloc(..., 0)

From: Kees Cook
Date: Sat Feb 12 2022 - 13:19:02 EST


GCC 12 was correctly reporting a potential use-after-free condition in
the xrealloc helper. Fix the warning by avoiding an implicit "free(ptr)"
when size == 0:

In file included from help.c:12:
In function 'xrealloc',
inlined from 'add_cmdname' at help.c:24:2: subcmd-util.h:56:23: error: pointer may be used after 'realloc' [-Werror=use-after-free]
56 | ret = realloc(ptr, size);
| ^~~~~~~~~~~~~~~~~~
subcmd-util.h:52:21: note: call to 'realloc' here
52 | void *ret = realloc(ptr, size);
| ^~~~~~~~~~~~~~~~~~
subcmd-util.h:58:31: error: pointer may be used after 'realloc' [-Werror=use-after-free]
58 | ret = realloc(ptr, 1);
| ^~~~~~~~~~~~~~~
subcmd-util.h:52:21: note: call to 'realloc' here
52 | void *ret = realloc(ptr, size);
| ^~~~~~~~~~~~~~~~~~

Reported-by: "Valdis Klētnieks" <valdis.kletnieks@xxxxxx>
Fixes: 2f4ce5ec1d44 ("perf tools: Finalize subcmd independence")
Cc: Josh Poimboeuf <jpoimboe@xxxxxxxxxx>
Signed-off-by: Kees Cook <keescook@xxxxxxxxxxxx>
---
tools/lib/subcmd/subcmd-util.h | 25 +++++++++++++++++--------
1 file changed, 17 insertions(+), 8 deletions(-)

diff --git a/tools/lib/subcmd/subcmd-util.h b/tools/lib/subcmd/subcmd-util.h
index 794a375dad36..de392fc5fd3a 100644
--- a/tools/lib/subcmd/subcmd-util.h
+++ b/tools/lib/subcmd/subcmd-util.h
@@ -49,15 +49,24 @@ static NORETURN inline void die(const char *err, ...)

static inline void *xrealloc(void *ptr, size_t size)
{
- void *ret = realloc(ptr, size);
- if (!ret && !size)
- ret = realloc(ptr, 1);
+ void *ret;
+
+ /*
+ * Convert a zero-sized allocation into 1 byte, since
+ * realloc(ptr, 0) means free(ptr), but we don't want
+ * to release the memory. For a new allocation (when
+ * ptr == NULL), avoid triggering NULL-checking error
+ * conditions for zero-sized allocations.
+ */
+ if (!size)
+ size = 1;
+ ret = realloc(ptr, size);
if (!ret) {
- ret = realloc(ptr, size);
- if (!ret && !size)
- ret = realloc(ptr, 1);
- if (!ret)
- die("Out of memory, realloc failed");
+ /*
+ * If realloc() fails, the original block is left untouched;
+ * it is not freed or moved.
+ */
+ die("Out of memory, realloc failed");
}
return ret;
}
--
2.30.2