diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
PATCH 1/1 diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
From: Elijah Newren <[email protected]>
f85b49f3d4a (diff: improve scaling of filenames in diffstat to handle UTF-8 chars, 2024-10-27) introduced a loop in show_stats() that calls utf8_width() repeatedly to skip leading characters until the displayed width fits. However, utf8_width() can return problematic values:
- For invalid UTF-8 sequences, pick_one_utf8_char() sets the name pointer to NULL and utf8_width() returns 0. Since name_len does not change, the loop iterates once more and pick_one_utf8_char() dereferences the NULL pointer, crashing.
- For control characters, utf8_width() returns -1, so name_len grows when it is expected to shrink. This can cause the loop to consume more characters than the string contains, reading past the trailing NUL.
By default, fill_print_name() will C-quotes filenames which escapes control characters and invalid bytes to printable text. That avoids this bug from being triggered; however, with core.quotePath=false, raw bytes can reach this code.
Add tests exercising both failure modes with core.quotePath=false and a narrow --stat-name-width to force truncation: one with a bare 0xC0 byte (invalid UTF-8 lead byte, triggers NULL deref) and one with a 0x01 byte (control character, causes the loop to read past the end of the string).
Fix the bug by:
- Adding a *name check to terminate the loop at end-of-string
- Detecting the NULL pointer from invalid UTF-8 and falling back to showing the full untruncated name
- Breaking on negative width (control characters)
---
diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
Maintainer note: This is a new bug from the v2.54 cycle
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-2093%2Fnewren%2Ffix%2Fdiffstat-utf8-loop-v1
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2093/newren/fix/diffstat-utf8-loop-v1
Pull-Request: https://github.com/gitgitgadget/git/pull/2093
diff.c | 13 +++++++++++-- t/t4052-stat-output.sh | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-)
diff.c +11 -2
@@ -3093,8 +3093,17 @@ static void show_stats(struct diffstat_t *data, struct diff_options *options)if (len <0 ) len =0 ; -while (name_len > len) - name_len -=utf8_width ((const char **)&name,NULL ); +while (name_len > len && *name) { +int w =utf8_width ((const char **)&name,NULL ); +if (!name) {/* Invalid UTF-8 */ + name = file->print_name; + name_len =utf8_strwidth (name); +break ; + } +if (w <0 )/* control character */ +break ; + name_len -= w; + } slash =strchr (name,'/' );if (slash)
t/t4052-stat-output.sh +25 -0
@@ -445,4 +445,29 @@ test_expect_success 'diffstat where line_prefix contains ANSI escape codes is co test_grep "<RED>|<RESET> ${FILENAME_TRIMMED} | 0" out ' +test_expect_success 'diffstat truncation with invalid UTF-8 does not crash' ' + empty_blob=$(git hash-object -w --stdin </dev/null) && + printf "100644 blob $empty_blob\taaa-\300-aaa\n" | + git mktree >tree_file && + tree=$(cat tree_file) && + empty_tree=$(git mktree </dev/null) && + c1=$(git commit-tree -m before $empty_tree) && + c2=$(git commit-tree -m after -p $c1 $tree) && + git -c core.quotepath=false diff --stat --stat-name-width=5 $c1..$c2 >output && + test_grep "| 0" output +' + +test_expect_success FUNNYNAMES 'diffstat truncation with control chars does not crash' ' + FNAME=$(printf "aaa-\x01-aaa") && + git commit --allow-empty -m setup && + >$FNAME && + git add -- $FNAME && + git commit -m "add file with control char name" && + git -c core.quotepath=false diff --stat --stat-name-width=5 HEAD~1..HEAD >output && + test_grep "| 0" output && + rm -- $FNAME && + git rm -- $FNAME && + git commit -m "remove test file" +' + test_done
base-commit: 9f223ef1c026d91c7ac68cc0211bde255dda6199
Signature · 1 line
gitgitgadget
Quoted 6 lines · Elijah Newren via GitGitGadget
From: Elijah Newren <[email protected]>
f85b49f3d4a(diff: improve scaling of filenames in diffstat to handle UTF-8 chars, 2024-10-27) introduced a loop inshow_stats()that callsutf8_width()repeatedly to skip leading characters until the displayed width fits.
A tangent, but I get a datestamp for the same f85b49f3 (diff:
improve scaling of filenames in diffstat to handle UTF-8 chars, 2026-01-16) that is different from what you showed above. Did you find a bug in "git show -s --pretty=reference"?
Quoted 10 lines
diff.c +0
-2@@ -3093,8 +3093,17 @@ static void show_stats(struct diffstat_t *data, struct diff_options *options)if (len <0 ) len =0 ; -while (name_len > len) - name_len -=utf8_width ((const char **)&name,NULL );
diff.c static void show_stats(struct diffstat_t *data, struct diff_options *options) · line 3105
Quoted 10 lines
diff.c +7
-0+while (name_len > len && *name) { +int w =utf8_width ((const char **)&name,NULL ); +if (!name) {/* Invalid UTF-8 */ + name = file->print_name; + name_len =utf8_strwidth (name); +break ; + }
IOW, we punt on "scaling" and instead use the full string? I was wondering if we can punt on only this segment by replacing this segment with just "..." and resync at the next slash.
diff.c static void show_stats(struct diffstat_t *data, struct diff_options *options) · line 3104
Quoted 2 lines
diff.c +2
-0+if (w <0 )/* control character */ +break ;
When we have a control characer, we instead chomp immediately before that byte, which sounds good. But then wouldn't the loop that found an Invalid UTF-8 sequence in the middle of a name want to do the same, i.e., take the good bits found so far and chomp at the broken byte?
diff.c static void show_stats(struct diffstat_t *data, struct diff_options *options) · line 3109
Quoted 5 lines
diff.c +2
-0+ name_len -= w; + }diff.c +0
-0slash =strchr (name,'/' );if (slash)
Thanks.
Quoted 10 lines · Junio C Hamano
Quoted 6 lines · Elijah Newren via GitGitGadget
From: Elijah Newren <[email protected]>
f85b49f3d4a(diff: improve scaling of filenames in diffstat to handle UTF-8 chars, 2024-10-27) introduced a loop inshow_stats()that callsutf8_width()repeatedly to skip leading characters until the displayed width fits.
Quoted 4 lines
A tangent, but I get a datestamp for the same
f85b49f3(diff:
improve scaling of filenames in diffstat to handle UTF-8 chars, 2026-01-16) that is different from what you showed above. Did you find a bug in "git show -s --pretty=reference"?
Hmm, indeed I get 2026-01-16 as well; I'm not sure what happened there.
Quoted 21 lines
Quoted 10 lines
diff.c +0
-2@@ -3093,8 +3093,17 @@ static void show_stats(struct diffstat_t *data, struct diff_options *options)if (len <0 ) len =0 ; -while (name_len > len) - name_len -=utf8_width ((const char **)&name,NULL );diff.c static void show_stats(struct diffstat_t *data, struct diff_options *options) · line 3105
Quoted 10 lines
diff.c +7
-0+while (name_len > len && *name) { +int w =utf8_width ((const char **)&name,NULL ); +if (!name) {/* Invalid UTF-8 */ + name = file->print_name; + name_len =utf8_strwidth (name); +break ; + }
Quoted 3 lines
IOW, we punt on "scaling" and instead use the full string? I was wondering if we can punt on only this segment by replacing this segment with just "..." and resync at the next slash.
Good point. Alternatively, perhaps I could just add a wrapper around utf8_width() which never sets name to NULL and never returns a negative value, and then use the original loop as-is other than calling the new function?
Quoted 9 lines
diff.c static void show_stats(struct diffstat_t *data, struct diff_options *options) · line 3104
Quoted 3 lines
diff.c +2
-0+if (w <0 )/* control character */ +break ;When we have a control characer, we instead chomp immediately before that byte, which sounds good. But then wouldn't the loop that found an Invalid UTF-8 sequence in the middle of a name want to do the same, i.e., take the good bits found so far and chomp at the broken byte?
Makes sense, though I think my simpler alternative might be easier. I'll send in a re-roll.
Quoted 8 lines
Quoted 6 lines
diff.c +2
-0+ name_len -= w; + }slash = strchr(name, '/'); if (slash)Thanks.
Quoted 2 lines · Elijah Newren
Makes sense, though I think my simpler alternative might be easier. I'll send in a re-roll.
As long as "an invalid UTF-8" and "a control character" behaves more or less the same (i.e., "eek, we cannot measure the width of the UTF-8 character at this byte position, so let's do X as a fallback", where X is the same regardless of the exact reason why we cannot measure the width), I'll be happy. If we see a slash after the problematic position, advancing to that slash might be the simplest, as that is in line with how the code works when there is no such problem, but we also need to be prepared for a filename whose last component is sufficiently long that we see no such slash after the problematic byte.
PATCH v2 1/1 diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
In reply to Elijah Newren via GitGitGadgetFrom: Elijah Newren <[email protected]>
f85b49f3d4a (diff: improve scaling of filenames in diffstat to handle UTF-8 chars, 2026-01-16) introduced a loop in show_stats() that calls utf8_width() repeatedly to skip leading characters until the displayed width fits. However, utf8_width() can return problematic values:
- For invalid UTF-8 sequences, pick_one_utf8_char() sets the name pointer to NULL and utf8_width() returns 0. Since name_len does not change, the loop iterates once more and pick_one_utf8_char() dereferences the NULL pointer, crashing.
- For control characters, utf8_width() returns -1, so name_len grows when it is expected to shrink. This can cause the loop to consume more characters than the string contains, reading past the trailing NUL.
By default, fill_print_name() will C-quotes filenames which escapes control characters and invalid bytes to printable text. That avoids this bug from being triggered; however, with core.quotePath=false, raw bytes can reach this code.
Add tests exercising both failure modes with core.quotePath=false and a narrow --stat-name-width to force truncation: one with a bare 0xC0 byte (invalid UTF-8 lead byte, triggers NULL deref) and one with a 0x01 byte (control character, causes the loop to read past the end of the string).
Fix both issues by introducing utf8_ish_width(), a thin wrapper around utf8_width() that guarantees the pointer always advances and the returned width is never negative:
- On invalid UTF-8 it restores the pointer, advances by one byte, and returns width 1 (matching the strlen()-based fallback used by utf8_strwidth()).
- On a control character it returns 0 (matching utf8_strnwidth() which skips them).
Also add a "&& *name" guard to the while-loop condition so it terminates at end-of-string even when utf8_strwidth()'s strlen() fallback causes name_len to exceed the sum of per-character widths.
---
diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
Changes since v1:
* Simplified the loop to almost what we had before via a wrapper function that always succeeds in advancing the string and never returns a negative width. (Which, as a consequence, treats invalid UTF-8 and control characters the roughly the same, unlike v1.)
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-2093%2Fnewren%2Ffix%2Fdiffstat-utf8-loop-v2
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2093/newren/fix/diffstat-utf8-loop-v2
Pull-Request: https://github.com/gitgitgadget/git/pull/2093
Range-diff vs v1:
1: fcd44d6cf8 ! 1: 4a72647ce2 diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
@@ Commit message
diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
f85b49f3d4a (diff: improve scaling of filenames in diffstat to handle
- UTF-8 chars, 2024-10-27) introduced a loop in show_stats() that calls
+ UTF-8 chars, 2026-01-16) introduced a loop in show_stats() that calls
utf8_width() repeatedly to skip leading characters until the displayed width fits. However, utf8_width() can return problematic values:
@@ Commit message
0x01 byte (control character, causes the loop to read past the end of the string).
- Fix the bug by:
- - Adding a *name check to terminate the loop at end-of-string
- - Detecting the NULL pointer from invalid UTF-8 and falling back to
- showing the full untruncated name
- - Breaking on negative width (control characters)
+ Fix both issues by introducing utf8_ish_width(), a thin wrapper
+ around utf8_width() that guarantees the pointer always advances and
+ the returned width is never negative:
+
+ - On invalid UTF-8 it restores the pointer, advances by one byte,
+ and returns width 1 (matching the strlen()-based fallback used
+ by utf8_strwidth()).
+ - On a control character it returns 0 (matching utf8_strnwidth()
+ which skips them).
+
+ Also add a "&& *name" guard to the while-loop condition so it
+ terminates at end-of-string even when utf8_strwidth()'s strlen()
+ fallback causes name_len to exceed the sum of per-character widths.
## diff.c ##
+@@ diff.c: void print_stat_summary(FILE *fp, int files,
+ print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
+ }
+
++/*
++ * Like utf8_width(), but guaranteed safe for use in loops that subtract ++ * per-character widths:
++ *
++ * - utf8_width() sets *start to NULL on invalid UTF-8 and returns 0;
++ * we restore the pointer and advance by one byte, returning width 1
++ * (matching the strlen()-based fallback in utf8_strwidth()).
++ *
++ * - utf8_width() returns -1 for control characters; we return 0
++ * (matching utf8_strnwidth() which skips them).
++ */
++static int utf8_ish_width(const char **start)
++{
++ const char *old = *start;
++ int w = utf8_width(start, NULL);
++ if (!*start) {
++ *start = old + 1;
++ return 1;
++ }
++ return (w < 0) ? 0 : w;
++}
++
+ static void show_stats(struct diffstat_t *data, struct diff_options *options)
+ {
+ int i, len, add, del, adds = 0, dels = 0;
@@ diff.c: static void show_stats(struct diffstat_t *data, struct diff_options *options)
if (len < 0)
len = 0;
- while (name_len > len)
- name_len -= utf8_width((const char**)&name, NULL);
-+ while (name_len > len && *name) {
-+ int w = utf8_width((const char **)&name, NULL);
-+ if (!name) { /* Invalid UTF-8 */
-+ name = file->print_name;
-+ name_len = utf8_strwidth(name);
-+ break;
-+ }
-+ if (w < 0) /* control character */
-+ break;
-+ name_len -= w;
-+ }
++ while (name_len > len && *name)
++ name_len -= utf8_ish_width((const char**)&name);
slash = strchr(name, '/'); if (slash)
diff.c | 26 ++++++++++++++++++++++++-- t/t4052-stat-output.sh | 25 +++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-)
diff.c +24 -2
@@ -2927,6 +2927,28 @@ void print_stat_summary(FILE *fp, int files,print_stat_summary_inserts_deletes (&o, files, insertions, deletions); } +/* +* Like utf8_width(), but guaranteed safe for use in loops that subtract +* per-character widths: +* +* - utf8_width() sets *start to NULL on invalid UTF-8 and returns 0; +* we restore the pointer and advance by one byte, returning width 1 +* (matching the strlen()-based fallback in utf8_strwidth()). +* +* - utf8_width() returns -1 for control characters; we return 0 +* (matching utf8_strnwidth() which skips them). +*/ +static int utf8_ish_width (const char **start) +{ +const char *old = *start; +int w =utf8_width (start,NULL ); +if (!*start) { + *start = old +1 ; +return 1 ; + } +return (w <0 ) ?0 : w; +} +static void show_stats (struct diffstat_t *data,struct diff_options *options) {int i, len, add, del, adds =0 , dels =0 ;
@@ -3093,8 +3115,8 @@ static void show_stats(struct diffstat_t *data, struct diff_options *options)if (len <0 ) len =0 ; -while (name_len > len) - name_len -=utf8_width ((const char **)&name,NULL ); +while (name_len > len && *name) + name_len -=utf8_ish_width ((const char **)&name); slash =strchr (name,'/' );if (slash)
t/t4052-stat-output.sh +25 -0
@@ -445,4 +445,29 @@ test_expect_success 'diffstat where line_prefix contains ANSI escape codes is co test_grep "<RED>|<RESET> ${FILENAME_TRIMMED} | 0" out ' +test_expect_success 'diffstat truncation with invalid UTF-8 does not crash' ' + empty_blob=$(git hash-object -w --stdin </dev/null) && + printf "100644 blob $empty_blob\taaa-\300-aaa\n" | + git mktree >tree_file && + tree=$(cat tree_file) && + empty_tree=$(git mktree </dev/null) && + c1=$(git commit-tree -m before $empty_tree) && + c2=$(git commit-tree -m after -p $c1 $tree) && + git -c core.quotepath=false diff --stat --stat-name-width=5 $c1..$c2 >output && + test_grep "| 0" output +' + +test_expect_success FUNNYNAMES 'diffstat truncation with control chars does not crash' ' + FNAME=$(printf "aaa-\x01-aaa") && + git commit --allow-empty -m setup && + >$FNAME && + git add -- $FNAME && + git commit -m "add file with control char name" && + git -c core.quotepath=false diff --stat --stat-name-width=5 HEAD~1..HEAD >output && + test_grep "| 0" output && + rm -- $FNAME && + git rm -- $FNAME && + git commit -m "remove test file" +' + test_done
base-commit: 9f223ef1c026d91c7ac68cc0211bde255dda6199
Signature · 1 line
gitgitgadget
Quoted 38 lines · Elijah Newren via GitGitGadget
From: Elijah Newren <[email protected]>
f85b49f3d4a(diff: improve scaling of filenames in diffstat to handle UTF-8 chars, 2026-01-16) introduced a loop inshow_stats()that callsutf8_width()repeatedly to skip leading characters until the displayed width fits. However,utf8_width()can return problematic values:- For invalid UTF-8 sequences,
pick_one_utf8_char()sets the name pointer to NULL andutf8_width()returns 0. Sincename_lendoes not change, the loop iterates once more andpick_one_utf8_char()dereferences the NULL pointer, crashing.- For control characters,
utf8_width()returns -1, soname_lengrows when it is expected to shrink. This can cause the loop to consume more characters than the string contains, reading past the trailing NUL.By default,
fill_print_name()will C-quotes filenames which escapes control characters and invalid bytes to printable text. That avoids this bug from being triggered; however, with core.quotePath=false, raw bytes can reach this code.Add tests exercising both failure modes with core.quotePath=false and a narrow --stat-name-width to force truncation: one with a bare
0xC0byte (invalid UTF-8 lead byte, triggers NULL deref) and one with a0x01byte (control character, causes the loop to read past the end of the string).Fix both issues by introducing
utf8_ish_width(), a thin wrapper aroundutf8_width()that guarantees the pointer always advances and the returned width is never negative:- On invalid UTF-8 it restores the pointer, advances by one byte, and returns width 1 (matching the strlen()-based fallback used by
utf8_strwidth()).
- On a control character it returns 0 (matchingutf8_strnwidth()which skips them).
Quoted 3 lines
Also add a "&& *name" guard to the while-loop condition so it terminates at end-of-string even when utf8_strwidth()'s
strlen()fallback causesname_lento exceed the sum of per-character widths.
i>
Quoted 1 line
Signed-off-by Elijah Newren <[email protected]>
Hi, thanks for CCing me and thanks for improving on my previous work.
All of these changes make a lot of sense, and indeed they fix issues that I didn't consider in f85b49f3d4a (diff: improve scaling of filenames in diffstat to handle UTF-8 chars, 2026-01-16).
[...]
Quoted 5 lines
t/t4052-stat-output.sh +0
-0@@ -445,4 +445,29 @@ test_expect_success 'diffstat where line_prefix contains ANSI escape codes is co
[...]
Quoted 5 lines
t/t4052-stat-output.sh +4
-0+test_expect_success FUNNYNAMES 'diffstat truncation with control chars does not crash' ' + FNAME=$(printf "aaa-\x01-aaa") && + git commit --allow-empty -m setup && + >$FNAME &&
t/t4052-stat-output.sh test_expect_success 'diffstat where line_prefix contains ANSI escape codes is co · line 473
Quoted 10 lines
t/t4052-stat-output.sh +9
-0+ git add -- $FNAME && + git commit -m "add file with control char name" && + git -c core.quotepath=false diff --stat --stat-name-width=5 HEAD~1..HEAD >output && + test_grep "| 0" output && + rm -- $FNAME && + git rm -- $FNAME && + git commit -m "remove test file" +' + test_done
The only thing that I don't quite understand is this second test.
From my tests, the previous code using:
``` [...] while (name_len > len) name_len -= utf8_width((const char**)&name, NULL); [...] ```
passes this second test just fine, while I believe it's supposed to fail.
Am I missing something?
Thanks,
Lorenzo
Quoted 27 lines · Lorenzo Pegorari
Quoted 5 lines
t/t4052-stat-output.sh +4
-0+test_expect_success FUNNYNAMES 'diffstat truncation with control chars does not crash' ' + FNAME=$(printf "aaa-\x01-aaa") && + git commit --allow-empty -m setup && + >$FNAME &&t/t4052-stat-output.sh test_expect_success 'diffstat where line_prefix contains ANSI escape codes is co · line 473
Quoted 10 lines
t/t4052-stat-output.sh +9
-0+ git add -- $FNAME && + git commit -m "add file with control char name" && + git -c core.quotepath=false diff --stat --stat-name-width=5 HEAD~1..HEAD >output && + test_grep "| 0" output && + rm -- $FNAME && + git rm -- $FNAME && + git commit -m "remove test file" +' + test_doneThe only thing that I don't quite understand is this second test.
From my tests, the previous code using:
``` [...] while (name_len > len) name_len -= utf8_width((const char**)&name, NULL); [...] ```
Quoted 4 lines
passes this second test just fine, while I believe it's supposed to fail.
Am I missing something?
Sorry, I did two things wrong -- I forgot to specify that the second test only fails under ASan, and I simplified the test too much such that it doesn't fail under ASan without the fixes (and simplified in three wrong ways: not enough control characters, wrong kind of control character, attempting to use hex control code to printf instead of octal) and apparently forgot to re-check afterwards. Using the filename
FNAME=$(printf "aaa-\302\237\302\237\302\237-aaa") &&
will trigger the out-of-bounds read under ASan before the fixes; removing the final \302\237 will make it pass with or without the code fixes. I'll correct the patch and send in a new round.
Thanks for checking closely.
PATCH v3 1/1 diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
In reply to Elijah Newren via GitGitGadgetFrom: Elijah Newren <[email protected]>
f85b49f3d4a (diff: improve scaling of filenames in diffstat to handle UTF-8 chars, 2026-01-16) introduced a loop in show_stats() that calls utf8_width() repeatedly to skip leading characters until the displayed width fits. However, utf8_width() can return problematic values:
- For invalid UTF-8 sequences, pick_one_utf8_char() sets the name pointer to NULL and utf8_width() returns 0. Since name_len does not change, the loop iterates once more and pick_one_utf8_char() dereferences the NULL pointer, crashing.
- For control characters, utf8_width() returns -1, so name_len grows when it is expected to shrink. This can cause the loop to consume more characters than the string contains, reading past the trailing NUL.
By default, fill_print_name() will C-quote filenames which escapes control characters and invalid bytes to printable text. That avoids this bug from being triggered; however, with core.quotePath=false, most characters are no longer escaped (though some control characters still are) and raw bytes can reach this code.
Add tests exercising both failure modes with core.quotePath=false and a narrow --stat-name-width to force truncation: one with a bare 0xC0 byte (invalid UTF-8 lead byte, triggers NULL deref) and one with several C1 control characters (repeats of 0xC2 0x9F, causing the loop to read past the end of the string). The second test reliably catches the out-of-bounds read when run under ASan, though it may pass silently without sanitizers.
Fix both issues by introducing utf8_ish_width(), a thin wrapper around utf8_width() that guarantees the pointer always advances and the returned width is never negative:
- On invalid UTF-8 it restores the pointer, advances by one byte, and returns width 1 (matching the strlen()-based fallback used by utf8_strwidth()).
- On a control character it returns 0 (matching utf8_strnwidth() which skips them).
Also add a "&& *name" guard to the while-loop condition so it terminates at end-of-string even when utf8_strwidth()'s strlen() fallback causes name_len to exceed the sum of per-character widths.
---
diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
Changes since v2:
* Fixed the filename in the final test such that it will trigger the out-of-bounds read under ASan, and updated the commit message to point out that ASan is needed to notice the out-of-bounds read.
Changes since v1:
* Simplified the loop to almost what we had before via a wrapper function that always succeeds in advancing the string and never returns a negative width. (Which, as a consequence, treats invalid UTF-8 and control characters the roughly the same, unlike v1.)
Published-As: https://github.com/gitgitgadget/git/releases/tag/pr-2093%2Fnewren%2Ffix%2Fdiffstat-utf8-loop-v3
Fetch-It-Via: git fetch https://github.com/gitgitgadget/git pr-2093/newren/fix/diffstat-utf8-loop-v3
Pull-Request: https://github.com/gitgitgadget/git/pull/2093
Range-diff vs v2:
1: 4a72647ce2 ! 1: 4a3126720b diff: fix out-of-bounds reads and NULL deref in diffstat UTF-8 truncation
@@ Commit message
consume more characters than the string contains, reading past
the trailing NUL.
- By default, fill_print_name() will C-quotes filenames which escapes
+ By default, fill_print_name() will C-quote filenames which escapes
control characters and invalid bytes to printable text. That avoids this bug from being triggered; however, with core.quotePath=false,
- raw bytes can reach this code.
+ most characters are no longer escaped (though some control characters
+ still are) and raw bytes can reach this code.
Add tests exercising both failure modes with core.quotePath=false and a narrow --stat-name-width to force truncation: one with a bare 0xC0
- byte (invalid UTF-8 lead byte, triggers NULL deref) and one with a
- 0x01 byte (control character, causes the loop to read past the end
- of the string).
+ byte (invalid UTF-8 lead byte, triggers NULL deref) and one with
+ several C1 control characters (repeats of 0xC2 0x9F, causing
+ the loop to read past the end of the string). The second test
+ reliably catches the out-of-bounds read when run under ASan, though
+ it may pass silently without sanitizers.
Fix both issues by introducing utf8_ish_width(), a thin wrapper
around utf8_width() that guarantees the pointer always advances and
@@ t/t4052-stat-output.sh: test_expect_success 'diffstat where line_prefix contains
+ test_grep "| 0" output
+'
+
-+test_expect_success FUNNYNAMES 'diffstat truncation with control chars does not crash' '
-+ FNAME=$(printf "aaa-\x01-aaa") &&
++test_expect_success FUNNYNAMES 'diffstat truncation with control chars does not read out of bounds' '
++ FNAME=$(printf "aaa-\302\237\302\237\302\237-aaa") &&
+ git commit --allow-empty -m setup &&
+ >$FNAME &&
+ git add -- $FNAME &&
diff.c | 26 ++++++++++++++++++++++++-- t/t4052-stat-output.sh | 25 +++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-)
diff.c +24 -2
@@ -2927,6 +2927,28 @@ void print_stat_summary(FILE *fp, int files,print_stat_summary_inserts_deletes (&o, files, insertions, deletions); } +/* +* Like utf8_width(), but guaranteed safe for use in loops that subtract +* per-character widths: +* +* - utf8_width() sets *start to NULL on invalid UTF-8 and returns 0; +* we restore the pointer and advance by one byte, returning width 1 +* (matching the strlen()-based fallback in utf8_strwidth()). +* +* - utf8_width() returns -1 for control characters; we return 0 +* (matching utf8_strnwidth() which skips them). +*/ +static int utf8_ish_width (const char **start) +{ +const char *old = *start; +int w =utf8_width (start,NULL ); +if (!*start) { + *start = old +1 ; +return 1 ; + } +return (w <0 ) ?0 : w; +} +static void show_stats (struct diffstat_t *data,struct diff_options *options) {int i, len, add, del, adds =0 , dels =0 ;
@@ -3093,8 +3115,8 @@ static void show_stats(struct diffstat_t *data, struct diff_options *options)if (len <0 ) len =0 ; -while (name_len > len) - name_len -=utf8_width ((const char **)&name,NULL ); +while (name_len > len && *name) + name_len -=utf8_ish_width ((const char **)&name); slash =strchr (name,'/' );if (slash)
t/t4052-stat-output.sh +25 -0
@@ -445,4 +445,29 @@ test_expect_success 'diffstat where line_prefix contains ANSI escape codes is co test_grep "<RED>|<RESET> ${FILENAME_TRIMMED} | 0" out ' +test_expect_success 'diffstat truncation with invalid UTF-8 does not crash' ' + empty_blob=$(git hash-object -w --stdin </dev/null) && + printf "100644 blob $empty_blob\taaa-\300-aaa\n" | + git mktree >tree_file && + tree=$(cat tree_file) && + empty_tree=$(git mktree </dev/null) && + c1=$(git commit-tree -m before $empty_tree) && + c2=$(git commit-tree -m after -p $c1 $tree) && + git -c core.quotepath=false diff --stat --stat-name-width=5 $c1..$c2 >output && + test_grep "| 0" output +' + +test_expect_success FUNNYNAMES 'diffstat truncation with control chars does not read out of bounds' ' + FNAME=$(printf "aaa-\302\237\302\237\302\237-aaa") && + git commit --allow-empty -m setup && + >$FNAME && + git add -- $FNAME && + git commit -m "add file with control char name" && + git -c core.quotepath=false diff --stat --stat-name-width=5 HEAD~1..HEAD >output && + test_grep "| 0" output && + rm -- $FNAME && + git rm -- $FNAME && + git commit -m "remove test file" +' + test_done
base-commit: 9f223ef1c026d91c7ac68cc0211bde255dda6199
Signature · 1 line
gitgitgadget
Quoted 41 lines · Elijah Newren via GitGitGadget
From: Elijah Newren <[email protected]>
f85b49f3d4a(diff: improve scaling of filenames in diffstat to handle UTF-8 chars, 2026-01-16) introduced a loop inshow_stats()that callsutf8_width()repeatedly to skip leading characters until the displayed width fits. However,utf8_width()can return problematic values:- For invalid UTF-8 sequences,
pick_one_utf8_char()sets the name pointer to NULL andutf8_width()returns 0. Sincename_lendoes not change, the loop iterates once more andpick_one_utf8_char()dereferences the NULL pointer, crashing.- For control characters,
utf8_width()returns -1, soname_lengrows when it is expected to shrink. This can cause the loop to consume more characters than the string contains, reading past the trailing NUL.By default,
fill_print_name()will C-quote filenames which escapes control characters and invalid bytes to printable text. That avoids this bug from being triggered; however, with core.quotePath=false, most characters are no longer escaped (though some control characters still are) and raw bytes can reach this code.Add tests exercising both failure modes with core.quotePath=false and a narrow --stat-name-width to force truncation: one with a bare
0xC0byte (invalid UTF-8 lead byte, triggers NULL deref) and one with several C1 control characters (repeats of0xC20x9F, causing the loop to read past the end of the string). The second test reliably catches the out-of-bounds read when run under ASan, though it may pass silently without sanitizers.Fix both issues by introducing
utf8_ish_width(), a thin wrapper aroundutf8_width()that guarantees the pointer always advances and the returned width is never negative:- On invalid UTF-8 it restores the pointer, advances by one byte, and returns width 1 (matching the strlen()-based fallback used by
utf8_strwidth()).
- On a control character it returns 0 (matchingutf8_strnwidth()which skips them).
Quoted 3 lines
Also add a "&& *name" guard to the while-loop condition so it terminates at end-of-string even when utf8_strwidth()'s
strlen()fallback causesname_lento exceed the sum of per-character widths.
OK, that does sounds sensible.
If we start from a valid UTF-8 string, chomp a few bytes from the tail end of it, and feed it into this loop, the initial part of the last character is fed to utf8_width(), which hopefully is already prepared to honor the NUL termination to avoid an OOB read while returning an error. And eventually we would see that NUL that truncated the last UTF-8 multi-byte letter ourselves in the loop and that is where this new loop terminating condition would help.