help: fix leaking return value from `help_unknown_cmd()`

While `help_unknown_cmd()` would usually die on an unknown command, it instead returns an autocorrected command when "help.autocorrect" is set. But while the function is declared to return a string constant, it actually returns an allocated string in that case. Callers thus aren't aware that they have to free the string, leading to a memory leak. Fix the function return type to be non-constant and free the returned value at its only callsite. Note that we cannot simply take ownership of `main_cmds.names[0]->name` and then eventually free it. This is because the `struct cmdname` is using a flex array to allocate the name, so the name pointer points into the middle of the structure and thus cannot be freed. Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Patrick Steinhardt committed Nov 20, 2024 at 14:39 UTC 7720dbe99b303b3d658898587e02d7cf224a93c3
3 files changed +7 -6
git.c
+3 -1
@@ -961,7 +961,9 @@ int cmd_main(int argc, const char **argv)
961 exit(1);
962 }
963 if (!done_help) {
964 - strvec_replace(&args, 0, help_unknown_cmd(cmd));
964 + char *assumed = help_unknown_cmd(cmd);
965 + strvec_replace(&args, 0, assumed);
966 + free(assumed);
967 cmd = args.v[0];
968 done_help = 1;
969 } else {
help.c
+3 -4
@@ -612,7 +612,7 @@ static const char bad_interpreter_advice[] =
612 N_("'%s' appears to be a git command, but we were not\n"
613 "able to execute it. Maybe git-%s is broken?");
614
615 -const char *help_unknown_cmd(const char *cmd)
615 +char *help_unknown_cmd(const char *cmd)
616 {
617 struct help_unknown_cmd_config cfg = { 0 };
618 int i, n, best_similarity = 0;
@@ -695,9 +695,8 @@ const char *help_unknown_cmd(const char *cmd)
695 ; /* still counting */
696 }
697 if (cfg.autocorrect && n == 1 && SIMILAR_ENOUGH(best_similarity)) {
698 - const char *assumed = main_cmds.names[0]->name;
699 - main_cmds.names[0] = NULL;
700 - cmdnames_release(&main_cmds);
698 + char *assumed = xstrdup(main_cmds.names[0]->name);
699 +
700 fprintf_ln(stderr,
701 _("WARNING: You called a Git command named '%s', "
702 "which does not exist."),
help.h
+1 -1
@@ -32,7 +32,7 @@ void list_all_other_cmds(struct string_list *list);
32 void list_cmds_by_category(struct string_list *list,
33 const char *category);
34 void list_cmds_by_config(struct string_list *list);
35 -const char *help_unknown_cmd(const char *cmd);
35 +char *help_unknown_cmd(const char *cmd);
36 void load_command_list(const char *prefix,
37 struct cmdnames *main_cmds,
38 struct cmdnames *other_cmds);