tools: Fix use-after-free for realloc(..., 0)
authorKees Cook <keescook@chromium.org>
Sat, 12 Feb 2022 17:54:04 +0000 (09:54 -0800)
committerKees Cook <keescook@chromium.org>
Mon, 14 Feb 2022 00:48:25 +0000 (16:48 -0800)
commit48f4900c115a99dd83e1c17347ff040ca2fdf165
tree5a579bde60630b3f0583e440e22422f812a87f55
parenta88ff09ac457262a822785974966171a9508c005
tools: Fix use-after-free for realloc(..., 0)

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@vt.edu>
Fixes: 2f4ce5ec1d44 ("perf tools: Finalize subcmd independence")
Cc: Josh Poimboeuf <jpoimboe@redhat.com>
Signed-off-by: Kees Cook <keescook@chromium.org>
tools/lib/subcmd/subcmd-util.h