midx-write: use cleanup when incremental midx fails

The incremental mode of writing a multi-pack-index has a few extra conditions that could lead to failure, but these are currently short-ciruiting with 'return -1' instead of setting the method's 'result' variable and going to the cleanup tag. Replace these returns with gotos to avoid memory issues when exiting early due to error conditions. Unfortunately, these error conditions are difficult to reproduce with test cases, which is perhaps one reason why the memory loss was not caught by existing test cases in memory tracking modes. Signed-off-by: Derrick Stolee <stolee@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Derrick Stolee committed Sep 5, 2025 at 19:26 UTC 9c2262d65dee8c1e3656b01f7db0660181902d2a
1 file changed +12 -6
midx-write.c
+12 -6
@@ -1345,13 +1345,15 @@ static int write_midx_internal(struct repository *r, const char *object_dir,
1345 incr = mks_tempfile_m(midx_name.buf, 0444);
1346 if (!incr) {
1347 error(_("unable to create temporary MIDX layer"));
1348 - return -1;
1348 + result = -1;
1349 + goto cleanup;
1350 }
1351
1352 if (adjust_shared_perm(r, get_tempfile_path(incr))) {
1353 error(_("unable to adjust shared permissions for '%s'"),
1354 get_tempfile_path(incr));
1354 - return -1;
1355 + result = -1;
1356 + goto cleanup;
1357 }
1358
1359 f = hashfd(r->hash_algo, get_tempfile_fd(incr),
@@ -1451,18 +1453,22 @@ static int write_midx_internal(struct repository *r, const char *object_dir,
1453
1454 if (!chainf) {
1455 error_errno(_("unable to open multi-pack-index chain file"));
1454 - return -1;
1456 + result = -1;
1457 + goto cleanup;
1458 }
1459
1457 - if (link_midx_to_chain(ctx.base_midx) < 0)
1458 - return -1;
1460 + if (link_midx_to_chain(ctx.base_midx) < 0) {
1461 + result = -1;
1462 + goto cleanup;
1463 + }
1464
1465 get_split_midx_filename_ext(r->hash_algo, &final_midx_name,
1466 object_dir, midx_hash, MIDX_EXT_MIDX);
1467
1468 if (rename_tempfile(&incr, final_midx_name.buf) < 0) {
1469 error_errno(_("unable to rename new multi-pack-index layer"));
1465 - return -1;
1470 + result = -1;
1471 + goto cleanup;
1472 }
1473
1474 strbuf_release(&final_midx_name);