submodule--helper: fix obscure leak in module_add()

Fix an obscure leak in module_add(), if the "git add" command we were piping to failed we'd fail to strbuf_release(&sb). This fixes a leak introduced in a6226fd772b (submodule--helper: convert the bulk of cmd_add() to C, 2021-08-10). In fixing it move to a "goto cleanup" pattern, and since we need to introduce a "ret" variable to do that let's also get rid of the intermediate "exit_code" variable. The initialization to "-1" in a6226fd772b has always been redundant, we'd only use the "exit_code" value after assigning the return value of pipe_command() to it. Signed-off-by: Ævar Arnfjörð Bjarmason <avarab@gmail.com> Reviewed-by: Glen Choo <chooglen@google.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Ævar Arnfjörð Bjarmason committed Sep 1, 2022 at 01:14 UTC 4e83605d38e30ba56878c121443695cb7eef0f56
1 file changed +11 -11
builtin/submodule--helper.c
+11 -11
@@ -3293,6 +3293,8 @@ static int module_add(int argc, const char **argv, const char *prefix)
3293 N_("git submodule add [<options>] [--] <repository> [<path>]"),
3294 NULL
3295 };
3296 + struct strbuf sb = STRBUF_INIT;
3297 + int ret = 1;
3298
3299 argc = parse_options(argc, argv, prefix, options, usage, 0);
3300
@@ -3342,21 +3344,17 @@ static int module_add(int argc, const char **argv, const char *prefix)
3344 die_on_repo_without_commits(add_data.sm_path);
3345
3346 if (!force) {
3345 - int exit_code = -1;
3346 - struct strbuf sb = STRBUF_INIT;
3347 struct child_process cp = CHILD_PROCESS_INIT;
3348
3349 cp.git_cmd = 1;
3350 cp.no_stdout = 1;
3351 strvec_pushl(&cp.args, "add", "--dry-run", "--ignore-missing",
3352 "--no-warn-embedded-repo", add_data.sm_path, NULL);
3353 - if ((exit_code = pipe_command(&cp, NULL, 0, NULL, 0, &sb, 0))) {
3353 + if ((ret = pipe_command(&cp, NULL, 0, NULL, 0, &sb, 0))) {
3354 strbuf_complete_line(&sb);
3355 fputs(sb.buf, stderr);
3356 - free(add_data.sm_path);
3357 - return exit_code;
3356 + goto cleanup;
3357 }
3359 - strbuf_release(&sb);
3358 }
3359
3360 if(!add_data.sm_name)
@@ -3371,15 +3369,17 @@ static int module_add(int argc, const char **argv, const char *prefix)
3369 add_data.progress = !!progress;
3370 add_data.dissociate = !!dissociate;
3371
3374 - if (add_submodule(&add_data)) {
3375 - free(add_data.sm_path);
3376 - return 1;
3377 - }
3372 + if (add_submodule(&add_data))
3373 + goto cleanup;
3374 configure_added_submodule(&add_data);
3375 +
3376 + ret = 0;
3377 +cleanup:
3378 free(add_data.sm_path);
3379 free(to_free);
3380 + strbuf_release(&sb);
3381
3382 - return 0;
3382 + return ret;
3383 }
3384
3385 #define SUPPORT_SUPER_PREFIX (1<<0)