Skip to content

Commit 17d23e8

Browse files
pks-tgitster
authored andcommitted
utf8: fix returning negative string width
The `utf8_strnwidth()` function calls `utf8_width()` in a loop and adds its returned width to the end result. `utf8_width()` can return `-1` though in case it reads a control character, which means that the computed string width is going to be wrong. In the worst case where there are more control characters than non-control characters, we may even return a negative string width. Fix this bug by treating control characters as having zero width. Signed-off-by: Patrick Steinhardt <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 522cc87 commit 17d23e8

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

t/t4205-log-pretty-formats.sh

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -899,6 +899,12 @@ test_expect_success SIZE_T_IS_64BIT 'log --pretty with overflowing wrapping dire
899899
test_cmp expect error
900900
'
901901

902+
test_expect_success 'log --pretty with padding and preceding control chars' '
903+
printf "\20\20 0" >expect &&
904+
git log -1 --pretty="format:%x10%x10%>|(4)%x30" >actual &&
905+
test_cmp expect actual
906+
'
907+
902908
test_expect_success EXPENSIVE,SIZE_T_IS_64BIT 'log --pretty with huge commit message' '
903909
# We only assert that this command does not crash. This needs to be
904910
# executed with the address sanitizer to demonstrate failure.

utf8.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,11 +212,15 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
212212
const char *orig = string;
213213

214214
while (string && string < orig + len) {
215-
int skip;
215+
int glyph_width, skip;
216+
216217
while (skip_ansi &&
217218
(skip = display_mode_esc_sequence_len(string)) != 0)
218219
string += skip;
219-
width += utf8_width(&string, NULL);
220+
221+
glyph_width = utf8_width(&string, NULL);
222+
if (glyph_width > 0)
223+
width += glyph_width;
220224
}
221225
return string ? width : len;
222226
}

0 commit comments

Comments
 (0)