Skip to content

Commit 3aef7a0

Browse files
pks-tgitster
authored andcommitted
git: fix leaking argv when handling builtins
In `handle_builtin()` we may end up creating an ad-hoc argv array in case we see that the command line contains the "--help" parameter. In this case we observe two memory leaks though: - We leak the `struct strvec` itself because we directly exit after calling `run_builtin()`, without bothering about any cleanups. - Even if we free'd that vector we'd end up leaking some of its strings because `run_builtin()` will modify the array. Plug both of these leaks. Signed-off-by: Patrick Steinhardt <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 0f26223 commit 3aef7a0

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

git.c

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,7 @@ static void strip_extension(const char **argv)
711711
static void handle_builtin(int argc, const char **argv)
712712
{
713713
struct strvec args = STRVEC_INIT;
714+
const char **argv_copy = NULL;
714715
const char *cmd;
715716
struct cmd_struct *builtin;
716717

@@ -731,13 +732,28 @@ static void handle_builtin(int argc, const char **argv)
731732
}
732733

733734
argc++;
734-
argv = args.v;
735+
736+
/*
737+
* `run_builtin()` will modify the argv array, so we need to
738+
* create a shallow copy such that we can free all of its
739+
* strings.
740+
*/
741+
CALLOC_ARRAY(argv_copy, argc + 1);
742+
COPY_ARRAY(argv_copy, args.v, argc);
743+
744+
argv = argv_copy;
735745
}
736746

737747
builtin = get_builtin(cmd);
738-
if (builtin)
739-
exit(run_builtin(builtin, argc, argv));
748+
if (builtin) {
749+
int ret = run_builtin(builtin, argc, argv);
750+
strvec_clear(&args);
751+
free(argv_copy);
752+
exit(ret);
753+
}
754+
740755
strvec_clear(&args);
756+
free(argv_copy);
741757
}
742758

743759
static void execv_dashed_external(const char **argv)

t/t0012-help.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
test_description='help'
44

5+
TEST_PASSES_SANITIZE_LEAK=true
56
. ./test-lib.sh
67

78
configure_help () {

0 commit comments

Comments
 (0)