help_unknown_ref(): duplicate collected refnames

When "git merge" sees an unknown refname, we iterate through the refs to try to suggest some possible alternates. We do so with for_each_ref(), and in the callback we add some of the refnames we get to a string_list that is declared with NODUP, directly adding a pointer into the refname string our callback received. But the for_each_ref() machinery does not promise that the refname string will remain valid, and as a result we may print garbage memory. The code in question dates back to its inception in e56181060e (help: add help_unknown_ref(), 2013-05-04). But back then, the refname strings generally did remain stable, at least immediately after the for_each_ref() call. Later, in d1cf15516f (packed_ref_iterator_begin(): iterate using `mmapped_ref_iterator`, 2017-09-25), we started consistently re-using a separate buffer for packed refs. The fix is simple: duplicate the strings we intend to collect. We already call string_list_clear(), so the memory is correctly freed. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed May 14, 2019 at 08:04 UTC 8ed51b066681adc88723dbe07b878904c348fdf6
2 files changed +15 -1
help.c
+1 -1
@@ -773,7 +773,7 @@ static int append_similar_ref(const char *refname, const struct object_id *oid,
773 static struct string_list guess_refs(const char *ref)
774 {
775 struct similar_ref_cb ref_cb;
776 - struct string_list similar_refs = STRING_LIST_INIT_NODUP;
776 + struct string_list similar_refs = STRING_LIST_INIT_DUP;
777
778 ref_cb.base_ref = ref;
779 ref_cb.similar_refs = &similar_refs;
t/t7600-merge.sh
+14
@@ -822,4 +822,18 @@ test_expect_success EXECKEEPSPID 'killed merge can be completed with --continue'
822 verify_parents $c0 $c1
823 '
824
825 +test_expect_success 'merge suggests matching remote refname' '
826 + git commit --allow-empty -m not-local &&
827 + git update-ref refs/remotes/origin/not-local HEAD &&
828 + git reset --hard HEAD^ &&
829 +
830 + # This is white-box testing hackery; we happen to know
831 + # that reading packed refs is more picky about the memory
832 + # ownership of strings we pass to for_each_ref() callbacks.
833 + git pack-refs --all --prune &&
834 +
835 + test_must_fail git merge not-local 2>stderr &&
836 + grep origin/not-local stderr
837 +'
838 +
839 test_done