[PATCH v1] lib subcmd: Avoid use-after-free when no commands are excluded

Ian Rogers posted 1 patch 2 years, 7 months ago
tools/lib/subcmd/help.c | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
[PATCH v1] lib subcmd: Avoid use-after-free when no commands are excluded
Posted by Ian Rogers 2 years, 7 months ago
The array shortening may be an unnecessary array copy. Before commit
657a3efee43a ("lib subcmd: Avoid memory leak in exclude_cmds") this
was benign, but afterwards this could lead to a segv.

Fixes: 657a3efee43a ("lib subcmd: Avoid memory leak in exclude_cmds")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/lib/subcmd/help.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/tools/lib/subcmd/help.c b/tools/lib/subcmd/help.c
index 67a8d6b740ea..b59ca17e406d 100644
--- a/tools/lib/subcmd/help.c
+++ b/tools/lib/subcmd/help.c
@@ -77,10 +77,11 @@ void exclude_cmds(struct cmdnames *cmds, struct cmdnames *excludes)
 			ei++;
 		}
 	}
-
-	while (ci < cmds->cnt) {
-		zfree(&cmds->names[cj]);
-		cmds->names[cj++] = cmds->names[ci++];
+	if (ci != cj) {
+		while (ci < cmds->cnt) {
+			zfree(&cmds->names[cj]);
+			cmds->names[cj++] = cmds->names[ci++];
+		}
 	}
 	for (ci = cj; ci < cmds->cnt; ci++)
 		zfree(&cmds->names[ci]);
-- 
2.41.0.162.gfafddb0af9-goog
Re: [PATCH v1] lib subcmd: Avoid use-after-free when no commands are excluded
Posted by Namhyung Kim 2 years, 7 months ago
On Mon, Jun 26, 2023 at 3:22 PM Ian Rogers <irogers@google.com> wrote:
>
> The array shortening may be an unnecessary array copy. Before commit
> 657a3efee43a ("lib subcmd: Avoid memory leak in exclude_cmds") this
> was benign, but afterwards this could lead to a segv.
>
> Fixes: 657a3efee43a ("lib subcmd: Avoid memory leak in exclude_cmds")
> Signed-off-by: Ian Rogers <irogers@google.com>
> ---
>  tools/lib/subcmd/help.c | 9 +++++----
>  1 file changed, 5 insertions(+), 4 deletions(-)
>
> diff --git a/tools/lib/subcmd/help.c b/tools/lib/subcmd/help.c
> index 67a8d6b740ea..b59ca17e406d 100644
> --- a/tools/lib/subcmd/help.c
> +++ b/tools/lib/subcmd/help.c
> @@ -77,10 +77,11 @@ void exclude_cmds(struct cmdnames *cmds, struct cmdnames *excludes)
>                         ei++;
>                 }
>         }
> -
> -       while (ci < cmds->cnt) {
> -               zfree(&cmds->names[cj]);
> -               cmds->names[cj++] = cmds->names[ci++];
> +       if (ci != cj) {
> +               while (ci < cmds->cnt) {
> +                       zfree(&cmds->names[cj]);
> +                       cmds->names[cj++] = cmds->names[ci++];

I'm not sure I'm following the logic in this function well
but it seems we also need to check the same thing
in the above loop - if (cmp < 0).

Thanks,
Namhyung


> +               }
>         }
>         for (ci = cj; ci < cmds->cnt; ci++)
>                 zfree(&cmds->names[ci]);
> --
> 2.41.0.162.gfafddb0af9-goog
>