builtin/help: fix leaks in `check_git_cmd()`

The `check_git_cmd()` function is declared to return a string constant. And while it sometimes does return a constant, it may also return an allocated string in two cases: - When handling aliases. This case is already marked with `UNLEAK()` to work around the leak. - When handling unknown commands in case "help.autocorrect" is enabled. This one is not marked with `UNLEAK()`. The function only has a single caller, so let's fix its return type to be non-constant, consistently return an allocated string and free it at its callsite to plug the leak. 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 2379b5c90038b2c334ff62cce62d50b4a8e78360
1 file changed +7 -6
builtin/help.c
+7 -6
@@ -551,12 +551,12 @@ static void show_html_page(const char *page)
551 open_html(page_path.buf);
552 }
553
554 -static const char *check_git_cmd(const char* cmd)
554 +static char *check_git_cmd(const char *cmd)
555 {
556 char *alias;
557
558 if (is_git_command(cmd))
559 - return cmd;
559 + return xstrdup(cmd);
560
561 alias = alias_lookup(cmd);
562 if (alias) {
@@ -589,14 +589,13 @@ static const char *check_git_cmd(const char* cmd)
589 die(_("bad alias.%s string: %s"), cmd,
590 split_cmdline_strerror(count));
591 free(argv);
592 - UNLEAK(alias);
592 return alias;
593 }
594
595 if (exclude_guides)
596 return help_unknown_cmd(cmd);
597
599 - return cmd;
598 + return xstrdup(cmd);
599 }
600
601 static void no_help_format(const char *opt_mode, enum help_format fmt)
@@ -642,6 +641,7 @@ int cmd_help(int argc,
641 {
642 int nongit;
643 enum help_format parsed_help_format;
644 + char *command = NULL;
645 const char *page;
646
647 argc = parse_options(argc, argv, prefix, builtin_help_options,
@@ -713,9 +713,9 @@ int cmd_help(int argc,
713 if (help_format == HELP_FORMAT_NONE)
714 help_format = parse_help_format(DEFAULT_HELP_FORMAT);
715
716 - argv[0] = check_git_cmd(argv[0]);
716 + command = check_git_cmd(argv[0]);
717
718 - page = cmd_to_page(argv[0]);
718 + page = cmd_to_page(command);
719 switch (help_format) {
720 case HELP_FORMAT_NONE:
721 case HELP_FORMAT_MAN:
@@ -729,5 +729,6 @@ int cmd_help(int argc,
729 break;
730 }
731
732 + free(command);
733 return 0;
734 }