Skip to contentSkip to conversation

lib subcmd: Avoid use-after-free when no commands are excluded

PATCH Superseded Ian Rogers 2 participants 2 messages Jun 26, 2023 – Jul 1, 2023

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Ian Rogers

author
#0 lore raw

PATCH 1/1 lib subcmd: Avoid use-after-free when no commands are excluded

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")
---
 tools/lib/subcmd/help.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
tools/lib/subcmd/help.c +5 -4
index 67a8d6b740ea..b59ca17e406d 100644
@@ -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]);
Signature · 1 line
2.41.0.162.gfafddb0af9-goog
#1 lore raw
Quoted 17 lines · Ian Rogers

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")
---
 tools/lib/subcmd/help.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
tools/lib/subcmd/help.c +0 -0
index 67a8d6b740ea..b59ca17e406d 100644
@@ -77,10 +77,11 @@ void exclude_cmds(struct cmdnames *cmds, struct cmdnames *excludes)
                        ei++;

tools/lib/subcmd/help.c void exclude_cmds(struct cmdnames *cmds, struct cmdnames *excludes) · line 83

Quoted 10 lines
tools/lib/subcmd/help.c +4 -4
                }
        }
-
-       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

Quoted 7 lines
tools/lib/subcmd/help.c +1 -1
+               }
        }
        for (ci = cj; ci < cmds->cnt; ci++)
                zfree(&cmds->names[ci]);
--

2.41.0.162.gfafddb0af9-goog