merge: fix NULL pointer dereference when merging nothing into void

When we are on an unborn branch and merging only one foreign parent, we allow "git merge" to fast-forward to that foreign parent commit. This codepath incorrectly attempted to dereference the list of parents that the merge is going to record even when the list is empty. It must refuse to operate instead when there is no parent. All other codepaths make sure the list is not empty before they dereference it, and are safe. Reported-by: Jose Ivan B. Vilarouca Filho Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Mar 21, 2016 at 12:01 UTC b84e65d40929ec1146f54dcf4c9dbf8dc58467d0
2 files changed +15 -5
builtin/merge.c
+5 -5
@@ -1257,12 +1257,12 @@ int cmd_merge(int argc, const char **argv, const char *prefix)
1257 builtin_merge_options);
1258
1259 if (!head_commit) {
1260 - struct commit *remote_head;
1260 /*
1261 * If the merged head is a valid one there is no reason
1262 * to forbid "git merge" into a branch yet to be born.
1263 * We do the same for "git pull".
1264 */
1265 + unsigned char *remote_head_sha1;
1266 if (squash)
1267 die(_("Squash commit into empty head not supported yet"));
1268 if (fast_forward == FF_NO)
@@ -1270,13 +1270,13 @@ int cmd_merge(int argc, const char **argv, const char *prefix)
1270 "an empty head"));
1271 remoteheads = collect_parents(head_commit, &head_subsumed,
1272 argc, argv, NULL);
1273 - remote_head = remoteheads->item;
1274 - if (!remote_head)
1273 + if (!remoteheads)
1274 die(_("%s - not something we can merge"), argv[0]);
1275 if (remoteheads->next)
1276 die(_("Can merge only exactly one commit into empty head"));
1278 - read_empty(remote_head->object.oid.hash, 0);
1279 - update_ref("initial pull", "HEAD", remote_head->object.oid.hash,
1277 + remote_head_sha1 = remoteheads->item->object.oid.hash;
1278 + read_empty(remote_head_sha1, 0);
1279 + update_ref("initial pull", "HEAD", remote_head_sha1,
1280 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
1281 goto done;
1282 }
t/t7600-merge.sh
+10
@@ -725,4 +725,14 @@ test_expect_success 'merge detects mod-256 conflicts (resolve)' '
725 test_must_fail git merge -s resolve master
726 '
727
728 +test_expect_success 'merge nothing into void' '
729 + git init void &&
730 + (
731 + cd void &&
732 + git remote add up .. &&
733 + git fetch up &&
734 + test_must_fail git merge FETCH_HEAD
735 + )
736 +'
737 +
738 test_done