sparse-checkout: free duplicate hashmap entries

In insert_recursive_pattern(), we create a new pattern_entry to insert into the parent_hashmap. If we find that the same entry already exists in the hashmap, we skip adding the new one. But we forget to free the new one, creating a leak. We can fix it by cleaning up the discarded entry. It would probably be possible to avoid creating it in the first place, but it's non-trivial. We'd have to define a "keydata" struct that lets us compare the existing entries to the broken-out fields. It's probably not worth the complexity, so we'll punt on that for now. There is one subtlety here: our insertion is happening in a loop, with each iteration looking at the pattern we just inserted (hence the "recursive" in the name). So if we skip insertion, what do we look at? The obvious answer is that we should remember the existing duplicate we found and use that. But I _think_ in that case, we probably already have all of the recursive bits already (from when the original entry was added). And so just breaking out of the loop would be correct. But I'm not 100% sure on that; after all, the original leaky code could have done the same break, but it didn't. So I went with the "obvious answer" above, which has no chance of changing the behavior aside from fixing the leak. With this patch, t1091 can now be marked leak-free. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Jun 4, 2024 at 06:13 UTC 6d107751b299e2d0439909d01439b245dd820c5d
2 files changed +9 -1
builtin/sparse-checkout.c
+8 -1
@@ -523,6 +523,7 @@ static void insert_recursive_pattern(struct pattern_list *pl, struct strbuf *pat
523 char *slash = strrchr(e->pattern, '/');
524 char *oldpattern = e->pattern;
525 size_t newlen;
526 + struct pattern_entry *dup;
527
528 if (!slash || slash == e->pattern)
529 break;
@@ -533,8 +534,14 @@ static void insert_recursive_pattern(struct pattern_list *pl, struct strbuf *pat
534 e->pattern = xstrndup(oldpattern, newlen);
535 hashmap_entry_init(&e->ent, fspathhash(e->pattern));
536
536 - if (!hashmap_get_entry(&pl->parent_hashmap, e, ent, NULL))
537 + dup = hashmap_get_entry(&pl->parent_hashmap, e, ent, NULL);
538 + if (!dup) {
539 hashmap_add(&pl->parent_hashmap, &e->ent);
540 + } else {
541 + free(e->pattern);
542 + free(e);
543 + e = dup;
544 + }
545 }
546 }
547
t/t1091-sparse-checkout-builtin.sh
+1
@@ -8,6 +8,7 @@ export GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME
8 GIT_TEST_SPLIT_INDEX=false
9 export GIT_TEST_SPLIT_INDEX
10
11 +TEST_PASSES_SANITIZE_LEAK=true
12 . ./test-lib.sh
13
14 list_files() {