stash show: fix segfault with --{include,only}-untracked

When `git stash show --include-untracked` or `git stash show --only-untracked` is run on a stash that doesn't include an untracked entry, a segfault occurs. This happens because we do not check whether the untracked entry is actually present and just attempt to blindly dereference it. Ensure that the untracked entry is present before actually attempting to dereference it. Signed-off-by: Denton Liu <liu.denton@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Denton Liu committed May 12, 2021 at 13:16 UTC 1ff595d218d9175eee1db753844044c2746d0515
2 files changed +21 -2
builtin/stash.c
+6 -2
@@ -900,10 +900,14 @@ static int show_stash(int argc, const char **argv, const char *prefix)
900 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
901 break;
902 case UNTRACKED_ONLY:
903 - diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
903 + if (info.has_u)
904 + diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
905 break;
906 case UNTRACKED_INCLUDE:
906 - diff_include_untracked(&info, &rev.diffopt);
907 + if (info.has_u)
908 + diff_include_untracked(&info, &rev.diffopt);
909 + else
910 + diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
911 break;
912 }
913 log_tree_diff_flush(&rev);
t/t3905-stash-include-untracked.sh
+15
@@ -405,4 +405,19 @@ test_expect_success 'stash show --include-untracked errors on duplicate files' '
405 test_i18ngrep "worktree and untracked commit have duplicate entries: tracked" err
406 '
407
408 +test_expect_success 'stash show --{include,only}-untracked on stashes without untracked entries' '
409 + git reset --hard &&
410 + git clean -xf &&
411 + >tracked &&
412 + git add tracked &&
413 + git stash &&
414 +
415 + git stash show >expect &&
416 + git stash show --include-untracked >actual &&
417 + test_cmp expect actual &&
418 +
419 + git stash show --only-untracked >actual &&
420 + test_must_be_empty actual
421 +'
422 +
423 test_done