e0195c4e19 (apply: reject an empty "diff --git" header, 2026-11-25)
reports a "diff --git" line without header lines as a corrupt patch.
But find_header() stops looking when fewer than 6 bytes are left after
the current line, and it does that before checking for "diff --git".
So a "diff --git" line with fewer than 6 bytes after it, such as one
at the end of the input, is still skipped, and the patches before it
apply without an error.
Check for "diff --git" before that size check, so this line is no
longer skipped. The size check stays in front of the "--- " and "+++ "
check, which reads the next line. Only compare lines longer than 11
bytes, so that memcmp() does not read past the end of a short last
line.
Reported-by: Junio C Hamano <gits…@pobox.com>
Signed-off-by: Tanga Joris <tang…@gmail.com>
---
This applies on top of tj/apply-reject-corrupt-headers. Junio pointed
out this case in his review of v4:
https://lore.kernel.org/git/xmqq…@gitster.g/
apply.c | 8 ++++----
t/t4133-apply-filenames.sh | 24 ++++++++++++++++++++++++
2 files changed, 28 insertions(+), 4 deletions(-)
diff --git a/apply.c b/apply.c
index 2a0220fde0..b65a59fafb 100644
--- a/apply.c
+++ b/apply.c
@@ -1655,14 +1655,11 @@ static int find_header(struct apply_state *state,
return -128;
}
- if (size < len + 6)
- break;
-
/*
* Git patch? It might not have a real patch, just a rename
* or mode change, so we handle that specially
*/
- if (!memcmp("diff --git ", line, 11)) {
+ if (len > 11 && !memcmp("diff --git ", line, 11)) {
int linenr = state->linenr;
int git_hdr_len = parse_git_diff_header(&state->root,
state->patch_input_file,
@@ -1680,6 +1677,9 @@ static int find_header(struct apply_state *state,
return offset;
}
+ if (size < len + 6)
+ break;
+
/* --- followed by +++ ? */
if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
continue;
diff --git a/t/t4133-apply-filenames.sh b/t/t4133-apply-filenames.sh
index 953749734b..43d67f2108 100755
--- a/t/t4133-apply-filenames.sh
+++ b/t/t4133-apply-filenames.sh
@@ -164,6 +164,30 @@ test_expect_success 'reject a "diff --git" line followed by another' '
test_cmp expect g
'
+test_expect_success 'reject a "diff --git" line at the end of the patch' '
+ test_when_finished "rm -f g" &&
+ echo 1 >g &&
+ cat >end_of_patch.diff <<-\EOF &&
+ diff --git a/g b/g
+ index d00491f..0cfbf08 100644
+ --- a/g
+ +++ b/g
+ @@ -1 +1 @@
+ -1
+ +2
+ diff --git a/x b/x
+ EOF
+ reject_empty_git_header end_of_patch.diff 8 &&
+ test_must_fail git apply end_of_patch.diff &&
+ echo 1 >expect &&
+ test_cmp expect g
+'
+
+test_expect_success 'reject a patch with only a "diff --git" line' '
+ echo "diff --git a/x b/x" >only_header.diff &&
+ reject_empty_git_header only_header.diff 1
+'
+
for old in /dev/null a/f
do
test_expect_success "reject \"--- $old\" before \"new file mode\"" '
base-commit: 744a0c0bee0a62e05d7fe4c262340d114dd9ddfa
--
2.43.0