Commit

16abad336073665c13c09b1026dd1227688b9c10

dir: do not apply prefix to negative pathspecs

common_prefix_len() derives the common prefix solely from non-exclude
pathspec items. However, match_pathspec_with_flags() also passes that
prefix when matching exclude items.

This can produce incorrect results because that prefix does not
necessarily match an exclude item. For example, given non-exclude items
"a/b" and "a/c" and an exclude item "x/b", stripping the two-byte
prefix from both the pathname "a/b/m" and pattern "x/b" makes the
remaining strings match and incorrectly excludes the pathname.

If an exclude item is shorter than the prefix, match_pathspec_item()
instead advances item->match beyond its allocation and subtracts the
prefix from item->len, producing a negative matchlen. It then
dereferences the out-of-bounds pointer. If the resulting byte is not
NUL, matchlen is converted to size_t when passed to ps_strncmp(), which
may cause a much larger out-of-bounds read.

The out-of-bounds access can be reproduced with AddressSanitizer:

    make SANITIZE=address CFLAGS="-g -O0" git
    git init test &&
    cd test &&
    DIR=$(printf "a%.0s" {1..150}) &&
    mkdir -p "$DIR" &&
    touch "$DIR/f.txt" &&
    git add -A &&
    git commit -m test &&
    ../git ls-files -- "$DIR/" ":(exclude)xy"

Fix the bug by using a zero prefix when matching exclude items. Add
regression tests for both the deterministic incorrect match and the
shorter exclude item that causes the out-of-bounds access.

Signed-off-by: Yannik Tausch <dev@ytausch.de>
Signed-off-by: Junio C Hamano <gitster@pobox.com>

Yannik Tausch <dev@ytausch.de> · 2026-09-14 07:25 UTC · committed by Junio C Hamano

Browse files
2 files changed, +19 −1
modified dir.c
@@ -593,7 +593,7 @@ static int match_pathspec_with_flags(struct index_state *istate,
593 593 if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
594 594 return positive;
595 595 negative = do_match_pathspec(istate, ps, name, namelen,
596 - prefix, seen,
596 + 0, seen,
597 597 flags | DO_MATCH_EXCLUDE);
598 598 return negative ? 0 : positive;
599 599 }
modified t/t6132-pathspec-exclude.sh
@@ -183,6 +183,24 @@ EOF
183 183 test_cmp expect actual
184 184 '
185 185
186 + test_expect_success 'negative pathspec shorter than positive pathspec prefix' '
187 + git ls-files -- sub/sub/ ":(exclude)sub2" >actual &&
188 + cat <<-\EOF >expect &&
189 + sub/sub/file
190 + sub/sub/sub/file
191 + EOF
192 + test_cmp expect actual
193 + '
194 +
195 + test_expect_success 'exclude is matched against the full path' '
196 + git ls-files -- sub/sub/ ":(exclude)zzzzzzz" >actual &&
197 + cat <<-\EOF >expect &&
198 + sub/sub/file
199 + sub/sub/sub/file
200 + EOF
201 + test_cmp expect actual
202 + '
203 +
186 204 test_expect_success 'multiple exclusions' '
187 205 git ls-files -- ":^*/file2" ":^sub2" >actual &&
188 206 cat <<-\EOF >expect &&