utf8: two minor fixes
Subsystems (2)
cover utf8: two minor fixes
A patch here on the list made me look at display_mode_esc_sequence_len() in utf8.c and I found two details in the file that are perhaps worth a fix:
1) utf8_strnwidth() disregards the given len argument when fed with proper string and len.
2) The comment for utf8_strnwidth() is incorrect: it states the function returns strlen() for cases when it actually returns its len argument.
---
Dirk Gouders (2):
utf8: respect bounds in utf8_strnwidth()
utf8: fix comment for utf8_strnwidth()
t/unit-tests/u-utf8-width.c | 11 +++++++++++ utf8.c | 12 ++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-)
---
base-commit: 7fb6055e678f800320d8ab8cd8f201d9493d1ba0
change-id: 20261116-master-69b171612823
PATCH 1/2 utf8: respect bounds in utf8_strnwidth()
utf8_strnwidth() takes a len argument, but because display_mode_esc_sequence_len() works without an explicit boundary, there are cases when utf8_strnwidth() operates beyond the given len boundary.
Fix this by adding a boundary-check after looping with display_mode_esc_sequence_len() to ensure we operate strictly within the given len.
Further, add three corner case tests of which two will fail without the fix:
------------------------------------------------------------------------
not ok 257 - utf8_width::strnwidth_ansi
---
reason: |
Expected comparison to hold: 0 == utf8_strnwidth("\033[31mhello", 4, 1)
0 != 1
at:
file: 't/unit-tests/u-utf8-width.c'
line: 11
function: 'test_utf8_width__strnwidth_ansi'
...------------------------------------------------------------------------
With the fix:
------------------------------------------------------------------------
ok 257 - utf8_width::strnwidth_ansi
------------------------------------------------------------------------
--- t/unit-tests/u-utf8-width.c | 11 +++++++++++ utf8.c | 10 +++++++--- 2 files changed, 18 insertions(+), 3 deletions(-)
t/unit-tests/u-utf8-width.c +11 -0
@@ -2,6 +2,17 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for strings with SGR sequences and corner case length +* arguments. +*/ +void test_utf8_width__strnwidth_ansi (void ) +{ +cl_assert_equal_i (0 ,utf8_strnwidth ("\033[31mhello" ,4 ,1 )); +cl_assert_equal_i (0 ,utf8_strnwidth ("\033[31mhello" ,5 ,1 )); +cl_assert_equal_i (1 ,utf8_strnwidth ("\033[31mhello" ,6 ,1 )); +} +/* * Test utf8_strnwidth with various Chinese strings * Chinese characters typically have a width of 2 columns when displayed
utf8.c +7 -3
@@ -217,9 +217,13 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)int glyph_width;size_t skip; -while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) - string += skip; +if (skip_ansi) { +while ((skip =display_mode_esc_sequence_len (string)) !=0 ) + string += skip; + +if (string >= orig + len) +break ; + } glyph_width =utf8_width (&string,NULL );if (glyph_width >0 )
Signature · 1 line
2.55.0
Re: [PATCH 1/2] utf8: respect bounds in utf8_strnwidth()
Quoted 4 lines · Dirk Gouders
utf8_strnwidth()takes a len argument, but becausedisplay_mode_esc_sequence_len()works without an explicit boundary, there are cases whenutf8_strnwidth()operates beyond the given len boundary.
The problem is well spotted, but isn't the blame slightly misplaced? The preimage with missing context looks like this:
int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
{
const char *orig = string;
size_t width = 0;
while (string && string < orig + len) {
int glyph_width;
size_t skip;
while (skip_ansi &&
(skip = display_mode_esc_sequence_len(string)) != 0)
string += skip;
glyph_width = utf8_width(&string, NULL);
if (glyph_width > 0)
width += glyph_width;
}Even if display_mode_esc_sequence_len() were updated to take the remaining number of bytes in string (which I think *is* a good change, by the way), the loop it is in may cause the entirety of the string up to the "len" bytes to be skipped. Because the original lacks a guard before the call to utf8_width(), however, we end up calling it even if string points beyond the given region of bytes orig[0,len).
If you blame the lack of such a guard before utf8_width() (or after the loop that has display_mode_esc_sequence_len()), it would match the proposed fix. But I doubt it is entirely fair to blame the lack of an explicit boundary in display_mode_esc_sequence_len() for the breakage you are addressing.
Quoted 3 lines
Fix this by adding a boundary-check after looping with
display_mode_esc_sequence_len()to ensure we operate strictly within the given len.
If the incoming "string" is at the end of an mmapped region (beyond the end of which nothing is mapped), reading string[len] would give you SIGBUS, so display_mode_esc_sequence_len() would already have taken you into trouble. In other words, even though such a check before utf8_width() is better than nothing, in a sense it is too late, no?
Quoted 21 lines
utf8.c +7
-3@@ -217,9 +217,13 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)int glyph_width;size_t skip; -while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) - string += skip; +if (skip_ansi) { +while ((skip =display_mode_esc_sequence_len (string)) !=0 ) + string += skip; + +if (string >= orig + len) +break ; + } glyph_width =utf8_width (&string,NULL );if (glyph_width >0 )
Re: [PATCH 1/2] utf8: respect bounds in utf8_strnwidth()
Quoted 36 lines · Junio C Hamano
Quoted 4 lines · Dirk Gouders
utf8_strnwidth()takes a len argument, but becausedisplay_mode_esc_sequence_len()works without an explicit boundary, there are cases whenutf8_strnwidth()operates beyond the given len boundary.The problem is well spotted, but isn't the blame slightly misplaced? The preimage with missing context looks like this:
int utf8_strnwidth(const char *string, size_t len, int skip_ansi) { const char *orig = string; size_t width = 0; while (string && string < orig + len) { int glyph_width; size_t skip; while (skip_ansi && (skip = display_mode_esc_sequence_len(string)) != 0) string += skip; glyph_width = utf8_width(&string, NULL); if (glyph_width > 0) width += glyph_width; }Even if
display_mode_esc_sequence_len()were updated to take the remaining number of bytes in string (which I think *is* a good change, by the way), the loop it is in may cause the entirety of the string up to the "len" bytes to be skipped. Because the original lacks a guard before the call toutf8_width(), however, we end up calling it even if string points beyond the given region of bytes orig[0,len).
Quoted 5 lines
If you blame the lack of such a guard before
utf8_width()(or after the loop that hasdisplay_mode_esc_sequence_len()), it would match the proposed fix. But I doubt it is entirely fair to blame the lack of an explicit boundary indisplay_mode_esc_sequence_len()for the breakage you are addressing.
Yes, I'm not sure if that term is correct but the main problem seems to be a "contract mismatch": a function that accepts a boundary argument calls one function display_mode_esc_sequence_len() that doesn't have an explicit boundary and for a second one utf8_width() it doesn't use the optional boundary argument.
Quoted 10 lines
Quoted 3 lines
Fix this by adding a boundary-check after looping with
display_mode_esc_sequence_len()to ensure we operate strictly within the given len.If the incoming "string" is at the end of an mmapped region (beyond the end of which nothing is mapped), reading string[len] would give you SIGBUS, so
display_mode_esc_sequence_len()would already have taken you into trouble. In other words, even though such a check beforeutf8_width()is better than nothing, in a sense it is too late, no?
Correct.
I am currently preparing a v2 that adresses all the above.
I will try to give that v2 sufficient time to hopefully reduce errors in my workflow and not steal other people's time.
Regards,
Dirk
Quoted 21 lines
Quoted 21 lines
utf8.c +7
-3@@ -217,9 +217,13 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)int glyph_width;size_t skip; -while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) - string += skip; +if (skip_ansi) { +while ((skip =display_mode_esc_sequence_len (string)) !=0 ) + string += skip; + +if (string >= orig + len) +break ; + } glyph_width =utf8_width (&string,NULL );if (glyph_width >0 )
Re: [PATCH 1/2] utf8: respect bounds in utf8_strnwidth()
In reply to Junio C HamanoQuoted 5 lines · Junio C Hamano
The problem is well spotted, but isn't the blame slightly misplaced?
...
Even ifdisplay_mode_esc_sequence_len()were updated to take the remaining number of bytes in string (which I think *is* a good change, by the way), ...
An update to display_mode_esc_sequence_len() to take the length limit, including its fallout, is shown below, and it does not look too bad. Not even compile-tested, but it should be sufficient as an illustration of the idea.
This does not make your "after display_mode_esc_sequence_len() skips, make sure if we still have remaining string to grab one UTF-8 character" change unnecessary, as I said.
pretty.c | 3 ++- utf8.c | 27 ++++++++++++++++++--------- utf8.h | 2 +- 3 files changed, 21 insertions(+), 11 deletions(-)
pretty.c +2 -1
@@ -1834,7 +1834,8 @@ static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */while (p > sb->buf && ch - p <10 && *p !='\033' ) p--;if (*p !='\033' || - ch +1 - p !=display_mode_esc_sequence_len (p)) + ch +1 - p !=display_mode_esc_sequence_len (p, + ch +1 - p))break ;/* * got a good ansi sequence, put it back to
utf8.c +18 -9
@@ -16,16 +16,23 @@ struct interval {ucs_char_t last; }; -size_t display_mode_esc_sequence_len (const char *s) +/* +* Return the length of the ANSI display mode escape sequence (e.g., +* "\033[1;31m") that appears at the beginning of the "len" bytes +* of string "s", or 0 if the bytes do not begin with a complete +* such sequence. Never looks at s[len] or beyond. +*/ +size_t display_mode_esc_sequence_len (const char *s,size_t len) { -const char *p = s; -if (*p++ !='\033' ) +const char *p = s, *end = s + len; + +if (end <= p || *p++ !='\033' )return 0 ; -if (*p++ !='[' ) +if (end <= p || *p++ !='[' )return 0 ; -while (isdigit (*p) || *p ==';' ) +while (p < end && (isdigit (*p) || *p ==';' )) p++; -if (*p++ !='m' ) +if (end <= p || *p++ !='m' )return 0 ;return p - s; }
@@ -218,7 +225,8 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)size_t skip;while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) + (skip =display_mode_esc_sequence_len (string, + orig + len - string)) !=0 ) string += skip; glyph_width =utf8_width (&string,NULL );
@@ -279,6 +287,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf, {int indent, w, assume_utf8 =1 ;const char *bol, *space, *start = text; +const char *end = text +strlen (text);size_t orig_len = buf->len;if (width <=0 ) {
@@ -299,7 +308,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf,char c;size_t skip; -while ((skip =display_mode_esc_sequence_len (text))) +while ((skip =display_mode_esc_sequence_len (text, end - text))) text += skip; c = *text;
@@ -378,7 +387,7 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,int glyph_width;size_t n; -while ((n =display_mode_esc_sequence_len (src))) { +while ((n =display_mode_esc_sequence_len (src, end - src))) {strbuf_add (&dst, src, n); src += n; }
utf8.h +1 -1
@@ -5,7 +5,7 @@ struct strbuf;typedef unsigned int ucs_char_t ;/* assuming 32bit int */ -size_t display_mode_esc_sequence_len (const char *s); +size_t display_mode_esc_sequence_len (const char *s,size_t len);int utf8_width (const char **start,size_t *remainder_p);int utf8_strnwidth (const char *string,size_t len,int skip_ansi);int utf8_strwidth (const char *string);
Re: [PATCH 1/2] utf8: respect bounds in utf8_strnwidth()
Quoted 8 lines · Junio C Hamano
Quoted 5 lines · Junio C Hamano
The problem is well spotted, but isn't the blame slightly misplaced?
...
Even ifdisplay_mode_esc_sequence_len()were updated to take the remaining number of bytes in string (which I think *is* a good change, by the way), ...
Quoted 8 lines
An update to
display_mode_esc_sequence_len()to take the length limit, including its fallout, is shown below, and it does not look too bad. Not even compile-tested, but it should be sufficient as an illustration of the idea.This does not make your "after
display_mode_esc_sequence_len()skips, make sure if we still have remaining string to grab one UTF-8 character" change unnecessary, as I said.
My v2 would have introduced two new functions (see attached) to replace display_mode_esc_sequence_len():
• size_t ansi_sgr_nlen(const char *str, size_t len);
• size_t ansi_sgr_nlen_multi(const char *s, size_t len);
The latter one to help (most of all) users who want to eat *all* leading SGR sequences so that they don't need loops.
But I saw you already posted a patch and that is also fine, of course.
Dirk
utf8.c +38 -0
@@ -30,6 +30,44 @@ size_t display_mode_esc_sequence_len(const char *s)return p - s; } +size_t ansi_sgr_nlen (const char *str,size_t len) +{ +const char *p = str; +const char *p_max = str + len; + +if (len <3 ) +return 0 ; + +if (*p++ !='\033' ) +return 0 ; +if (*p++ !='[' ) +return 0 ; + +while (p < p_max && (isdigit (*p) || *p ==';' )) + p++; + +if (p == p_max || *p !='m' ) +return 0 ; + +return p - str; +} + +size_t ansi_sgr_nlen_multi (const char *s,size_t len) +{ +size_t sgr_len =0 ; + +while (sgr_len < len) { +size_t count =ansi_sgr_nlen (s + sgr_len, len - sgr_len); + +if (!count) +break ; + + sgr_len += count; + } + +return sgr_len; +} +/* auxiliary function for binary search in interval table */ static int bisearch (ucs_char_t ucs,const struct interval *table,int max) {
Re: [PATCH 1/2] utf8: respect bounds in utf8_strnwidth()
Quoted 11 lines · Dirk Gouders
Quoted 8 lines
An update to
display_mode_esc_sequence_len()to take the length limit, including its fallout, is shown below, and it does not look too bad. Not even compile-tested, but it should be sufficient as an illustration of the idea.This does not make your "after
display_mode_esc_sequence_len()skips, make sure if we still have remaining string to grab one UTF-8 character" change unnecessary, as I said.My v2 would have introduced two new functions (see attached) to replace
display_mode_esc_sequence_len():
A two-function arrangement would be a good idea for maintainability.
Add display_mode_esc_sequence_len_counted() to use the counted string API, with display_mode_esc_sequence_len() keeping the original calling convention (i.e., we call strlen(s) then call the new helper). I was too lazy to do the function pair in the illustration patch, which caused all existing callers to be affected, but given that there is another topic or two that are just being proposed that would add more callers to this function, it probably makes sense to keep a function with the NUL-terminated string API as before, and add the counted interface for callers that care, like the one you are fixing.
Thanks.
PATCH 2/2 utf8: fix comment for utf8_strnwidth()
In reply to Dirk GoudersThe comment for utf8_strnwidth() states it returns strlen() for cases when the given string doesn't look like valid utf8, but it returns its argument len in such cases.
Fix the comment accordingly.
--- utf8.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
utf8.c +1 -1
@@ -205,7 +205,7 @@ int utf8_width(const char **start, size_t *remainder_p)/* * Returns the total number of columns required by a null-terminated -* string, assuming that the string is utf8. Returns strlen() instead +* string, assuming that the string is utf8. Returns len instead * if the string does not look like a valid utf8 string. */ int utf8_strnwidth (const char *string,size_t len,int skip_ansi)
Signature · 1 line
2.55.0
v2 cover utf8: bounds-related fixes and a doc fix
In reply to Dirk GoudersA patch here on the list made me look at display_mode_esc_sequence_len() in utf8.c and I found two details in the file that are perhaps worth a fix:
1) utf8_strnwidth() disregards the given len argument when fed with proper string and len.
2) The comment for utf8_strnwidth() is incorrect: it states the function returns strlen() for cases when it actually returns its len argument.
---
Changes in v2:
- Add a patch by Junio that introduces a bounded function display_mode_esc_sequence_len_counted() I added some tests for this new function.
- 2/2 became 2/4
- 3/4 is the modified 1/2 and uses the new display_mode_esc_sequence_len_counted() so that the while loop stays
within the given bounds.
The commit message was adjusted.
One of the tests was wrong: "\033" has width 0, so the sum must be 3 instead of 4.
- 4/4 is an addition to fix a similar problem with utf8_width().
That function is used without its optional bounds argument and
can violate boundaries as well. Test for such cases are added.
- Link to v1: https://patch.msgid.link/[email protected]
---
Dirk Gouders (3):
utf8: fix comment for utf8_strnwidth()
utf8: respect string boundaries after skipping ANSI escape sequences
utf8: respect boundaries in utf8_strnwidth()
Junio C Hamano (1):
utf8: add display_mode_esc_sequence_len_counted()
Makefile | 1 + t/meson.build | 1 + t/unit-tests/u-utf8-ansi.c | 14 +++++++++++++ t/unit-tests/u-utf8-width.c | 20 ++++++++++++++++++ utf8.c | 50 +++++++++++++++++++++++++++++++++------------ utf8.h | 1 + 6 files changed, 74 insertions(+), 13 deletions(-)
Range-diff versus v1:
-: ---------- > 1: 3b2ab53858 utf8: add display_mode_esc_sequence_len_counted() 2: aab04775f6 = 2: efeff5cfd7 utf8: fix comment for utf8_strnwidth() 1: 21baf82731 ! 3: 152210dd15 utf8: respect bounds in utf8_strnwidth()
@@ Metadata
Author: Dirk Gouders <[email protected]>
## Commit message ##
- utf8: respect bounds in utf8_strnwidth()
+ utf8: respect string boundaries after skipping ANSI escape sequences
- utf8_strnwidth() takes a len argument, but because
- display_mode_esc_sequence_len() works without an explicit boundary,
- there are cases when utf8_strnwidth() operates beyond the given len
- boundary.
+ utf8_strnwidth() can skip ANSI escape sequences and it is possible
+ that such sequences end the string within the given boundary.
- Fix this by adding a boundary-check after looping with
- display_mode_esc_sequence_len() to ensure we operate strictly within
- the given len.
+ Check for such situations before proceeding and calling utf8_width().
- Further, add three corner case tests of which two will fail without
- the fix:
- ------------------------------------------------------------------------
- not ok 257 - utf8_width::strnwidth_ansi
- ---
- reason: |
- Expected comparison to hold: 0 == utf8_strnwidth("\033[31mhello", 4, 1)
- 0 != 1
- at:
- file: 't/unit-tests/u-utf8-width.c'
- line: 11
- function: 'test_utf8_width__strnwidth_ansi'
- ...
- ------------------------------------------------------------------------
-
- With the fix:
- ------------------------------------------------------------------------
- ok 257 - utf8_width::strnwidth_ansi
- ------------------------------------------------------------------------
+ Add tests that test such corner cases.
@@ t/unit-tests/u-utf8-width.c
+ */
+void test_utf8_width__strnwidth_ansi(void)
+{
-+ cl_assert_equal_i(0, utf8_strnwidth("\033[31mhello", 4, 1));
++ cl_assert_equal_i(3, utf8_strnwidth("\033[31mhello", 4, 1));
+ cl_assert_equal_i(0, utf8_strnwidth("\033[31mhello", 5, 1));
+ cl_assert_equal_i(1, utf8_strnwidth("\033[31mhello", 6, 1));
+}
@@ utf8.c: int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
size_t skip;
- while (skip_ansi &&
-- (skip = display_mode_esc_sequence_len(string)) != 0)
+- (skip = display_mode_esc_sequence_len_counted(string,
+- orig + len - string)) != 0)
- string += skip;
-+ if (skip_ansi) {
-+ while ((skip = display_mode_esc_sequence_len(string)) != 0)
++ if (skip_ansi ) {
++ while ((skip = display_mode_esc_sequence_len_counted(string,
++ orig + len - string)) != 0)
+ string += skip;
+
+ if (string >= orig + len)
-: ---------- > 4: 044d188fa8 utf8: respect boundaries in utf8_strnwidth()
---
base-commit: 7fb6055e678f800320d8ab8cd8f201d9493d1ba0
change-id: 20261116-master-69b171612823
PATCH v2 1/4 utf8: add display_mode_esc_sequence_len_counted()
From: Junio C Hamano <[email protected]>
display_mode_esc_sequence_len() scans for an ANSI display mode escape sequence (e.g. "ESC [ 1 ; 31 m") at the start of a string, relying on NUL termination to stop. Some callers, however, work on a counted buffer: utf8_strnwidth() takes <string, len> and must not scan past it, while strbuf_utf8_replace() and strbuf_add_wrapped_text() know (or can cheaply learn) the end.
Add display_mode_esc_sequence_len_counted() taking <ptr, len>, which never reads at or beyond ptr[len], and make display_mode_esc_sequence_len() a thin wrapper for NUL-terminated strings.
Use the counted variant in utf8_strnwidth() for correctness, and in strbuf_utf8_replace() and strbuf_add_wrapped_text() (computing the end once upfront in the latter) to avoid measuring the remaining text in each iteration.
Also, add some tests for the new function.
--- Makefile | 1 + t/meson.build | 1 + t/unit-tests/u-utf8-ansi.c | 14 ++++++++++++++ utf8.c | 35 ++++++++++++++++++++++++++--------- utf8.h | 1 + 5 files changed, 43 insertions(+), 9 deletions(-)
Makefile +1 -0
@@ -1564,6 +1564,7 @@ CLAR_TEST_SUITES += u-strvec CLAR_TEST_SUITES += u-trailer CLAR_TEST_SUITES += u-urlmatch-normalization CLAR_TEST_SUITES += u-utf8-width +CLAR_TEST_SUITES += u-utf8-ansi CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X) CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES)) CLAR_TEST_OBJS += $(UNIT_TEST_DIR)/clar/clar.o
t/meson.build +1 -0
@@ -27,6 +27,7 @@ clar_test_suites = [ 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', 'unit-tests/u-utf8-width.c', + 'unit-tests/u-utf8-ansi.c', ] clar_sources = [
t/unit-tests/u-utf8-ansi.c new file +14 -0
@@ -0,0 +1,14 @@ +#include "unit-test.h" +#include "utf8.h" +#include "strbuf.h" + +/* +* Test len limited functions for ANSI SGR lengths. +*/ +void test_utf8_ansi__sgr_len (void ) +{ +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_counted ("\033[m" ,2 )); +cl_assert_equal_i (3 ,display_mode_esc_sequence_len_counted ("\033[m" ,3 )); +cl_assert_equal_i (5 ,display_mode_esc_sequence_len_counted ("\033[31m" ,5 )); +cl_assert_equal_i (7 ,display_mode_esc_sequence_len_counted ("\033[0;31m" ,7 )); +}
utf8.c +26 -9
@@ -16,20 +16,33 @@ struct interval {ucs_char_t last; }; -size_t display_mode_esc_sequence_len (const char *s) +/* +* Return the length of the ANSI display mode escape sequence (e.g., +* "\033[1;31m") that appears at the beginning of the "len" bytes +* of string "s", or 0 if the bytes do not begin with a complete +* such sequence. Never looks at s[len] or beyond. +*/ +size_t display_mode_esc_sequence_len_counted (const char *s,size_t len) { -const char *p = s; -if (*p++ !='\033' ) +const char *p = s, *end = s + len; + +if (end <= p || *p++ !='\033' )return 0 ; -if (*p++ !='[' ) +if (end <= p || *p++ !='[' )return 0 ; -while (isdigit (*p) || *p ==';' ) +while (p < end && (isdigit (*p) || *p ==';' )) p++; -if (*p++ !='m' ) +if (end <= p || *p++ !='m' )return 0 ;return p - s; } +/* Same as above, but for a NUL-terminated string "s". */ +size_t display_mode_esc_sequence_len (const char *s) +{ +return display_mode_esc_sequence_len_counted (s,strlen (s)); +} +/* auxiliary function for binary search in interval table */ static int bisearch (ucs_char_t ucs,const struct interval *table,int max) {
@@ -218,7 +231,8 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)size_t skip;while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) + (skip =display_mode_esc_sequence_len_counted (string, + orig + len - string)) !=0 ) string += skip; glyph_width =utf8_width (&string,NULL );
@@ -279,6 +293,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf, {int indent, w, assume_utf8 =1 ;const char *bol, *space, *start = text; +const char *end = text +strlen (text);size_t orig_len = buf->len;if (width <=0 ) {
@@ -299,7 +314,8 @@ void strbuf_add_wrapped_text(struct strbuf *buf,char c;size_t skip; -while ((skip =display_mode_esc_sequence_len (text))) +while ((skip =display_mode_esc_sequence_len_counted (text, + end - text))) text += skip; c = *text;
@@ -378,7 +394,8 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,int glyph_width;size_t n; -while ((n =display_mode_esc_sequence_len (src))) { +while ((n =display_mode_esc_sequence_len_counted (src, + end - src))) {strbuf_add (&dst, src, n); src += n; }
utf8.h +1 -0
@@ -6,6 +6,7 @@ struct strbuf;typedef unsigned int ucs_char_t ;/* assuming 32bit int */ size_t display_mode_esc_sequence_len (const char *s); +size_t display_mode_esc_sequence_len_counted (const char *s,size_t len);int utf8_width (const char **start,size_t *remainder_p);int utf8_strnwidth (const char *string,size_t len,int skip_ansi);int utf8_strwidth (const char *string);
Signature · 1 line
2.55.0
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
utf8.c struct interval { · line 44
Quoted 5 lines · Dirk Gouders
utf8.c +5
-0+/* Same as above, but for a NUL-terminated string "s". */ +size_t display_mode_esc_sequence_len (const char *s) +{ +return display_mode_esc_sequence_len_counted (s,strlen (s)); +}
This is a performance regression compared to the original function. Calls that previously returned immediately because *s != '\033', or after a few bytes of scanning, now scan the entire string with strlen. It turns scanning a whole string for SGRs with repeated calls to the function from linear to quadratic.
Therefore I think that if the original implementation isn't going to be kept, it would be better not to provide the wrapper, and thereby make callers think about what they want to pass as the length.
Uses on strbufs can of course compute it with sb.buf + sb.len - s, but they don't actually need this safety net, because strbufs are guaranteed to be NUL-terminated and the function stops at NULs. And the length calculation itself adds a source of errors.
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 13 lines · Andy Koppe
utf8.c struct interval { · line 44
Quoted 5 lines · Dirk Gouders
utf8.c +5
-0+/* Same as above, but for a NUL-terminated string "s". */ +size_t display_mode_esc_sequence_len (const char *s) +{ +return display_mode_esc_sequence_len_counted (s,strlen (s)); +}This is a performance regression compared to the original function. Calls that previously returned immediately because *s != '\033', or after a few bytes of scanning, now scan the entire string with strlen. It turns scanning a whole string for SGRs with repeated calls to the function from linear to quadratic.
Quoted 8 lines
Therefore I think that if the original implementation isn't going to be kept, it would be better not to provide the wrapper, and thereby make callers think about what they want to pass as the length.
Uses on strbufs can of course compute it with
sb.buf + sb.len - s, but they don't actually need this safety net, because strbufs are guaranteed to be NUL-terminated and the function stops at NULs. And the length calculation itself adds a source of errors.
There is only one user in pretty.c that uses the wrapper.
I can change it to use the _counted version and we could then drop the wrapper. Junio's v1 already included such a change and I could steal it from there.
Would that be OK?
Dirk
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 25 lines · Dirk Gouders
Quoted 13 lines · Andy Koppe
utf8.c struct interval { · line 44
Quoted 5 lines · Dirk Gouders
utf8.c +5
-0+/* Same as above, but for a NUL-terminated string "s". */ +size_t display_mode_esc_sequence_len (const char *s) +{ +return display_mode_esc_sequence_len_counted (s,strlen (s)); +}This is a performance regression compared to the original function. Calls that previously returned immediately because *s != '\033', or after a few bytes of scanning, now scan the entire string with strlen. It turns scanning a whole string for SGRs with repeated calls to the function from linear to quadratic.
Quoted 8 lines
Therefore I think that if the original implementation isn't going to be kept, it would be better not to provide the wrapper, and thereby make callers think about what they want to pass as the length.
Uses on strbufs can of course compute it with
sb.buf + sb.len - s, but they don't actually need this safety net, because strbufs are guaranteed to be NUL-terminated and the function stops at NULs. And the length calculation itself adds a source of errors.
Quoted 6 lines
There is only one user in
pretty.cthat uses the wrapper.
I can change it to use the_countedversion and we could then drop the wrapper. Junio's v1 already included such a change and I could steal it from there.Would that be OK?
No objection from me. I would change the make_line_colors_self_contained() function I'm proposing in [1] to the _counted variant anyway if the original display_mode_esc_sequence_len() is going away, to avoid the performance issue with the wrapper.
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 6 lines · Andy Koppe
Quoted 5 lines · Dirk Gouders
There is only one user in
pretty.cthat uses the wrapper.
I can change it to use the_countedversion and we could then drop the wrapper. Junio's v1 already included such a change and I could steal it from there.
Quoted 8 lines
Quoted 1 line
Would that be OK?
No objection from me. I would change the
make_line_colors_self_contained()function I'm proposing in [1] to the_countedvariant anyway if the originaldisplay_mode_esc_sequence_len()is going away, to avoid the performance issue with the wrapper.
ps: I guess you might as well just drop the _counted suffix then, and basically just add the len parameter to display_mode_esc_sequence_len().
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 14 lines · Andy Koppe
Quoted 13 lines · Andy Koppe
Quoted 6 lines · Dirk Gouders
There is only one user in
pretty.cthat uses the wrapper.
I can change it to use the_countedversion and we could then drop the wrapper. Junio's v1 already included such a change and I could steal it from there.Would that be OK?
No objection from me. I would change the
make_line_colors_self_contained()function I'm proposing in [1] to the_countedvariant anyway if the originaldisplay_mode_esc_sequence_len()is going away, to avoid the performance issue with the wrapper.
Quoted 4 lines
Quoted 1 line
ps: I guess you might as well just drop the
_countedsuffix then, and basically just add the len parameter todisplay_mode_esc_sequence_len().
That was the plan. I just checked v1 and all this would actually mean to use Junio's v1 instead of v2.
Dirk
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
In reply to Andy KoppeQuoted 12 lines · Andy Koppe
utf8.c struct interval { · line 44
Quoted 5 lines · Dirk Gouders
utf8.c +5
-0+/* Same as above, but for a NUL-terminated string "s". */ +size_t display_mode_esc_sequence_len (const char *s) +{ +return display_mode_esc_sequence_len_counted (s,strlen (s)); +}This is a performance regression compared to the original function. Calls that previously returned immediately because *s != '\033', or after a few bytes of scanning, now scan the entire string with strlen. It turns scanning a whole string for SGRs with repeated calls to the function from linear to quadratic.
How about creating a v3 for display_mode_esc_sequence_len() similar to utf8_width() to accept an optional remainder argument?
If NULL is given, display_mode_esc_sequence_len() assumes a null-terminated string, otherwise the length is given in *remainder. The function can then update the remainder and return the length.
Just an idea.
Dirk
Quoted 8 lines
Therefore I think that if the original implementation isn't going to be kept, it would be better not to provide the wrapper, and thereby make callers think about what they want to pass as the length.
Uses on strbufs can of course compute it with
sb.buf + sb.len - s, but they don't actually need this safety net, because strbufs are guaranteed to be NUL-terminated and the function stops at NULs. And the length calculation itself adds a source of errors.
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 15 lines · Dirk Gouders
Quoted 12 lines · Andy Koppe
Review
Quoted 5 lines · Dirk Gouders
(quoted diff) +5
-0+/* Same as above, but for a NUL-terminated string "s". */ +size_t display_mode_esc_sequence_len(const char *s) +{ + return display_mode_esc_sequence_len_counted(s, strlen(s)); +}This is a performance regression compared to the original function. Calls that previously returned immediately because *s != '\033', or after a few bytes of scanning, now scan the entire string with strlen. It turns scanning a whole string for SGRs with repeated calls to the function from linear to quadratic.
Quoted 8 lines
How about creating a v3 for
display_mode_esc_sequence_len()similar toutf8_width()to accept an optional remainder argument?If NULL is given,
display_mode_esc_sequence_len()assumes a null-terminated string, otherwise the length is given in *remainder. The function can then update the remainder and return the length.Just an idea.
Something like this untested example (please ignore the _counted):
utf8.c +12 -6
@@ -22,18 +22,24 @@ struct interval {* of string "s", or 0 if the bytes do not begin with a complete * such sequence. Never looks at s[len] or beyond. */ -size_t display_mode_esc_sequence_len_counted (const char *s,size_t len) +size_t display_mode_esc_sequence_len_counted (const char *s,size_t *len) { -const char *p = s, *end = s + len; +const char *p = s, *end =NULL ; -if (end <= p || *p++ !='\033' ) +if (len) + end = s + *len; + +if ((end && end <= p) || *p++ !='\033' )return 0 ; -if (end <= p || *p++ !='[' ) +if ((end && end <= p) || *p++ !='[' )return 0 ; -while (p < end && (isdigit (*p) || *p ==';' )) +while (((end && p < end) || (!end && *p)) && (isdigit (*p) || *p ==';' )) p++; -if (end <= p || *p++ !='m' ) +if ((end && end <= p) || (!end && !*p) || *p++ !='m' )return 0 ; + +if (len) + *len -= p - s;return p - s; }
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
In reply to Dirk GoudersQuoted 16 lines · Dirk Gouders
Quoted 12 lines · Andy Koppe
utf8.c struct interval { · line 44
Quoted 5 lines · Dirk Gouders
utf8.c +5
-0+/* Same as above, but for a NUL-terminated string "s". */ +size_t display_mode_esc_sequence_len (const char *s) +{ +return display_mode_esc_sequence_len_counted (s,strlen (s)); +}This is a performance regression compared to the original function. Calls that previously returned immediately because *s != '\033', or after a few bytes of scanning, now scan the entire string with strlen. It turns scanning a whole string for SGRs with repeated calls to the function from linear to quadratic.
Quoted 6 lines
How about creating a v3 for
display_mode_esc_sequence_len()similar toutf8_width()to accept an optional remainder argument?If NULL is given,
display_mode_esc_sequence_len()assumes a null-terminated string, otherwise the length is given in *remainder. The function can then update the remainder and return the length.
Callers could already sidestep the length check by passing SIZE_MAX, and the number of consumed bytes is returned, so I don't think that's needed.
Andy
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 2 lines · Andy Koppe
Callers could already sidestep the length check by passing
SIZE_MAX, and the number of consumed bytes is returned, so I don't think that's needed.
I like the simplicity of the approach. Thanks.
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 7 lines · Junio C Hamano
Quoted 2 lines · Andy Koppe
Callers could already sidestep the length check by passing
SIZE_MAX, and the number of consumed bytes is returned, so I don't think that's needed.I like the simplicity of the approach. Thanks.
Except, I was wrong, sorry. The 'end = s + len' would be undefined behaviour with SIZE_MAX. Callers do have to pass a valid length.
But it didn't sound like there are use cases that don't know the remaining length anyway and can't tolerate calling strlen().
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
In reply to Dirk Gouderst/meson.build clar_test_suites = [ · line 31
Quoted 10 lines · Dirk Gouders
t/meson.build +1
-0@@ -27,6 +27,7 @@ clar_test_suites = [ 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', 'unit-tests/u-utf8-width.c', + 'unit-tests/u-utf8-ansi.c', ]
Should this list be reordered? "make -C t check-meson" complains.
Re: [PATCH v2 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 14 lines · Junio C Hamano
t/meson.build clar_test_suites = [ · line 31
Quoted 10 lines · Dirk Gouders
t/meson.build +1
-0@@ -27,6 +27,7 @@ clar_test_suites = [ 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', 'unit-tests/u-utf8-width.c', + 'unit-tests/u-utf8-ansi.c', ]Should this list be reordered? "make -C t check-meson" complains.
Ah yes, thank you. The list in meson.txt must be sorted (check-meson diff's the output of ls(1) and the list in meson.build).
I will fix the sorting order with v3.
Dirk
PS: The purpose of 154ce05cce (Makefile: detect missing Meson tests, 2024-12-13) wasn't to enforce a sorted order and maybe it would help to put a comment in meson.build.
PATCH v2 2/4 utf8: fix comment for utf8_strnwidth()
In reply to Dirk GoudersThe comment for utf8_strnwidth() states it returns strlen() for cases when the given string doesn't look like valid utf8, but it returns its argument len in such cases.
Fix the comment accordingly.
--- utf8.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
utf8.c +1 -1
@@ -218,7 +218,7 @@ int utf8_width(const char **start, size_t *remainder_p)/* * Returns the total number of columns required by a null-terminated -* string, assuming that the string is utf8. Returns strlen() instead +* string, assuming that the string is utf8. Returns len instead * if the string does not look like a valid utf8 string. */ int utf8_strnwidth (const char *string,size_t len,int skip_ansi)
Signature · 1 line
2.55.0
Re: [PATCH v2 2/4] utf8: fix comment for utf8_strnwidth()
Quoted 6 lines · Dirk Gouders
The comment for
utf8_strnwidth()states it returnsstrlen()for cases when the given string doesn't look like valid utf8, but it returns its argument len in such cases.Fix the comment accordingly.
…
Quoted 7 lines
/*
* Returns the total number of columns required by a null-terminated
- * string, assuming that the string is utf8. Returnsstrlen()instead
+ * string, assuming that the string is utf8. Returns len instead
* if the string does not look like a valid utf8 string.
*/
intutf8_strnwidth(const char *string, size_t len, int skip_ansi)
"null-terminated" is wrong too.
Re: [PATCH v2 2/4] utf8: fix comment for utf8_strnwidth()
Quoted 16 lines · Andy Koppe
Quoted 6 lines · Dirk Gouders
The comment for
utf8_strnwidth()states it returnsstrlen()for cases when the given string doesn't look like valid utf8, but it returns its argument len in such cases.Fix the comment accordingly.
…
Quoted 7 lines
/*
* Returns the total number of columns required by a null-terminated
- * string, assuming that the string is utf8. Returnsstrlen()instead
+ * string, assuming that the string is utf8. Returns len instead
* if the string does not look like a valid utf8 string.
*/
intutf8_strnwidth(const char *string, size_t len, int skip_ansi)
Quoted 1 line
"null-terminated" is wrong too.
Yes, I will fix that, too. Thank you.
Dirk
PATCH v2 3/4 utf8: respect string boundaries after skipping ANSI escape sequences
In reply to Dirk Goudersutf8_strnwidth() can skip ANSI escape sequences and it is possible that such sequences end the string within the given boundary.
Check for such situations before proceeding and calling utf8_width().
Add tests that test such corner cases.
--- t/unit-tests/u-utf8-width.c | 11 +++++++++++ utf8.c | 12 ++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-)
t/unit-tests/u-utf8-width.c +11 -0
@@ -2,6 +2,17 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for strings with SGR sequences and corner case length +* arguments. +*/ +void test_utf8_width__strnwidth_ansi (void ) +{ +cl_assert_equal_i (3 ,utf8_strnwidth ("\033[31mhello" ,4 ,1 )); +cl_assert_equal_i (0 ,utf8_strnwidth ("\033[31mhello" ,5 ,1 )); +cl_assert_equal_i (1 ,utf8_strnwidth ("\033[31mhello" ,6 ,1 )); +} +/* * Test utf8_strnwidth with various Chinese strings * Chinese characters typically have a width of 2 columns when displayed
utf8.c +8 -4
@@ -230,10 +230,14 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)int glyph_width;size_t skip; -while (skip_ansi && - (skip =display_mode_esc_sequence_len_counted (string, - orig + len - string)) !=0 ) - string += skip; +if (skip_ansi ) { +while ((skip =display_mode_esc_sequence_len_counted (string, + orig + len - string)) !=0 ) + string += skip; + +if (string >= orig + len) +break ; + } glyph_width =utf8_width (&string,NULL );if (glyph_width >0 )
Signature · 1 line
2.55.0
Re: [PATCH v2 3/4] utf8: respect string boundaries after skipping ANSI escape sequences
utf8.c int utf8_strnwidth(const char *string, size_t len, int skip_ansi) · line 233
Quoted 5 lines · Dirk Gouders
utf8.c +1
-4-while (skip_ansi && - (skip =display_mode_esc_sequence_len_counted (string, - orig + len - string)) !=0 ) - string += skip; +if (skip_ansi ) {
Drop excess SP after the variable.
utf8.c int utf8_strnwidth(const char *string, size_t len, int skip_ansi) · line 236
Quoted 3 lines
utf8.c +3
-0+while ((skip =display_mode_esc_sequence_len_counted (string, + orig + len - string)) !=0 ) + string += skip;
Overlong line. You can (and are encouraged to) omit comparison with zero "!= 0" to lose 5 columns but it still is overly long.
if (skip_ansi) {
while ((skip = display_mode_esc_sequence_len_counted(
string, orig + len - string)))
string += skip;or something, perhaps.
Quoted 6 lines
utf8.c +3
-0+if (string >= orig + len) +break ; + } glyph_width =utf8_width (&string,NULL );if (glyph_width >0 )
PATCH v2 4/4 utf8: respect boundaries in utf8_strnwidth()
In reply to Dirk Goudersutf8_strnwidth() can be called with boundaries that effectively cause incomplete multibyte sequences and we should return "len" in such cases.
But, utf8_width is used without its optional boundary argument and will thus work beyond the given boundary.
Fix this by using the boundary argument for utf8_width. Add some tests that cover such situations.
--- t/unit-tests/u-utf8-width.c | 9 +++++++++ utf8.c | 5 ++++- 2 files changed, 13 insertions(+), 1 deletion(-)
t/unit-tests/u-utf8-width.c +9 -0
@@ -2,6 +2,15 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for cjk characters invalidated by len argument. +*/ +void test_utf8_width__strnwidth_cjk_chopped (void ) +{ +cl_assert_equal_i (1 ,utf8_strnwidth ("三bytes long, 二columns wide" ,1 ,1 )); +cl_assert_equal_i (2 ,utf8_strnwidth ("三bytes long, 二columns wide" ,3 ,1 )); +} +/* * Test utf8_strnwidth for strings with SGR sequences and corner case length * arguments.
utf8.c +4 -1
@@ -229,6 +229,7 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi) while (string && string < orig + len) { int glyph_width; size_t skip; + size_t remainder; if (skip_ansi ) { while ((skip = display_mode_esc_sequence_len_counted(string,
@@ -239,7 +240,9 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)break ; } - glyph_width =utf8_width (&string,NULL ); + remainder = orig + len - string; + + glyph_width =utf8_width (&string, &remainder);if (glyph_width >0 ) width += glyph_width; }
Signature · 1 line
2.55.0
Re: [PATCH v2 4/4] utf8: respect boundaries in utf8_strnwidth()
Quoted 7 lines · Dirk Gouders
utf8_strnwidth()can be called with boundaries that effectively cause incomplete multibyte sequences and we should return "len" in such cases.But,
utf8_widthis used without its optional boundary argument and will thus work beyond the given boundary.
Quoted 8 lines
Fix this by using the boundary argument for
utf8_width. Add some tests that cover such situations.Signed-off-by Dirk Gouders <[email protected]>--- t/unit-tests/u-utf8-width.c | 9 +++++++++ utf8.c | 5 ++++- 2 files changed, 13 insertions(+), 1 deletion(-)
Well spotted, and nicely done.
Quoted 44 lines
t/unit-tests/u-utf8-width.c +9
-0@@ -2,6 +2,15 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for cjk characters invalidated by len argument. +*/ +void test_utf8_width__strnwidth_cjk_chopped (void ) +{ +cl_assert_equal_i (1 ,utf8_strnwidth ("三bytes long, 二columns wide" ,1 ,1 )); +cl_assert_equal_i (2 ,utf8_strnwidth ("三bytes long, 二columns wide" ,3 ,1 )); +} +/* * Test utf8_strnwidth for strings with SGR sequences and corner case length * arguments. utf8.c +4
-1@@ -229,6 +229,7 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi) while (string && string < orig + len) { int glyph_width; size_t skip; + size_t remainder; if (skip_ansi ) { while ((skip = display_mode_esc_sequence_len_counted(string,@@ -239,7 +240,9 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)break ; } - glyph_width =utf8_width (&string,NULL ); + remainder = orig + len - string; + + glyph_width =utf8_width (&string, &remainder);if (glyph_width >0 ) width += glyph_width; }
v3 cover utf8: bounds-related fixes and a doc fix
In reply to Dirk GoudersA patch here on the list made me look at display_mode_esc_sequence_len() in utf8.c and I found two details in the file that are perhaps worth a fix:
1) utf8_strnwidth() disregards the given len argument when fed with proper string and len.
2) The comment for utf8_strnwidth() is incorrect: it states the function returns strlen() for cases when it actually returns its len argument.
---
Changes in v3:
- 1/5: * fix sorting order in t/meson.build
* fix risk of O(n²) degradation:
drop the wrapper function and introduce an end pointer to display_mode_esc_sequence_len()
(I was so used to len arguments for string handling functions
that I only now realized the beauty of optionally optional end pointers for string handling. I know: beauty is in the eye of the beholder ;-))
* try to fix an overly long line
- 2/5: also fix a further error concerning "null-terminated"
- 3/5: * drop excess SP in if-statement
- 5/5: this actually is a POC, not fixing a bug:
users of display_mode_esc_sequence_len() often need the length of all leading SGR sequences and here is a function that does that. I mentioned such a function in the discussion for v1.
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Add a patch by Junio that introduces a bounded function display_mode_esc_sequence_len_counted() I added some tests for this new function.
- 2/2 became 2/4
- 3/4 is the modified 1/2 and uses the new display_mode_esc_sequence_len_counted() so that the while loop stays
within the given bounds.
The commit message was adjusted.
One of the tests was wrong: "\033" has width 0, so the sum must be 3 instead of 4.
- 4/4 is an addition to fix a similar problem with utf8_width().
That function is used without its optional bounds argument and
can violate boundaries as well. Test for such cases are added.
- Link to v1: https://patch.msgid.link/[email protected]
---
Dirk Gouders (3):
utf8: fix comment for utf8_strnwidth()
utf8: respect string boundaries after skipping ANSI escape sequences
utf8: respect boundaries in utf8_strnwidth()
Junio C Hamano (1):
utf8: introduce bounds for display_mode_esc_sequence_len()
Makefile | 1 + pretty.c | 2 +- t/meson.build | 1 + t/unit-tests/u-utf8-ansi.c | 85 +++++++++++++++++++++++++++++++++++++++++++++ t/unit-tests/u-utf8-width.c | 20 +++++++++++ utf8.c | 78 +++++++++++++++++++++++++++++------------ utf8.h | 3 +- 7 files changed, 165 insertions(+), 25 deletions(-)
Range-diff versus v2:
1: 60979dc4d6 < -: ---------- utf8: add display_mode_esc_sequence_len_counted()
2: b8dbf5c5bf < -: ---------- utf8: fix comment for utf8_strnwidth()
-: ---------- > 1: 5b938b3fa0 utf8: introduce bounds for display_mode_esc_sequence_len()
-: ---------- > 2: 5ef8308d51 utf8: fix comment for utf8_strnwidth()
3: 12a99d1c8d ! 3: bd7c9b0b01 utf8: respect string boundaries after skipping ANSI escape sequences
@@ utf8.c: int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
size_t skip;
- while (skip_ansi &&
-- (skip = display_mode_esc_sequence_len_counted(string,
-- orig + len - string)) != 0)
+- (skip = display_mode_esc_sequence_len(string, end)))
- string += skip;
-+ if (skip_ansi ) {
-+ while ((skip = display_mode_esc_sequence_len_counted(string,
-+ orig + len - string)) != 0)
++ if (skip_ansi) {
++ while ((skip = display_mode_esc_sequence_len(string, end)))
+ string += skip;
+
-+ if (string >= orig + len)
++ if (string >= end)
+ break;
+ }4: 471c3d6888 < -: ---------- utf8: respect boundaries in utf8_strnwidth() -: ---------- > 4: a6cf4c99dc utf8: respect boundaries in utf8_strnwidth()
---
base-commit: 7fb6055e678f800320d8ab8cd8f201d9493d1ba0
change-id: 20261116-master-69b171612823
PATCH v3 1/4 utf8: introduce bounds for display_mode_esc_sequence_len()
From: Junio C Hamano <[email protected]>
display_mode_esc_sequence_len() scans for an ANSI display mode escape sequence (e.g. "ESC [ 1 ; 31 m") at the start of a string, relying on NUL termination to stop. Some callers, however, work on a counted buffer: utf8_strnwidth() takes <string, len> and must not scan past it, while strbuf_utf8_replace() and strbuf_add_wrapped_text() know (or can cheaply learn) the end.
Introduce an optional end pointer to display_mode_esc_sequence_len() which then never reads *end or beyond when end is not NULL. If end is NULL, display_mode_esc_sequence_len() assumes a NUL terminated string as before.
Andy Koppe pointed out the risk of performance degrading to O(n²) when functions process strings and have to check each position for an escape sequence [1]. This change doesn't carry this risk.
Further, add thorough tests for both end pointer cases.
[1] https://lore.kernel.org/git/CAHWeT-aWx1VwUjM+hZ--jjSAbcMenz5Mw11y9ouFavGndUMrSA@mail.gmail.com/
--- Makefile | 1 + pretty.c | 2 +- t/meson.build | 1 + t/unit-tests/u-utf8-ansi.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++ utf8.c | 34 ++++++++++++++++---------- utf8.h | 2 +- 6 files changed, 85 insertions(+), 14 deletions(-)
Makefile +1 -0
@@ -1563,6 +1563,7 @@ CLAR_TEST_SUITES += u-string-list CLAR_TEST_SUITES += u-strvec CLAR_TEST_SUITES += u-trailer CLAR_TEST_SUITES += u-urlmatch-normalization +CLAR_TEST_SUITES += u-utf8-ansi CLAR_TEST_SUITES += u-utf8-width CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X) CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES))
pretty.c +1 -1
@@ -1848,7 +1848,7 @@ static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */while (p > sb->buf && ch - p <10 && *p !='\033' ) p--;if (*p !='\033' || - ch +1 - p !=display_mode_esc_sequence_len (p)) + ch +1 - p !=display_mode_esc_sequence_len (p, ch +1 ))break ;/* * got a good ansi sequence, put it back to
t/meson.build +1 -0
@@ -26,6 +26,7 @@ clar_test_suites = [ 'unit-tests/u-strvec.c', 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', + 'unit-tests/u-utf8-ansi.c', 'unit-tests/u-utf8-width.c', ]
t/unit-tests/u-utf8-ansi.c new file +59 -0
59 lines not on this page · raw message
utf8.c +22 -12
@@ -16,18 +16,27 @@ struct interval {ucs_char_t last; }; -size_t display_mode_esc_sequence_len (const char *s) +/* +* Return the length of the ANSI display mode escape sequence (e.g., +* "\033[1;31m") that appears at the beginning of the string starting at start, +* or 0 if the string does not begin with a complete such sequence. +* If end is NULL, assume a NUL terminated string, else never look at *end or +* beyond. +*/ +size_t display_mode_esc_sequence_len (const char *start,const char *end) { -const char *p = s; -if (*p++ !='\033' ) +const char *p = start; + +if ((end && end <= p) || *p++ !='\033' )return 0 ; -if (*p++ !='[' ) +if ((end && end <= p) || *p++ !='[' )return 0 ; -while (isdigit (*p) || *p ==';' ) +while (((end && p < end) || (!end && *p)) && (isdigit (*p) || *p ==';' )) p++; -if (*p++ !='m' ) +if ((end && end <= p) || (!end && !*p) || *p++ !='m' )return 0 ; -return p - s; + +return p - start; }/* auxiliary function for binary search in interval table */
@@ -210,15 +219,15 @@ int utf8_width(const char **start, size_t *remainder_p)*/ int utf8_strnwidth (const char *string,size_t len,int skip_ansi) { -const char *orig = string; +const char *end = string + len;size_t width =0 ; -while (string && string < orig + len) { +while (string && string < end) {int glyph_width;size_t skip;while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) + (skip =display_mode_esc_sequence_len (string, end))) string += skip; glyph_width =utf8_width (&string,NULL );
@@ -279,6 +288,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf, {int indent, w, assume_utf8 =1 ;const char *bol, *space, *start = text; +const char *end = text +strlen (text);size_t orig_len = buf->len;if (width <=0 ) {
@@ -299,7 +309,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf,char c;size_t skip; -while ((skip =display_mode_esc_sequence_len (text))) +while ((skip =display_mode_esc_sequence_len (text, end))) text += skip; c = *text;
@@ -378,7 +388,7 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,int glyph_width;size_t n; -while ((n =display_mode_esc_sequence_len (src))) { +while ((n =display_mode_esc_sequence_len (src, end))) {strbuf_add (&dst, src, n); src += n; }
utf8.h +1 -1
@@ -5,7 +5,7 @@ struct strbuf;typedef unsigned int ucs_char_t ;/* assuming 32bit int */ -size_t display_mode_esc_sequence_len (const char *s); +size_t display_mode_esc_sequence_len (const char *start,const char *end);int utf8_width (const char **start,size_t *remainder_p);int utf8_strnwidth (const char *string,size_t len,int skip_ansi);int utf8_strwidth (const char *string);
Signature · 1 line
2.55.0
PATCH v3 2/4 utf8: fix comment for utf8_strnwidth()
In reply to Dirk GoudersThe comment for utf8_strnwidth() states it works on a NUL terminated string whereas the string is bounded by len.
It also states it returns strlen() for cases when the given string doesn't look like valid utf8, but it returns its argument len in such cases.
Fix the comment accordingly.
--- utf8.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
utf8.c +2 -2
@@ -213,8 +213,8 @@ int utf8_width(const char **start, size_t *remainder_p) }/* -* Returns the total number of columns required by a null-terminated -* string, assuming that the string is utf8. Returns strlen() instead +* Returns the total number of columns required by a string terminated by len, +* assuming that the string is utf8. Returns len instead * if the string does not look like a valid utf8 string. */ int utf8_strnwidth (const char *string,size_t len,int skip_ansi)
Signature · 1 line
2.55.0
PATCH v3 3/4 utf8: respect string boundaries after skipping ANSI escape sequences
In reply to Dirk Goudersutf8_strnwidth() can skip ANSI escape sequences and it is possible that such sequences end the string within the given boundary.
Check for such situations before proceeding and calling utf8_width().
Add tests that test such corner cases.
--- t/unit-tests/u-utf8-width.c | 11 +++++++++++ utf8.c | 10 +++++++--- 2 files changed, 18 insertions(+), 3 deletions(-)
t/unit-tests/u-utf8-width.c +11 -0
@@ -2,6 +2,17 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for strings with SGR sequences and corner case length +* arguments. +*/ +void test_utf8_width__strnwidth_ansi (void ) +{ +cl_assert_equal_i (3 ,utf8_strnwidth ("\033[31mhello" ,4 ,1 )); +cl_assert_equal_i (0 ,utf8_strnwidth ("\033[31mhello" ,5 ,1 )); +cl_assert_equal_i (1 ,utf8_strnwidth ("\033[31mhello" ,6 ,1 )); +} +/* * Test utf8_strnwidth with various Chinese strings * Chinese characters typically have a width of 2 columns when displayed
utf8.c +7 -3
@@ -226,9 +226,13 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)int glyph_width;size_t skip; -while (skip_ansi && - (skip =display_mode_esc_sequence_len (string, end))) - string += skip; +if (skip_ansi) { +while ((skip =display_mode_esc_sequence_len (string, end))) + string += skip; + +if (string >= end) +break ; + } glyph_width =utf8_width (&string,NULL );if (glyph_width >0 )
Signature · 1 line
2.55.0
PATCH v3 4/4 utf8: respect boundaries in utf8_strnwidth()
In reply to Dirk Goudersutf8_strnwidth() can be called with boundaries that effectively cause incomplete multibyte sequences and we should return "len" in such cases.
But, utf8_width is used without its optional boundary argument and will thus work beyond the given boundary.
Fix this by using the boundary argument for utf8_width. Add some tests that cover such situations.
--- t/unit-tests/u-utf8-ansi.c | 26 ++++++++++++++++++++++++++ t/unit-tests/u-utf8-width.c | 9 +++++++++ utf8.c | 40 +++++++++++++++++++++++++++++----------- utf8.h | 1 + 4 files changed, 65 insertions(+), 11 deletions(-)
t/unit-tests/u-utf8-ansi.c +26 -0
@@ -2,6 +2,32 @@#include "utf8.h" #include "strbuf.h" +/* +* Test the greedy function display_mode_esc_sequence_len_all(). +*/ +void test_utf8_ansi__sgr_len_greedy (void ) +{ +char *s1 = (char *)"no ESC sequence" ; +char *s2 = (char *)"\033[m" ; +char *s3 = (char *)"\033[0;31m" ; +char *s4 = (char *)"\033[0m\033[31m" ; + +/* no sequences */ +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_all ("" ,"" )); +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_all (s1, s1 +5 )); + +/* single sequences */ +cl_assert_equal_i (3 ,display_mode_esc_sequence_len_all (s2, s2 +3 )); +cl_assert_equal_i (7 ,display_mode_esc_sequence_len_all (s3, s3 +7 )); +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_all (s3, s3 +3 )); + +/* multiple sequences */ +cl_assert_equal_i (4 ,display_mode_esc_sequence_len_all (s4, s4 +4 )); +cl_assert_equal_i (9 ,display_mode_esc_sequence_len_all (s4, s4 +9 )); +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_all (s4, s4 +3 )); +cl_assert_equal_i (4 ,display_mode_esc_sequence_len_all (s4, s4 +8 )); +} +/* * Test display_mode_esc_sequence_len() for NUL terminated strings. */
t/unit-tests/u-utf8-width.c +9 -0
@@ -2,6 +2,15 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for cjk characters invalidated by len argument. +*/ +void test_utf8_width__strnwidth_cjk_chopped (void ) +{ +cl_assert_equal_i (1 ,utf8_strnwidth ("三bytes long, 二columns wide" ,1 ,1 )); +cl_assert_equal_i (2 ,utf8_strnwidth ("三bytes long, 二columns wide" ,3 ,1 )); +} +/* * Test utf8_strnwidth for strings with SGR sequences and corner case length * arguments.
utf8.c +29 -11
@@ -39,6 +39,26 @@ size_t display_mode_esc_sequence_len(const char *start, const char *end)return p - start; } +/* +* Count the lenght of all leading ANSI display mode escape sequences that +* are a prefix of the string at start up to end. +*/ +size_t display_mode_esc_sequence_len_all (const char *start,const char *end) +{ +size_t seq_len =0 ; + +while (start + seq_len < end) { +size_t count =display_mode_esc_sequence_len (start + seq_len, end); + +if (!count) +break ; + + seq_len += count; + } + +return seq_len; +} +/* auxiliary function for binary search in interval table */ static int bisearch (ucs_char_t ucs,const struct interval *table,int max) {
@@ -224,17 +244,18 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)while (string && string < end) {int glyph_width; -size_t skip; +size_t remainder;if (skip_ansi) { -while ((skip =display_mode_esc_sequence_len (string, end))) - string += skip; + string +=display_mode_esc_sequence_len_all (string, end);if (string >= end)break ; } - glyph_width =utf8_width (&string,NULL ); + remainder = end - string; + + glyph_width =utf8_width (&string, &remainder);if (glyph_width >0 ) width += glyph_width; }
@@ -311,10 +332,8 @@ void strbuf_add_wrapped_text(struct strbuf *buf,for (;;) {char c; -size_t skip; -while ((skip =display_mode_esc_sequence_len (text, end))) - text += skip; + text +=display_mode_esc_sequence_len_all (text, end); c = *text;if (!c ||isspace (c)) {
@@ -392,10 +411,9 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,int glyph_width;size_t n; -while ((n =display_mode_esc_sequence_len (src, end))) { -strbuf_add (&dst, src, n); - src += n; - } + n =display_mode_esc_sequence_len_all (src, end); +strbuf_add (&dst, src, n); + src += n;if (src >= end)break ;
utf8.h +1 -0
@@ -6,6 +6,7 @@ struct strbuf;typedef unsigned int ucs_char_t ;/* assuming 32bit int */ size_t display_mode_esc_sequence_len (const char *start,const char *end); +size_t display_mode_esc_sequence_len_all (const char *start,const char *end);int utf8_width (const char **start,size_t *remainder_p);int utf8_strnwidth (const char *string,size_t len,int skip_ansi);int utf8_strwidth (const char *string);
Signature · 1 line
2.55.0
Re: [PATCH v3 0/4] utf8: bounds-related fixes and a doc fix
In reply to Dirk GoudersI used --reflect >5 times but with the final "simple" polish I squased two commits -- and did not --reflect one more time...
Please disregard this series.
Dirk
Quoted 96 lines · Dirk Gouders
A patch here on the list made me look at
display_mode_esc_sequence_len()inutf8.cand I found two details in the file that are perhaps worth a fix:1)
utf8_strnwidth()disregards the given len argument when fed with proper string and len.2) The comment for
utf8_strnwidth()is incorrect: it states the function returnsstrlen()for cases when it actually returns its len argument.Signed-off-by Dirk Gouders <[email protected]>---
Changes in v3:
- 1/5: * fix sorting order in t/meson.build
* fix risk of O(n²) degradation:
drop the wrapper function and introduce an end pointer todisplay_mode_esc_sequence_len()
(I was so used to len arguments for string handling functions
that I only now realized the beauty of optionally optional end pointers for string handling. I know: beauty is in the eye of the beholder ;-))
* try to fix an overly long line
- 2/5: also fix a further error concerning "null-terminated"
- 3/5: * drop excess SP in if-statement
- 5/5: this actually is a POC, not fixing a bug:
users ofdisplay_mode_esc_sequence_len()often need the length of all leading SGR sequences and here is a function that does that. I mentioned such a function in the discussion for v1.
- Link to v2: https://patch.msgid.link/[email protected]Changes in v2:
- Add a patch by Junio that introduces a bounded functiondisplay_mode_esc_sequence_len_counted()I added some tests for this new function.
- 2/2 became 2/4
- 3/4 is the modified 1/2 and uses the newdisplay_mode_esc_sequence_len_counted()so that the while loop stays
within the given bounds.
The commit message was adjusted.
One of the tests was wrong: "\033" has width 0, so the sum must be 3 instead of 4.
- 4/4 is an addition to fix a similar problem withutf8_width().
That function is used without its optional bounds argument and
can violate boundaries as well. Test for such cases are added.
- Link to v1: https://patch.msgid.link/[email protected]---
Dirk Gouders (3):
utf8: fix comment forutf8_strnwidth()
utf8: respect string boundaries after skipping ANSI escape sequences
utf8: respect boundaries inutf8_strnwidth()Junio C Hamano (1):
utf8: introduce bounds fordisplay_mode_esc_sequence_len()Makefile | 1 + pretty.c | 2 +- t/meson.build | 1 + t/unit-tests/u-utf8-ansi.c | 85 +++++++++++++++++++++++++++++++++++++++++++++ t/unit-tests/u-utf8-width.c | 20 +++++++++++ utf8.c | 78 +++++++++++++++++++++++++++++------------ utf8.h | 3 +- 7 files changed, 165 insertions(+), 25 deletions(-)Range-diff versus v2:
1: 60979dc4d6 < -: ---------- utf8: add display_mode_esc_sequence_len_counted() 2: b8dbf5c5bf < -: ---------- utf8: fix comment for utf8_strnwidth() -: ---------- > 1: 5b938b3fa0 utf8: introduce bounds for display_mode_esc_sequence_len() -: ---------- > 2: 5ef8308d51 utf8: fix comment for utf8_strnwidth() 3: 12a99d1c8d ! 3: bd7c9b0b01 utf8: respect string boundaries after skipping ANSI escape sequences @@ utf8.c: int utf8_strnwidth(const char *string, size_t len, int skip_ansi) size_t skip; - while (skip_ansi && -- (skip = display_mode_esc_sequence_len_counted(string, -- orig + len - string)) != 0) +- (skip = display_mode_esc_sequence_len(string, end))) - string += skip; -+ if (skip_ansi ) { -+ while ((skip = display_mode_esc_sequence_len_counted(string, -+ orig + len - string)) != 0) ++ if (skip_ansi) { ++ while ((skip = display_mode_esc_sequence_len(string, end))) + string += skip; + -+ if (string >= orig + len) ++ if (string >= end) + break; + }4: 471c3d6888 < -: ---------- utf8: respect boundaries in utf8_strnwidth() -: ---------- > 4: a6cf4c99dc utf8: respect boundaries in utf8_strnwidth()---
base-commit:7fb6055e678f800320d8ab8cd8f201d9493d1ba0
change-id: 20261116-master-69b171612823
v4 cover utf8: bounds-related fixes and a doc fix
In reply to Dirk GoudersA patch here on the list made me look at display_mode_esc_sequence_len() in utf8.c and I found two details in the file that are perhaps worth a fix:
1) utf8_strnwidth() disregards the given len argument when fed with proper string and len.
2) The comment for utf8_strnwidth() is incorrect: it states the function returns strlen() for cases when it actually returns its len argument.
---
Changes in v4:
- Resend un-squashed v3
Changes in v3:
- 1/5: * fix sorting order in t/meson.build
* fix risk of O(n²) degradation:
drop the wrapper function and introduce an end pointer to display_mode_esc_sequence_len()
(I was so used to len arguments for string handling functions
that I only now realized the beauty of optionally optional end pointers for string handling. I know: beauty is in the eye of the beholder ;-))
* try to fix an overly long line
- 2/5: also fix a further error concerning "null-terminated"
- 3/5: * drop excess SP in if-statement
- 5/5: this actually is a POC, not fixing a bug:
users of display_mode_esc_sequence_len() often need the length of all leading SGR sequences and here is a function that does that. I mentioned such a function in the discussion for v1.
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Add a patch by Junio that introduces a bounded function display_mode_esc_sequence_len_counted() I added some tests for this new function.
- 2/2 became 2/4
- 3/4 is the modified 1/2 and uses the new display_mode_esc_sequence_len_counted() so that the while loop stays
within the given bounds.
The commit message was adjusted.
One of the tests was wrong: "\033" has width 0, so the sum must be 3 instead of 4.
- 4/4 is an addition to fix a similar problem with utf8_width().
That function is used without its optional bounds argument and
can violate boundaries as well. Test for such cases are added.
- Link to v1: https://patch.msgid.link/[email protected]
---
Dirk Gouders (4):
utf8: fix comment for utf8_strnwidth()
utf8: respect string boundaries after skipping ANSI escape sequences
utf8: respect boundaries in utf8_strnwidth()
utf8: introduce display_mode_esc_sequence_len_all()
Junio C Hamano (1):
utf8: introduce bounds for display_mode_esc_sequence_len()
Makefile | 1 + pretty.c | 2 +- t/meson.build | 1 + t/unit-tests/u-utf8-ansi.c | 85 +++++++++++++++++++++++++++++++++++++++++++++ t/unit-tests/u-utf8-width.c | 20 +++++++++++ utf8.c | 78 +++++++++++++++++++++++++++++------------ utf8.h | 3 +- 7 files changed, 165 insertions(+), 25 deletions(-)
Range-diff versus v3:
1: 122df176a3 = 1: ce2736da52 utf8: introduce bounds for display_mode_esc_sequence_len() 2: 6cb2da91ae = 2: ec70d5e553 utf8: fix comment for utf8_strnwidth() 3: d62360d690 = 3: 0e09e16822 utf8: respect string boundaries after skipping ANSI escape sequences -: ---------- > 4: f49010e6c5 utf8: respect boundaries in utf8_strnwidth() 4: caca770f8b ! 5: eb428dfc47 utf8: respect boundaries in utf8_strnwidth()
@@ Metadata
Author: Dirk Gouders <[email protected]>
## Commit message ##
- utf8: respect boundaries in utf8_strnwidth()
+ utf8: introduce display_mode_esc_sequence_len_all()
- utf8_strnwidth() can be called with boundaries that effectively cause
- incomplete multibyte sequences and we should return "len" in such
- cases.
+ Most users of display_mode_esc_sequence_len() need to know the length
+ of *all* leading ANSI display mode escape sequences and use
+ display_mode_esc_sequence_len() in a loop.
- But, utf8_width is used without its optional boundary argument and
- will thus work beyond the given boundary.
+ Introduce display_mode_esc_sequence_len_all() for convenience and
+ to reduce the risk of bugs.
- Fix this by using the boundary argument for utf8_width.
- Add some tests that cover such situations.
+ Add tests for this function as well.
@@ t/unit-tests/u-utf8-ansi.c
* Test display_mode_esc_sequence_len() for NUL terminated strings. */
- ## t/unit-tests/u-utf8-width.c ##
-@@
- #include "utf8.h"
- #include "strbuf.h"
-
-+/*
-+ * Test utf8_strnwidth for cjk characters invalidated by len argument. -+ */
-+void test_utf8_width__strnwidth_cjk_chopped(void)
-+{
-+ cl_assert_equal_i(1, utf8_strnwidth("三bytes long, 二columns wide", 1, 1));
-+ cl_assert_equal_i(2, utf8_strnwidth("三bytes long, 二columns wide", 3, 1));
-+}
-+
- /*
- * Test utf8_strnwidth for strings with SGR sequences and corner case length
- * arguments.
-
## utf8.c ##
@@ utf8.c: size_t display_mode_esc_sequence_len(const char *start, const char *end)
return p - start;
@@ utf8.c: size_t display_mode_esc_sequence_len(const char *start, const char *end)
static int bisearch(ucs_char_t ucs, const struct interval *table, int max) {
@@ utf8.c: int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
-
- while (string && string < end) {
- int glyph_width;
-- size_t skip;
-+ size_t remainder;
+ size_t remainder;
if (skip_ansi) {
- while ((skip = display_mode_esc_sequence_len(string, end)))
@@ utf8.c: int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
if (string >= end)
break;
- }
-
-- glyph_width = utf8_width(&string, NULL);
-+ remainder = end - string;
-+
-+ glyph_width = utf8_width(&string, &remainder);
- if (glyph_width > 0)
- width += glyph_width;
- }
@@ utf8.c: void strbuf_add_wrapped_text(struct strbuf *buf,
for (;;) {
---
base-commit: 7fb6055e678f800320d8ab8cd8f201d9493d1ba0
change-id: 20261116-master-69b171612823
PATCH v4 1/5 utf8: introduce bounds for display_mode_esc_sequence_len()
From: Junio C Hamano <[email protected]>
display_mode_esc_sequence_len() scans for an ANSI display mode escape sequence (e.g. "ESC [ 1 ; 31 m") at the start of a string, relying on NUL termination to stop. Some callers, however, work on a counted buffer: utf8_strnwidth() takes <string, len> and must not scan past it, while strbuf_utf8_replace() and strbuf_add_wrapped_text() know (or can cheaply learn) the end.
Introduce an optional end pointer to display_mode_esc_sequence_len() which then never reads *end or beyond when end is not NULL. If end is NULL, display_mode_esc_sequence_len() assumes a NUL terminated string as before.
Andy Koppe pointed out the risk of performance degrading to O(n²) when functions process strings and have to check each position for an escape sequence [1]. This change doesn't carry this risk.
Further, add thorough tests for both end pointer cases.
[1] https://lore.kernel.org/git/CAHWeT-aWx1VwUjM+hZ--jjSAbcMenz5Mw11y9ouFavGndUMrSA@mail.gmail.com/
--- Makefile | 1 + pretty.c | 2 +- t/meson.build | 1 + t/unit-tests/u-utf8-ansi.c | 59 ++++++++++++++++++++++++++++++++++++++++++++++ utf8.c | 34 ++++++++++++++++---------- utf8.h | 2 +- 6 files changed, 85 insertions(+), 14 deletions(-)
Makefile +1 -0
@@ -1563,6 +1563,7 @@ CLAR_TEST_SUITES += u-string-list CLAR_TEST_SUITES += u-strvec CLAR_TEST_SUITES += u-trailer CLAR_TEST_SUITES += u-urlmatch-normalization +CLAR_TEST_SUITES += u-utf8-ansi CLAR_TEST_SUITES += u-utf8-width CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X) CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES))
pretty.c +1 -1
@@ -1848,7 +1848,7 @@ static size_t format_and_pad_commit(struct strbuf *sb, /* in UTF-8 */while (p > sb->buf && ch - p <10 && *p !='\033' ) p--;if (*p !='\033' || - ch +1 - p !=display_mode_esc_sequence_len (p)) + ch +1 - p !=display_mode_esc_sequence_len (p, ch +1 ))break ;/* * got a good ansi sequence, put it back to
t/meson.build +1 -0
@@ -26,6 +26,7 @@ clar_test_suites = [ 'unit-tests/u-strvec.c', 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', + 'unit-tests/u-utf8-ansi.c', 'unit-tests/u-utf8-width.c', ]
t/unit-tests/u-utf8-ansi.c new file +59 -0
59 lines not on this page · raw message
utf8.c +22 -12
@@ -16,18 +16,27 @@ struct interval {ucs_char_t last; }; -size_t display_mode_esc_sequence_len (const char *s) +/* +* Return the length of the ANSI display mode escape sequence (e.g., +* "\033[1;31m") that appears at the beginning of the string starting at start, +* or 0 if the string does not begin with a complete such sequence. +* If end is NULL, assume a NUL terminated string, else never look at *end or +* beyond. +*/ +size_t display_mode_esc_sequence_len (const char *start,const char *end) { -const char *p = s; -if (*p++ !='\033' ) +const char *p = start; + +if ((end && end <= p) || *p++ !='\033' )return 0 ; -if (*p++ !='[' ) +if ((end && end <= p) || *p++ !='[' )return 0 ; -while (isdigit (*p) || *p ==';' ) +while (((end && p < end) || (!end && *p)) && (isdigit (*p) || *p ==';' )) p++; -if (*p++ !='m' ) +if ((end && end <= p) || (!end && !*p) || *p++ !='m' )return 0 ; -return p - s; + +return p - start; }/* auxiliary function for binary search in interval table */
@@ -210,15 +219,15 @@ int utf8_width(const char **start, size_t *remainder_p)*/ int utf8_strnwidth (const char *string,size_t len,int skip_ansi) { -const char *orig = string; +const char *end = string + len;size_t width =0 ; -while (string && string < orig + len) { +while (string && string < end) {int glyph_width;size_t skip;while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) + (skip =display_mode_esc_sequence_len (string, end))) string += skip; glyph_width =utf8_width (&string,NULL );
@@ -279,6 +288,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf, {int indent, w, assume_utf8 =1 ;const char *bol, *space, *start = text; +const char *end = text +strlen (text);size_t orig_len = buf->len;if (width <=0 ) {
@@ -299,7 +309,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf,char c;size_t skip; -while ((skip =display_mode_esc_sequence_len (text))) +while ((skip =display_mode_esc_sequence_len (text, end))) text += skip; c = *text;
@@ -378,7 +388,7 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,int glyph_width;size_t n; -while ((n =display_mode_esc_sequence_len (src))) { +while ((n =display_mode_esc_sequence_len (src, end))) {strbuf_add (&dst, src, n); src += n; }
utf8.h +1 -1
@@ -5,7 +5,7 @@ struct strbuf;typedef unsigned int ucs_char_t ;/* assuming 32bit int */ -size_t display_mode_esc_sequence_len (const char *s); +size_t display_mode_esc_sequence_len (const char *start,const char *end);int utf8_width (const char **start,size_t *remainder_p);int utf8_strnwidth (const char *string,size_t len,int skip_ansi);int utf8_strwidth (const char *string);
Signature · 1 line
2.55.0
Re: [PATCH v4 1/5] utf8: introduce bounds for display_mode_esc_sequence_len()
Quoted 13 lines · Dirk Gouders
+ * Return the length of the ANSI display mode escape sequence (e.g.,
+ * "\033[1;31m") that appears at the beginning of the string starting at start,
+ * or 0 if the string does not begin with a complete such sequence.
+ * If end is NULL, assume a NUL terminated string, else never look at *end or
+ * beyond.
+ */utf8.c +4
-2+size_t display_mode_esc_sequence_len (const char *start,const char *end) { -const char *p = s; -if (*p++ !='\033' ) +const char *p = start; + +if ((end && end <= p) || *p++ !='\033' )
utf8.c struct interval { · line 37
Quoted 10 lines
utf8.c +3
-3return 0 ; -if (*p++ !='[' ) +if ((end && end <= p) || *p++ !='[' )return 0 ; -while (isdigit (*p) || *p ==';' ) +while (((end && p < end) || (!end && *p)) && (isdigit (*p) || *p ==';' )) p++; -if (*p++ !='m' ) +if ((end && end <= p) || (!end && !*p) || *p++ !='m' )return 0 ;
Those checks can be simplified a bit:
while (!(end && p >= end) && (isdigit(*p) || *p == ';'))
p++;
if ((end && p >= end) || *p++ != 'm')
return 0;In case you want to go back to a length parameter instead of the optional end pointer: I looked it up and functions such as strncmp() and POSIX strnlen() that take a length bound actually support passing SIZE_MAX as the length.
The key is not to compute s + len, because that can create a pointer more than one past the end of the object, which is undefined behaviour even without dereferencing the pointer. Instead, the bounds need to be checked with something like p - s < len before reading *p, which avoids creating an undefined pointer.
Andy
Re: [PATCH v4 1/5] utf8: introduce bounds for display_mode_esc_sequence_len()
Quoted 27 lines · Andy Koppe
Quoted 13 lines · Dirk Gouders
+ * Return the length of the ANSI display mode escape sequence (e.g.,
+ * "\033[1;31m") that appears at the beginning of the string starting at start,
+ * or 0 if the string does not begin with a complete such sequence.
+ * If end is NULL, assume a NUL terminated string, else never look at *end or
+ * beyond.
+ */utf8.c +4
-2+size_t display_mode_esc_sequence_len (const char *start,const char *end) { -const char *p = s; -if (*p++ !='\033' ) +const char *p = start; + +if ((end && end <= p) || *p++ !='\033' )utf8.c struct interval { · line 37
Quoted 10 lines
utf8.c +3
-3return 0 ; -if (*p++ !='[' ) +if ((end && end <= p) || *p++ !='[' )return 0 ; -while (isdigit (*p) || *p ==';' ) +while (((end && p < end) || (!end && *p)) && (isdigit (*p) || *p ==';' )) p++; -if (*p++ !='m' ) +if ((end && end <= p) || (!end && !*p) || *p++ !='m' )return 0 ;Those checks can be simplified a bit:
Quoted 4 lines
while (!(end && p >= end) && (isdigit(*p) || *p == ';'))
p++;
if ((end && p >= end) || *p++ != 'm')
return 0;Yes, thanks for spotting this.
Dirk
Re: [PATCH v4 1/5] utf8: introduce bounds for display_mode_esc_sequence_len()
In reply to Andy KoppeQuoted 10 lines · Andy Koppe
In case you want to go back to a length parameter instead of the optional end pointer: I looked it up and functions such as
strncmp()and POSIXstrnlen()that take a length bound actually support passingSIZE_MAXas the length.The key is not to compute
s + len, because that can create a pointer more than one past the end of the object, which is undefined behaviour even without dereferencing the pointer. Instead, the bounds need to be checked with something likep - s < lenbefore reading*p, which avoids creating an undefined pointer.
That sounds very reasonable and also fixes the O(n²) risk.
So, I will take Junio's function as suggested, check it for s + len problems and the wrapper then simply calls it with SIZE_MAX.
Thanks for the review,
Dirk
Re: [PATCH v4 1/5] utf8: introduce bounds for display_mode_esc_sequence_len()
In reply to Dirk Gouderst/unit-tests/u-utf8-ansi.c line 35
Quoted 8 lines · Dirk Gouders
t/unit-tests/u-utf8-ansi.c new file +8
-0+void test_utf8_ansi__sgr_len_end_ptr (void ) +{ +char *sgr_1 = (char *)"\033[m" ; +char *sgr_2 = (char *)"\033[31m" ; +char *sgr_3 = (char *)"\033[31;m" ; +char *sgr_4 = (char *)"\033[31;0m" ; + +cl_assert_equal_i (0 ,display_mode_esc_sequence_len ("" ,"" ));
Strictly speaking, that's undefined behaviour, because it makes display_mode_esc_sequence_len() compare pointers to different objects. In practice, the compiler will pass a pointer to the same empty string for both arguments, but the test should not rely on that.
t/unit-tests/u-utf8-ansi.c line 48
Quoted 2 lines
t/unit-tests/u-utf8-ansi.c new file +2
-0+cl_assert_equal_i (6 ,display_mode_esc_sequence_len (sgr_3, sgr_3 +sizeof (sgr_3) -1 )); +cl_assert_equal_i (7 ,display_mode_esc_sequence_len (sgr_4, sgr_4 +sizeof (sgr_4) -1 ));
Those sizeofs return the sizes of the pointers rather than the strings as intended. (And the lines are a bit long.)
Andy
Re: [PATCH v4 1/5] utf8: introduce bounds for display_mode_esc_sequence_len()
Quoted 15 lines · Andy Koppe
t/unit-tests/u-utf8-ansi.c line 35
Quoted 8 lines · Dirk Gouders
t/unit-tests/u-utf8-ansi.c new file +8
-0+void test_utf8_ansi__sgr_len_end_ptr (void ) +{ +char *sgr_1 = (char *)"\033[m" ; +char *sgr_2 = (char *)"\033[31m" ; +char *sgr_3 = (char *)"\033[31;m" ; +char *sgr_4 = (char *)"\033[31;0m" ; + +cl_assert_equal_i (0 ,display_mode_esc_sequence_len ("" ,"" ));Strictly speaking, that's undefined behaviour, because it makes
display_mode_esc_sequence_len()compare pointers to different objects. In practice, the compiler will pass a pointer to the same empty string for both arguments, but the test should not rely on that.
Quoted 5 lines
t/unit-tests/u-utf8-ansi.c line 48
Quoted 2 lines
t/unit-tests/u-utf8-ansi.c new file +2
-0+cl_assert_equal_i (6 ,display_mode_esc_sequence_len (sgr_3, sgr_3 +sizeof (sgr_3) -1 )); +cl_assert_equal_i (7 ,display_mode_esc_sequence_len (sgr_4, sgr_4 +sizeof (sgr_4) -1 ));Those sizeofs return the sizes of the pointers rather than the strings as intended. (And the lines are a bit long.)
Thank you, all of these will be fixed.
Dirk
PATCH v4 2/5 utf8: fix comment for utf8_strnwidth()
In reply to Dirk GoudersThe comment for utf8_strnwidth() states it works on a NUL terminated string whereas the string is bounded by len.
It also states it returns strlen() for cases when the given string doesn't look like valid utf8, but it returns its argument len in such cases.
Fix the comment accordingly.
--- utf8.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
utf8.c +2 -2
@@ -213,8 +213,8 @@ int utf8_width(const char **start, size_t *remainder_p) }/* -* Returns the total number of columns required by a null-terminated -* string, assuming that the string is utf8. Returns strlen() instead +* Returns the total number of columns required by a string terminated by len, +* assuming that the string is utf8. Returns len instead * if the string does not look like a valid utf8 string. */ int utf8_strnwidth (const char *string,size_t len,int skip_ansi)
Signature · 1 line
2.55.0
PATCH v4 3/5 utf8: respect string boundaries after skipping ANSI escape sequences
In reply to Dirk Goudersutf8_strnwidth() can skip ANSI escape sequences and it is possible that such sequences end the string within the given boundary.
Check for such situations before proceeding and calling utf8_width().
Add tests that test such corner cases.
--- t/unit-tests/u-utf8-width.c | 11 +++++++++++ utf8.c | 10 +++++++--- 2 files changed, 18 insertions(+), 3 deletions(-)
t/unit-tests/u-utf8-width.c +11 -0
@@ -2,6 +2,17 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for strings with SGR sequences and corner case length +* arguments. +*/ +void test_utf8_width__strnwidth_ansi (void ) +{ +cl_assert_equal_i (3 ,utf8_strnwidth ("\033[31mhello" ,4 ,1 )); +cl_assert_equal_i (0 ,utf8_strnwidth ("\033[31mhello" ,5 ,1 )); +cl_assert_equal_i (1 ,utf8_strnwidth ("\033[31mhello" ,6 ,1 )); +} +/* * Test utf8_strnwidth with various Chinese strings * Chinese characters typically have a width of 2 columns when displayed
utf8.c +7 -3
@@ -226,9 +226,13 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)int glyph_width;size_t skip; -while (skip_ansi && - (skip =display_mode_esc_sequence_len (string, end))) - string += skip; +if (skip_ansi) { +while ((skip =display_mode_esc_sequence_len (string, end))) + string += skip; + +if (string >= end) +break ; + } glyph_width =utf8_width (&string,NULL );if (glyph_width >0 )
Signature · 1 line
2.55.0
PATCH v4 4/5 utf8: respect boundaries in utf8_strnwidth()
In reply to Dirk Goudersutf8_strnwidth() can be called with boundaries that effectively cause incomplete multibyte sequences and we should return "len" in such cases.
But, utf8_width is used without its optional boundary argument and will thus work beyond the given boundary.
Fix this by using the boundary argument for utf8_width. Add some tests that cover such situations.
--- t/unit-tests/u-utf8-width.c | 9 +++++++++ utf8.c | 6 ++++-- 2 files changed, 13 insertions(+), 2 deletions(-)
t/unit-tests/u-utf8-width.c +9 -0
@@ -2,6 +2,15 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for cjk characters invalidated by len argument. +*/ +void test_utf8_width__strnwidth_cjk_chopped (void ) +{ +cl_assert_equal_i (1 ,utf8_strnwidth ("三bytes long, 二columns wide" ,1 ,1 )); +cl_assert_equal_i (2 ,utf8_strnwidth ("三bytes long, 二columns wide" ,3 ,1 )); +} +/* * Test utf8_strnwidth for strings with SGR sequences and corner case length * arguments.
utf8.c +4 -2
@@ -224,7 +224,7 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)while (string && string < end) {int glyph_width; -size_t skip; +size_t remainder;if (skip_ansi) {while ((skip =display_mode_esc_sequence_len (string, end)))
@@ -234,7 +234,9 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)break ; } - glyph_width =utf8_width (&string,NULL ); + remainder = end - string; + + glyph_width =utf8_width (&string, &remainder);if (glyph_width >0 ) width += glyph_width; }
Signature · 1 line
2.55.0
PATCH v4 5/5 utf8: introduce display_mode_esc_sequence_len_all()
In reply to Dirk GoudersMost users of display_mode_esc_sequence_len() need to know the length of *all* leading ANSI display mode escape sequences and use display_mode_esc_sequence_len() in a loop.
Introduce display_mode_esc_sequence_len_all() for convenience and to reduce the risk of bugs.
Add tests for this function as well.
--- t/unit-tests/u-utf8-ansi.c | 26 ++++++++++++++++++++++++++ utf8.c | 34 +++++++++++++++++++++++++--------- utf8.h | 1 + 3 files changed, 52 insertions(+), 9 deletions(-)
t/unit-tests/u-utf8-ansi.c +26 -0
@@ -2,6 +2,32 @@#include "utf8.h" #include "strbuf.h" +/* +* Test the greedy function display_mode_esc_sequence_len_all(). +*/ +void test_utf8_ansi__sgr_len_greedy (void ) +{ +char *s1 = (char *)"no ESC sequence" ; +char *s2 = (char *)"\033[m" ; +char *s3 = (char *)"\033[0;31m" ; +char *s4 = (char *)"\033[0m\033[31m" ; + +/* no sequences */ +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_all ("" ,"" )); +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_all (s1, s1 +5 )); + +/* single sequences */ +cl_assert_equal_i (3 ,display_mode_esc_sequence_len_all (s2, s2 +3 )); +cl_assert_equal_i (7 ,display_mode_esc_sequence_len_all (s3, s3 +7 )); +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_all (s3, s3 +3 )); + +/* multiple sequences */ +cl_assert_equal_i (4 ,display_mode_esc_sequence_len_all (s4, s4 +4 )); +cl_assert_equal_i (9 ,display_mode_esc_sequence_len_all (s4, s4 +9 )); +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_all (s4, s4 +3 )); +cl_assert_equal_i (4 ,display_mode_esc_sequence_len_all (s4, s4 +8 )); +} +/* * Test display_mode_esc_sequence_len() for NUL terminated strings. */
utf8.c +25 -9
@@ -39,6 +39,26 @@ size_t display_mode_esc_sequence_len(const char *start, const char *end)return p - start; } +/* +* Count the lenght of all leading ANSI display mode escape sequences that +* are a prefix of the string at start up to end. +*/ +size_t display_mode_esc_sequence_len_all (const char *start,const char *end) +{ +size_t seq_len =0 ; + +while (start + seq_len < end) { +size_t count =display_mode_esc_sequence_len (start + seq_len, end); + +if (!count) +break ; + + seq_len += count; + } + +return seq_len; +} +/* auxiliary function for binary search in interval table */ static int bisearch (ucs_char_t ucs,const struct interval *table,int max) {
@@ -227,8 +247,7 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)size_t remainder;if (skip_ansi) { -while ((skip =display_mode_esc_sequence_len (string, end))) - string += skip; + string +=display_mode_esc_sequence_len_all (string, end);if (string >= end)break ;
@@ -313,10 +332,8 @@ void strbuf_add_wrapped_text(struct strbuf *buf,for (;;) {char c; -size_t skip; -while ((skip =display_mode_esc_sequence_len (text, end))) - text += skip; + text +=display_mode_esc_sequence_len_all (text, end); c = *text;if (!c ||isspace (c)) {
@@ -394,10 +411,9 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,int glyph_width;size_t n; -while ((n =display_mode_esc_sequence_len (src, end))) { -strbuf_add (&dst, src, n); - src += n; - } + n =display_mode_esc_sequence_len_all (src, end); +strbuf_add (&dst, src, n); + src += n;if (src >= end)break ;
utf8.h +1 -0
@@ -6,6 +6,7 @@ struct strbuf;typedef unsigned int ucs_char_t ;/* assuming 32bit int */ size_t display_mode_esc_sequence_len (const char *start,const char *end); +size_t display_mode_esc_sequence_len_all (const char *start,const char *end);int utf8_width (const char **start,size_t *remainder_p);int utf8_strnwidth (const char *string,size_t len,int skip_ansi);int utf8_strwidth (const char *string);
Signature · 1 line
2.55.0
Re: [PATCH v4 0/5] utf8: bounds-related fixes and a doc fix
In reply to Dirk GoudersQuoted 11 lines · Dirk Gouders
A patch here on the list made me look at
display_mode_esc_sequence_len()inutf8.cand I found two details in the file that are perhaps worth a fix:1)
utf8_strnwidth()disregards the given len argument when fed with proper string and len.2) The comment for
utf8_strnwidth()is incorrect: it states the function returnsstrlen()for cases when it actually returns its len argument.
This no longer describes the series, which I think has become a bit unfocused. I'd concentrate on these:
- The comment fix.
- The optional end pointer for display_mode_esc_sequence_len(), and changing the callers accordingly.
- The end guard after the display_mode_esc_sequence_len() call and the bounded utf8_width() call in utf8_strnwidth().
display_mode_esc_sequence_len_all() isn't needed for the fixes, and I'm not sure it's worth adding.
As the series stands, patch 4/5 doesn't build, because skip is undeclared.
Regards,
Andy
Re: [PATCH v4 0/5] utf8: bounds-related fixes and a doc fix
Quoted 16 lines · Andy Koppe
Quoted 11 lines · Dirk Gouders
A patch here on the list made me look at
display_mode_esc_sequence_len()inutf8.cand I found two details in the file that are perhaps worth a fix:1)
utf8_strnwidth()disregards the given len argument when fed with proper string and len.2) The comment for
utf8_strnwidth()is incorrect: it states the function returnsstrlen()for cases when it actually returns its len argument.This no longer describes the series, which I think has become a bit unfocused. I'd concentrate on these:
Quoted 8 lines
- The comment fix.
- The optional end pointer fordisplay_mode_esc_sequence_len(), and changing the callers accordingly.
- The end guard after thedisplay_mode_esc_sequence_len()call and the boundedutf8_width()call inutf8_strnwidth().
display_mode_esc_sequence_len_all()isn't needed for the fixes, and I'm not sure it's worth adding.
Yes, I also think that is only noise and I already dropped it.
Quoted 2 lines
As the series stands, patch 4/5 doesn't build, because
skipis undeclared.
Thank you for testing. I noticed a mistake I was doing when resolving merge conflicts (and of course not test-compiling even after "trivial" changes). That should be fixed, now.
Dirk
v5 cover utf8: bounds-related fixes and a doc fix
In reply to Dirk GoudersA patch here on the list made me look at display_mode_esc_sequence_len() in utf8.c and I found two details in the file that are perhaps worth a fix:
1) utf8_strnwidth() disregards the given len argument when fed with proper string and len.
2) The comment for utf8_strnwidth() is incorrect: it states the function returns strlen() for cases when it actually returns its len argument.
---
Changes in v5:
This version moves back much closer to Junio's suggestion:
Keep Junio's functions but take care for the risk of O(n²) degradation. For NUL-terminated strings, do not calculate exact lengths with strlen(), but:
1. In the _counted variant, ensure we never calculate s + len but instead, we work with an array index to ensure it stays <= len and we never touch s[len] or beyond.
2. Because of 1. we can pass SIZE_MAX in the wrapper for NUL-terminated strings.
Further, I dropped 5/5 of v4. This series should stick with actually fixing issues and not introduce noise.
- 1/4: Change this back to Junio's suggestion and modify it to work with an array index.
I added more tests so that the wrapper function is tested, as well.
Arrays initialized with string constants are now used so that sizeof() can be used when testing the ends of such strings. Andy also reviewed that doing sizeof() on pointers is a bad idea.
- 2/4: "NUL-terminated" instead of "NUL terminated"
- 3/4: Back to display_mode_esc_sequence_len_counted()
- 4/4: Restore the variable "skip" according to Andy's review.
- Link to v4: https://patch.msgid.link/[email protected]
Changes in v4:
- Resend un-squashed v3
Changes in v3:
- 1/5: * fix sorting order in t/meson.build
* fix risk of O(n²) degradation:
drop the wrapper function and introduce an end pointer to display_mode_esc_sequence_len()
(I was so used to len arguments for string handling functions
that I only now realized the beauty of optionally optional end pointers for string handling. I know: beauty is in the eye of the beholder ;-))
* try to fix an overly long line
- 2/5: also fix a further error concerning "null-terminated"
- 3/5: * drop excess SP in if-statement
- 5/5: this actually is a POC, not fixing a bug:
users of display_mode_esc_sequence_len() often need the length of all leading SGR sequences and here is a function that does that. I mentioned such a function in the discussion for v1.
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Add a patch by Junio that introduces a bounded function display_mode_esc_sequence_len_counted() I added some tests for this new function.
- 2/2 became 2/4
- 3/4 is the modified 1/2 and uses the new display_mode_esc_sequence_len_counted() so that the while loop stays
within the given bounds.
The commit message was adjusted.
One of the tests was wrong: "\033" has width 0, so the sum must be 3 instead of 4.
- 4/4 is an addition to fix a similar problem with utf8_width().
That function is used without its optional bounds argument and
can violate boundaries as well. Test for such cases are added.
- Link to v1: https://patch.msgid.link/[email protected]
---
Dirk Gouders (3):
utf8: fix comment for utf8_strnwidth()
utf8: respect string boundaries after skipping ANSI escape sequences
utf8: respect boundaries in utf8_strnwidth()
Junio C Hamano (1):
utf8: add display_mode_esc_sequence_len_counted()
Makefile | 1 + t/meson.build | 1 + t/unit-tests/u-utf8-ansi.c | 86 +++++++++++++++++++++++++++++++++++++++++++++ t/unit-tests/u-utf8-width.c | 20 +++++++++++ utf8.c | 56 ++++++++++++++++++++--------- utf8.h | 1 + 6 files changed, 149 insertions(+), 16 deletions(-)
Range-diff versus v4:
1: 9d485b3d85 < -: ---------- utf8: introduce bounds for display_mode_esc_sequence_len() -: ---------- > 1: 1a45a2c68d utf8: add display_mode_esc_sequence_len_counted() 2: 804d6e33e2 ! 2: 8a39f7d1ef utf8: fix comment for utf8_strnwidth()
@@ Metadata
## Commit message ##
utf8: fix comment for utf8_strnwidth()
- The comment for utf8_strnwidth() states it works on a NUL terminated
+ The comment for utf8_strnwidth() states it works on a NUL-terminated
string whereas the string is bounded by len.
It also states it returns strlen() for cases when the given string
doesn't look like valid utf8, but it returns its argument len in such
3: 04779942c0 ! 3: c131754368 utf8: respect string boundaries after skipping ANSI escape sequences
@@ utf8.c: int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
size_t skip;
- while (skip_ansi &&
-- (skip = display_mode_esc_sequence_len(string, end)))
+- (skip = display_mode_esc_sequence_len_counted(string,
+- orig + len - string)) != 0)
- string += skip;
+ if (skip_ansi) {
-+ while ((skip = display_mode_esc_sequence_len(string, end)))
++ while ((skip = display_mode_esc_sequence_len_counted(string,
++ orig + len - string)))
+ string += skip;
+
-+ if (string >= end)
++ if (string >= orig + len)
+ break;
+ }4: dad74fb874 ! 4: a64dbf4eeb utf8: respect boundaries in utf8_strnwidth()
@@ t/unit-tests/u-utf8-width.c
## utf8.c ##
@@ utf8.c: int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
-
- while (string && string < end) {
+ while (string && string < orig + len) {
int glyph_width;
-- size_t skip;
+ size_t skip;
+ size_t remainder;
if (skip_ansi) {
- while ((skip = display_mode_esc_sequence_len(string, end)))
+ while ((skip = display_mode_esc_sequence_len_counted(string,
@@ utf8.c: int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
break;
}
- glyph_width = utf8_width(&string, NULL);
-+ remainder = end - string;
++ remainder = orig + len - string;
+
+ glyph_width = utf8_width(&string, &remainder);
if (glyph_width > 0)5: 1a3fc65005 < -: ---------- utf8: introduce display_mode_esc_sequence_len_all()
---
base-commit: f7de81456940dd6f3274e461149bba12965de609
change-id: 20261116-master-69b171612823
PATCH v5 1/4 utf8: add display_mode_esc_sequence_len_counted()
From: Junio C Hamano <[email protected]>
display_mode_esc_sequence_len() scans for an ANSI display mode escape sequence (e.g. "ESC [ 1 ; 31 m") at the start of a string, relying on NUL termination to stop. Some callers, however, work on a counted buffer: utf8_strnwidth() takes <string, len> and must not scan past it, while strbuf_utf8_replace() and strbuf_add_wrapped_text() know (or can cheaply learn) the end.
Add display_mode_esc_sequence_len_counted() taking <ptr, len>, which never reads at or beyond ptr[len], and make display_mode_esc_sequence_len() a thin wrapper for NUL-terminated strings.
Use the counted variant in utf8_strnwidth() for correctness, and in strbuf_utf8_replace() and strbuf_add_wrapped_text() (computing the end once upfront in the latter) to avoid measuring the remaining text in each iteration.
[Dirk Gouders: allow SIZE_MAX to be passed for NUL-terminated strings
to avoid O(n²) degradation as suggested by Andy Koppe. Also add tests for these functions.]
--- Makefile | 1 + t/meson.build | 1 + t/unit-tests/u-utf8-ansi.c | 86 ++++++++++++++++++++++++++++++++++++++++++++++ utf8.c | 39 +++++++++++++++------ utf8.h | 1 + 5 files changed, 117 insertions(+), 11 deletions(-)
Makefile +1 -0
@@ -1563,6 +1563,7 @@ CLAR_TEST_SUITES += u-string-list CLAR_TEST_SUITES += u-strvec CLAR_TEST_SUITES += u-trailer CLAR_TEST_SUITES += u-urlmatch-normalization +CLAR_TEST_SUITES += u-utf8-ansi CLAR_TEST_SUITES += u-utf8-width CLAR_TEST_PROG = $(UNIT_TEST_BIN)/unit-tests$(X) CLAR_TEST_OBJS = $(patsubst %,$(UNIT_TEST_DIR)/%.o,$(CLAR_TEST_SUITES))
t/meson.build +1 -0
@@ -26,6 +26,7 @@ clar_test_suites = [ 'unit-tests/u-strvec.c', 'unit-tests/u-trailer.c', 'unit-tests/u-urlmatch-normalization.c', + 'unit-tests/u-utf8-ansi.c', 'unit-tests/u-utf8-width.c', ]
t/unit-tests/u-utf8-ansi.c new file +86 -0
86 lines not on this page · raw message
utf8.c +28 -11
@@ -16,18 +16,31 @@ struct interval {ucs_char_t last; }; -size_t display_mode_esc_sequence_len (const char *s) +/* +* Return the length of the ANSI display mode escape sequence (e.g., +* "\033[1;31m") that appears at the beginning of the "len" bytes +* of string "s", or 0 if the bytes do not begin with a complete +* such sequence. Never looks at s[len] or beyond. +*/ +size_t display_mode_esc_sequence_len_counted (const char *s,size_t len) { -const char *p = s; -if (*p++ !='\033' ) +size_t i =0 ; + +if (i >= len || s[i++] !='\033' )return 0 ; -if (*p++ !='[' ) +if (i >= len || s[i++] !='[' )return 0 ; -while (isdigit (*p) || *p ==';' ) - p++; -if (*p++ !='m' ) +while (i < len && (isdigit (s[i]) || s[i] ==';' )) + i++; +if (i >= len || s[i++] !='m' )return 0 ; -return p - s; +return i; +} + +/* Same as above, but for a NUL-terminated string "s". */ +size_t display_mode_esc_sequence_len (const char *s) +{ +return display_mode_esc_sequence_len_counted (s,SIZE_MAX ); }/* auxiliary function for binary search in interval table */
@@ -218,7 +231,8 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)size_t skip;while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) + (skip =display_mode_esc_sequence_len_counted (string, + orig + len - string)) !=0 ) string += skip; glyph_width =utf8_width (&string,NULL );
@@ -279,6 +293,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf, {int indent, w, assume_utf8 =1 ;const char *bol, *space, *start = text; +const char *end = text +strlen (text);size_t orig_len = buf->len;if (width <=0 ) {
@@ -299,7 +314,8 @@ void strbuf_add_wrapped_text(struct strbuf *buf,char c;size_t skip; -while ((skip =display_mode_esc_sequence_len (text))) +while ((skip =display_mode_esc_sequence_len_counted (text, + end - text))) text += skip; c = *text;
@@ -378,7 +394,8 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,int glyph_width;size_t n; -while ((n =display_mode_esc_sequence_len (src))) { +while ((n =display_mode_esc_sequence_len_counted (src, + end - src))) {strbuf_add (&dst, src, n); src += n; }
utf8.h +1 -0
@@ -6,6 +6,7 @@ struct strbuf;typedef unsigned int ucs_char_t ;/* assuming 32bit int */ size_t display_mode_esc_sequence_len (const char *s); +size_t display_mode_esc_sequence_len_counted (const char *s,size_t len);int utf8_width (const char **start,size_t *remainder_p);int utf8_strnwidth (const char *string,size_t len,int skip_ansi);int utf8_strwidth (const char *string);
Signature · 1 line
2.55.0
Re: [PATCH v5 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 9 lines · Dirk Gouders
From: Junio C Hamano <[email protected]>
display_mode_esc_sequence_len()scans for an ANSI display mode escape sequence (e.g. "ESC [ 1 ; 31 m") at the start of a string, relying on NUL termination to stop. Some callers, however, work on a counted buffer:utf8_strnwidth()takes <string, len> and must not scan past it, whilestrbuf_utf8_replace()andstrbuf_add_wrapped_text()know (or can cheaply learn) the end.
Quoted 4 lines
Add
display_mode_esc_sequence_len_counted()taking <ptr, len>, which never reads at or beyond ptr[len], and makedisplay_mode_esc_sequence_len()a thin wrapper for NUL-terminated strings.
Good.
Quoted 4 lines
Use the counted variant in
utf8_strnwidth()for correctness, and instrbuf_utf8_replace()andstrbuf_add_wrapped_text()(computing the end once upfront in the latter) to avoid measuring the remaining text in each iteration.
OK, but the latter needs a slight fix (see below).
Quoted 7 lines
[Dirk Gouders: allow
SIZE_MAXto be passed for NUL-terminated strings
to avoid O(n²) degradation as suggested by Andy Koppe. Also add tests for these functions.]Helped-by Andy Koppe <[email protected]>Signed-off-by Junio C Hamano <[email protected]>Signed-off-by Dirk Gouders <[email protected]>
Minor nit. These ought to be a chronological record of custodial chain. The original author's sign-off comes first, then Helped-by and [note on the help in square brackets], and finally the sign-off of person who is relaying the final package.
t/unit-tests/u-utf8-ansi.c line 3
Quoted 9 lines
t/unit-tests/u-utf8-ansi.c new file +3
-0@@ -0,0 +1,86 @@ +#include "unit-test.h" +#include "utf8.h" +#include "strbuf.h"
Do we use <strbuf.h> at this stage? I do not think so (and <unit-test.h> includes it anyway).
t/unit-tests/u-utf8-ansi.c line 27
Quoted 11 lines
t/unit-tests/u-utf8-ansi.c new file +11
-0+ +/* +* Test display_mode_esc_sequence_len_counted() for NUL-terminated strings. +*/ +void test_utf8_ansi__sgr_len_counted (void ) +{ +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_counted ("" ,SIZE_MAX )); + +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_counted ("\033" ,SIZE_MAX )); +... +cl_assert_equal_i (7 ,display_mode_esc_sequence_len_counted ("\033[31;0ma" ,SIZE_MAX ));
It is sad that these lines have to become this long.
As the values returned from display_mode_esc_sequence_len_counted() and friends are all size_t, not signed, cl_assert_equal_u() would be a much more appropriate assertion here.
See how t/unit-tests/u-odb-inmemory.c:cl_assert_object_info() nearby uses it to check values of type size_t.
t/unit-tests/u-utf8-ansi.c line 16
Quoted 2 lines
t/unit-tests/u-utf8-ansi.c new file +2
-0+/* +* Test display_mode_esc_sequence_len_counted() with end pointers.
Probably with "length limits" instead of "end pointers" in this iteration.
Quoted 23 lines
utf8.c +10
-3@@ -16,18 +16,31 @@ struct interval {ucs_char_t last; }; -size_t display_mode_esc_sequence_len (const char *s) +/* +* Return the length of the ANSI display mode escape sequence (e.g., +* "\033[1;31m") that appears at the beginning of the "len" bytes +* of string "s", or 0 if the bytes do not begin with a complete +* such sequence. Never looks at s[len] or beyond. +*/ +size_t display_mode_esc_sequence_len_counted (const char *s,size_t len) { -const char *p = s; -if (*p++ !='\033' ) +size_t i =0 ; + +if (i >= len || s[i++] !='\033' )return 0 ;
utf8.c struct interval { · line 36
Quoted 10 lines
utf8.c +4
-4-if (*p++ !='[' ) +if (i >= len || s[i++] !='[' )return 0 ; -while (isdigit (*p) || *p ==';' ) - p++; -if (*p++ !='m' ) +while (i < len && (isdigit (s[i]) || s[i] ==';' )) + i++; +if (i >= len || s[i++] !='m' )return 0 ;
Among 4 comparisons between i and len, only one of them follow the "textual order reflects actual order" principle. Can we revert it back to the version I gave you to compare (len <= i) instead, if we allow the commit to claim to be from me, as I wouldn't write (i >= len) in these places if I were writing this patch myself.
Quoted 15 lines
utf8.c +4
-1+return i; +}/* auxiliary function for binary search in interval table */ @@ -218,7 +231,8 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)size_t skip;while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) + (skip =display_mode_esc_sequence_len_counted (string, + orig + len - string)) !=0 ) string += skip; glyph_width =utf8_width (&string,NULL );
utf8.c void strbuf_add_wrapped_text(struct strbuf *buf, · line 296
Quoted 4 lines
utf8.c +1
-0@@ -279,6 +293,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf, {int indent, w, assume_utf8 =1 ;const char *bol, *space, *start = text; +const char *end = text +strlen (text);
This strlen() call is unconditionally made, even before the check to see if we divert to strbuf_add_indented_text() with "if (width <= 0)"; measuring the length of text in that code path is wasted.
utf8.c void strbuf_add_wrapped_text(struct strbuf *buf, · line 319
Quoted 11 lines
utf8.c +2
-1size_t orig_len = buf->len;if (width <=0 ) {@@ -299,7 +314,8 @@ void strbuf_add_wrapped_text(struct strbuf *buf,char c;size_t skip; -while ((skip =display_mode_esc_sequence_len (text))) +while ((skip =display_mode_esc_sequence_len_counted (text, + end - text))) text += skip;
OK, I guess.
It is a bit sad that we cannot use the trick similar to passing SIZE_MAX to avoid having to prescan to find "end", though.
Quoted 23 lines
utf8.c +2
-1c = *text;@@ -378,7 +394,8 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,int glyph_width;size_t n; -while ((n =display_mode_esc_sequence_len (src))) { +while ((n =display_mode_esc_sequence_len_counted (src, + end - src))) {strbuf_add (&dst, src, n); src += n; }utf8.h +1
-0@@ -6,6 +6,7 @@ struct strbuf;typedef unsigned int ucs_char_t ;/* assuming 32bit int */ size_t display_mode_esc_sequence_len (const char *s); +size_t display_mode_esc_sequence_len_counted (const char *s,size_t len);int utf8_width (const char **start,size_t *remainder_p);int utf8_strnwidth (const char *string,size_t len,int skip_ansi);int utf8_strwidth (const char *string);
Re: [PATCH v5 1/4] utf8: add display_mode_esc_sequence_len_counted()
Quoted 29 lines · Junio C Hamano
Quoted 9 lines · Dirk Gouders
From: Junio C Hamano <[email protected]>
display_mode_esc_sequence_len()scans for an ANSI display mode escape sequence (e.g. "ESC [ 1 ; 31 m") at the start of a string, relying on NUL termination to stop. Some callers, however, work on a counted buffer:utf8_strnwidth()takes <string, len> and must not scan past it, whilestrbuf_utf8_replace()andstrbuf_add_wrapped_text()know (or can cheaply learn) the end.Quoted 4 lines
Add
display_mode_esc_sequence_len_counted()taking <ptr, len>, which never reads at or beyond ptr[len], and makedisplay_mode_esc_sequence_len()a thin wrapper for NUL-terminated strings.Good.
Quoted 4 lines
Use the counted variant in
utf8_strnwidth()for correctness, and instrbuf_utf8_replace()andstrbuf_add_wrapped_text()(computing the end once upfront in the latter) to avoid measuring the remaining text in each iteration.OK, but the latter needs a slight fix (see below).
Quoted 4 lines
[Dirk Gouders: allow
SIZE_MAXto be passed for NUL-terminated strings
to avoid O(n²) degradation as suggested by Andy Koppe. Also add tests for these functions.]
Quoted 8 lines
Quoted 3 lines
Helped-by Andy Koppe <[email protected]>Signed-off-by Junio C Hamano <[email protected]>Signed-off-by Dirk Gouders <[email protected]>Minor nit. These ought to be a chronological record of custodial chain. The original author's sign-off comes first, then Helped-by and [note on the help in square brackets], and finally the sign-off of person who is relaying the final package.
OK, I will search for an example in the log.
Quoted 13 lines
t/unit-tests/u-utf8-ansi.c line 3
Quoted 9 lines
t/unit-tests/u-utf8-ansi.c new file +3
-0@@ -0,0 +1,86 @@ +#include "unit-test.h" +#include "utf8.h" +#include "strbuf.h" Do we use <
strbuf.h> at this stage? I do not think so (and <unit-test.h> includes it anyway).
Quoted 13 lines
t/unit-tests/u-utf8-ansi.c line 14
Quoted 11 lines
t/unit-tests/u-utf8-ansi.c new file +11
-0+ +/* +* Test display_mode_esc_sequence_len_counted() for NUL-terminated strings. +*/ +void test_utf8_ansi__sgr_len_counted (void ) +{ +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_counted ("" ,SIZE_MAX )); + +cl_assert_equal_i (0 ,display_mode_esc_sequence_len_counted ("\033" ,SIZE_MAX )); +... +cl_assert_equal_i (7 ,display_mode_esc_sequence_len_counted ("\033[31;0ma" ,SIZE_MAX ));It is sad that these lines have to become this long.
Two possible ways to make it prettier (in my eyes) would be to #1 rename the function or #2 do something like:
t/unit-tests/u-utf8-ansi.c +8 -5
@@ -5,26 +5,29 @@/* * Test display_mode_esc_sequence_len_counted() for NUL-terminated strings. */ +size_t (*test_function)(const char *,size_t ) = + display_mode_esc_sequence_len_counted; +void test_utf8_ansi__sgr_len_counted (void ) { -cl_assert_equal_i (0 ,display_mode_esc_sequence_len_counted ("" ,SIZE_MAX )); +cl_assert_equal_i (0 ,test_function ("" ,SIZE_MAX )); -cl_assert_equal_i (0 ,display_mode_esc_sequence_len_counted ("\033" ,SIZE_MAX )); -cl_assert_equal_i (0 ,display_mode_esc_sequence_len_counted ("\033[" ,SIZE_MAX )); -cl_assert_equal_i (3 ,display_mode_esc_sequence_len_counted ("\033[m" ,SIZE_MAX )); -cl_assert_equal_i (3 ,display_mode_esc_sequence_len_counted ("\033[ma" ,SIZE_MAX )); +cl_assert_equal_i (0 ,test_function ("\033" ,SIZE_MAX )); +cl_assert_equal_i (0 ,test_function ("\033[" ,SIZE_MAX )); +cl_assert_equal_i (3 ,test_function ("\033[m" ,SIZE_MAX )); +cl_assert_equal_i (3 ,test_function ("\033[ma" ,SIZE_MAX ));
...
Quoted 91 lines
As the values returned from
display_mode_esc_sequence_len_counted()and friends are allsize_t, not signed,cl_assert_equal_u()would be a much more appropriate assertion here.See how t/unit-tests/u-odb-inmemory.c:cl_assert_object_info() nearby uses it to check values of type
size_t.Quoted 2 lines
+/*
+ * Testdisplay_mode_esc_sequence_len_counted()with end pointers.Probably with "length limits" instead of "end pointers" in this iteration.
Quoted 23 lines
utf8.c +10
-3@@ -16,18 +16,31 @@ struct interval {ucs_char_t last; }; -size_t display_mode_esc_sequence_len (const char *s) +/* +* Return the length of the ANSI display mode escape sequence (e.g., +* "\033[1;31m") that appears at the beginning of the "len" bytes +* of string "s", or 0 if the bytes do not begin with a complete +* such sequence. Never looks at s[len] or beyond. +*/ +size_t display_mode_esc_sequence_len_counted (const char *s,size_t len) { -const char *p = s; -if (*p++ !='\033' ) +size_t i =0 ; + +if (i >= len || s[i++] !='\033' )return 0 ;utf8.c struct interval { · line 36
Quoted 10 lines
utf8.c +4
-4-if (*p++ !='[' ) +if (i >= len || s[i++] !='[' )return 0 ; -while (isdigit (*p) || *p ==';' ) - p++; -if (*p++ !='m' ) +while (i < len && (isdigit (s[i]) || s[i] ==';' )) + i++; +if (i >= len || s[i++] !='m' )return 0 ;Among 4 comparisons between i and len, only one of them follow the "textual order reflects actual order" principle. Can we revert it back to the version I gave you to compare (len <= i) instead, if we allow the commit to claim to be from me, as I wouldn't write (i >= len) in these places if I were writing this patch myself.
Quoted 15 lines
utf8.c +4
-1+return i; +}/* auxiliary function for binary search in interval table */ @@ -218,7 +231,8 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)size_t skip;while (skip_ansi && - (skip =display_mode_esc_sequence_len (string)) !=0 ) + (skip =display_mode_esc_sequence_len_counted (string, + orig + len - string)) !=0 ) string += skip; glyph_width =utf8_width (&string,NULL );utf8.c void strbuf_add_wrapped_text(struct strbuf *buf, · line 296
Quoted 4 lines
utf8.c +1
-0@@ -279,6 +293,7 @@ void strbuf_add_wrapped_text(struct strbuf *buf, {int indent, w, assume_utf8 =1 ;const char *bol, *space, *start = text; +const char *end = text +strlen (text);This
strlen()call is unconditionally made, even before the check to see if we divert tostrbuf_add_indented_text()with "if (width <= 0)"; measuring the length of text in that code path is wasted.utf8.c void strbuf_add_wrapped_text(struct strbuf *buf, · line 319
Quoted 11 lines
utf8.c +2
-1size_t orig_len = buf->len;if (width <=0 ) {@@ -299,7 +314,8 @@ void strbuf_add_wrapped_text(struct strbuf *buf,char c;size_t skip; -while ((skip =display_mode_esc_sequence_len (text))) +while ((skip =display_mode_esc_sequence_len_counted (text, + end - text))) text += skip;OK, I guess.
Quoted 2 lines
It is a bit sad that we cannot use the trick similar to passing
SIZE_MAXto avoid having to prescan to find "end", though.
Now that you mention it: if we can do strlen(text) then we can avoid the _counted variant. I have to test it but I'm pretty sure.
Dirk
Quoted 23 lines
Quoted 23 lines
utf8.c +2
-1c = *text;@@ -378,7 +394,8 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,int glyph_width;size_t n; -while ((n =display_mode_esc_sequence_len (src))) { +while ((n =display_mode_esc_sequence_len_counted (src, + end - src))) {strbuf_add (&dst, src, n); src += n; }utf8.h +1
-0@@ -6,6 +6,7 @@ struct strbuf;typedef unsigned int ucs_char_t ;/* assuming 32bit int */ size_t display_mode_esc_sequence_len (const char *s); +size_t display_mode_esc_sequence_len_counted (const char *s,size_t len);int utf8_width (const char **start,size_t *remainder_p);int utf8_strnwidth (const char *string,size_t len,int skip_ansi);int utf8_strwidth (const char *string);
PATCH v5 2/4 utf8: fix comment for utf8_strnwidth()
In reply to Dirk GoudersThe comment for utf8_strnwidth() states it works on a NUL-terminated string whereas the string is bounded by len.
It also states it returns strlen() for cases when the given string doesn't look like valid utf8, but it returns its argument len in such cases.
Fix the comment accordingly.
--- utf8.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
utf8.c +2 -2
@@ -217,8 +217,8 @@ int utf8_width(const char **start, size_t *remainder_p) }/* -* Returns the total number of columns required by a null-terminated -* string, assuming that the string is utf8. Returns strlen() instead +* Returns the total number of columns required by a string terminated by len, +* assuming that the string is utf8. Returns len instead * if the string does not look like a valid utf8 string. */ int utf8_strnwidth (const char *string,size_t len,int skip_ansi)
Signature · 1 line
2.55.0
Re: [PATCH v5 2/4] utf8: fix comment for utf8_strnwidth()
Quoted 10 lines · Dirk Gouders
The comment for
utf8_strnwidth()states it works on a NUL-terminated string whereas the string is bounded by len.
It also states it returnsstrlen()for cases when the given string doesn't look like valid utf8, but it returns its argument len in such cases.
...
- * Returns the total number of columns required by a null-terminated
- * string, assuming that the string is utf8. Returnsstrlen()instead
+ * Returns the total number of columns required by a string terminated by len,
+ * assuming that the string is utf8. Returns len instead
"terminated" -> "bounded" (the proposed log message above uses the verb, and it sounds much less awkward), perhaps?
Other than that, looking good.
PATCH v5 3/4 utf8: respect string boundaries after skipping ANSI escape sequences
In reply to Dirk Goudersutf8_strnwidth() can skip ANSI escape sequences and it is possible that such sequences end the string within the given boundary.
Check for such situations before proceeding and calling utf8_width().
Add tests that test such corner cases.
--- t/unit-tests/u-utf8-width.c | 11 +++++++++++ utf8.c | 12 ++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-)
t/unit-tests/u-utf8-width.c +11 -0
@@ -2,6 +2,17 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for strings with SGR sequences and corner case length +* arguments. +*/ +void test_utf8_width__strnwidth_ansi (void ) +{ +cl_assert_equal_i (3 ,utf8_strnwidth ("\033[31mhello" ,4 ,1 )); +cl_assert_equal_i (0 ,utf8_strnwidth ("\033[31mhello" ,5 ,1 )); +cl_assert_equal_i (1 ,utf8_strnwidth ("\033[31mhello" ,6 ,1 )); +} +/* * Test utf8_strnwidth with various Chinese strings * Chinese characters typically have a width of 2 columns when displayed
utf8.c +8 -4
@@ -230,10 +230,14 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)int glyph_width;size_t skip; -while (skip_ansi && - (skip =display_mode_esc_sequence_len_counted (string, - orig + len - string)) !=0 ) - string += skip; +if (skip_ansi) { +while ((skip =display_mode_esc_sequence_len_counted (string, + orig + len - string))) + string += skip; + +if (string >= orig + len) +break ; + } glyph_width =utf8_width (&string,NULL );if (glyph_width >0 )
Signature · 1 line
2.55.0
Re: [PATCH v5 3/4] utf8: respect string boundaries after skipping ANSI escape sequences
Quoted 6 lines · Dirk Gouders
utf8_strnwidth()can skip ANSI escape sequences and it is possible that such sequences end the string within the given boundary.Check for such situations before proceeding and calling
utf8_width().Add tests that test such corner cases.
It would become clearer if the above described externally observable symptom and the condition to trigger it.
"such sequences end the string within the given boundary" is slightly imprecise, isn't it? IIUC, the problem is that an escape sequence reaching orig + len would cause utf8_width() to read past len, which leads it to count extra columns or reading out-of-bounds memory.
The code change looks correct, though ;-)
Quoted 8 lines
t/unit-tests/u-utf8-width.c +0
-0@@ -2,6 +2,17 @@#include "utf8.h" #include "strbuf.h"
t/unit-tests/u-utf8-width.c line 14
Quoted 10 lines
t/unit-tests/u-utf8-width.c +10
-0+/* +* Test utf8_strnwidth for strings with SGR sequences and corner case length +* arguments. +*/ +void test_utf8_width__strnwidth_ansi (void ) +{ +cl_assert_equal_i (3 ,utf8_strnwidth ("\033[31mhello" ,4 ,1 )); +cl_assert_equal_i (0 ,utf8_strnwidth ("\033[31mhello" ,5 ,1 )); +cl_assert_equal_i (1 ,utf8_strnwidth ("\033[31mhello" ,6 ,1 )); +}
These are OK to be equal_i() for now, but I notice a TODO at the bottom of utf8_strnwidth(). It might be helpful to leave a comment to warn that this test needs to be updated when it happens?
Quoted 10 lines
utf8.c +0
-2@@ -230,10 +230,14 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)int glyph_width;size_t skip; - while (skip_ansi && - (skip = display_mode_esc_sequence_len_counted(string,
utf8.c int utf8_strnwidth(const char *string, size_t len, int skip_ansi) · line 240
Quoted 10 lines
utf8.c +8
-2- orig + len - string)) != 0) - string += skip; +if (skip_ansi) { +while ((skip =display_mode_esc_sequence_len_counted (string, + orig + len - string))) + string += skip; + +if (string >= orig + len) +break ; + }
Thanks.
Re: [PATCH v5 3/4] utf8: respect string boundaries after skipping ANSI escape sequences
Quoted 9 lines · Junio C Hamano
Quoted 6 lines · Dirk Gouders
utf8_strnwidth()can skip ANSI escape sequences and it is possible that such sequences end the string within the given boundary.Check for such situations before proceeding and calling
utf8_width().Add tests that test such corner cases.
Quoted 7 lines
It would become clearer if the above described externally observable symptom and the condition to trigger it.
"such sequences end the string within the given boundary" is slightly imprecise, isn't it? IIUC, the problem is that an escape sequence reaching orig + len would cause
utf8_width()to read past len, which leads it to count extra columns or reading out-of-bounds memory.
Yes, even for the one who observed this it can be difficult to reconstruct the needed imaginary after a few days.
I will try to provide an example.
Quoted 10 lines
The code change looks correct, though ;-)
Quoted 8 lines
t/unit-tests/u-utf8-width.c +0
-0@@ -2,6 +2,17 @@#include "utf8.h" #include "strbuf.h"
Quoted 14 lines
t/unit-tests/u-utf8-width.c line 14
Quoted 10 lines
t/unit-tests/u-utf8-width.c +10
-0+/* +* Test utf8_strnwidth for strings with SGR sequences and corner case length +* arguments. +*/ +void test_utf8_width__strnwidth_ansi (void ) +{ +cl_assert_equal_i (3 ,utf8_strnwidth ("\033[31mhello" ,4 ,1 )); +cl_assert_equal_i (0 ,utf8_strnwidth ("\033[31mhello" ,5 ,1 )); +cl_assert_equal_i (1 ,utf8_strnwidth ("\033[31mhello" ,6 ,1 )); +}These are OK to be
equal_i()for now, but I notice a TODO at the bottom ofutf8_strnwidth(). It might be helpful to leave a comment to warn that this test needs to be updated when it happens?
Ok, I will leave a similar comment.
I also noticed the comment and started an .org file to note what the callers (and theirs ...) do with the return values and what changes are needed. In quite some case those int's end as widths specifiers in format strings and I concluded I'd better stay away from this task.
Quoted 22 lines
Quoted 10 lines
utf8.c +0
-2@@ -230,10 +230,14 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)int glyph_width;size_t skip; - while (skip_ansi && - (skip = display_mode_esc_sequence_len_counted(string,utf8.c int utf8_strnwidth(const char *string, size_t len, int skip_ansi) · line 240
Quoted 10 lines
utf8.c +8
-2- orig + len - string)) != 0) - string += skip; +if (skip_ansi) { +while ((skip =display_mode_esc_sequence_len_counted (string, + orig + len - string))) + string += skip; + +if (string >= orig + len) +break ; + }Thanks.
PATCH v5 4/4 utf8: respect boundaries in utf8_strnwidth()
In reply to Dirk Goudersutf8_strnwidth() can be called with boundaries that effectively cause incomplete multibyte sequences and we should return "len" in such cases.
But, utf8_width is used without its optional boundary argument and will thus work beyond the given boundary.
Fix this by using the boundary argument for utf8_width. Add some tests that cover such situations.
--- t/unit-tests/u-utf8-width.c | 9 +++++++++ utf8.c | 5 ++++- 2 files changed, 13 insertions(+), 1 deletion(-)
t/unit-tests/u-utf8-width.c +9 -0
@@ -2,6 +2,15 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for cjk characters invalidated by len argument. +*/ +void test_utf8_width__strnwidth_cjk_chopped (void ) +{ +cl_assert_equal_i (1 ,utf8_strnwidth ("三bytes long, 二columns wide" ,1 ,1 )); +cl_assert_equal_i (2 ,utf8_strnwidth ("三bytes long, 二columns wide" ,3 ,1 )); +} +/* * Test utf8_strnwidth for strings with SGR sequences and corner case length * arguments.
utf8.c +4 -1
@@ -229,6 +229,7 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi) while (string && string < orig + len) { int glyph_width; size_t skip; + size_t remainder; if (skip_ansi) { while ((skip = display_mode_esc_sequence_len_counted(string,
@@ -239,7 +240,9 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)break ; } - glyph_width =utf8_width (&string,NULL ); + remainder = orig + len - string; + + glyph_width =utf8_width (&string, &remainder);if (glyph_width >0 ) width += glyph_width; }
Signature · 1 line
2.55.0
Re: [PATCH v5 4/4] utf8: respect boundaries in utf8_strnwidth()
Quoted 1 line · Dirk Gouders
Subject: Re: [PATCH v5 4/4] utf8: respect boundaries in
utf8_strnwidth()
Micronit. I recall 3/4 was also making utf8_strnwidth() respect boundaries. Can we tighten the title to be a bit more specific to what this patch does, e.g., utf8: bound utf8_width() calls in utf8_strnwidth() or somtheing?
Quoted 9 lines
utf8_strnwidth()can be called with boundaries that effectively cause incomplete multibyte sequences and we should return "len" in such cases.But,
utf8_widthis used without its optional boundary argument and will thus work beyond the given boundary.Fix this by using the boundary argument for
utf8_width. Add some tests that cover such situations.
If you follow the convention to mark functions with () suffix, consistently do so also for utf8_width(). It is a very good change to make sure that the called utf8_width() will not read beyond the known end-of-region the caller has.
Quoted 49 lines
Signed-off-by Dirk Gouders <[email protected]>--- t/unit-tests/u-utf8-width.c | 9 +++++++++ utf8.c | 5 ++++- 2 files changed, 13 insertions(+), 1 deletion(-)t/unit-tests/u-utf8-width.c +9
-0@@ -2,6 +2,15 @@#include "utf8.h" #include "strbuf.h" +/* +* Test utf8_strnwidth for cjk characters invalidated by len argument. +*/ +void test_utf8_width__strnwidth_cjk_chopped (void ) +{ +cl_assert_equal_i (1 ,utf8_strnwidth ("三bytes long, 二columns wide" ,1 ,1 )); +cl_assert_equal_i (2 ,utf8_strnwidth ("三bytes long, 二columns wide" ,3 ,1 )); +} +/* * Test utf8_strnwidth for strings with SGR sequences and corner case length * arguments. utf8.c +4
-1@@ -229,6 +229,7 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi) while (string && string < orig + len) { int glyph_width; size_t skip; + size_t remainder; if (skip_ansi) { while ((skip = display_mode_esc_sequence_len_counted(string,@@ -239,7 +240,9 @@ int utf8_strnwidth(const char *string, size_t len, int skip_ansi)break ; } - glyph_width =utf8_width (&string,NULL ); + remainder = orig + len - string; + + glyph_width =utf8_width (&string, &remainder);if (glyph_width >0 ) width += glyph_width; }
Re: [PATCH v5 0/4] utf8: bounds-related fixes and a doc fix
In reply to Dirk GoudersQuoted 4 lines · Dirk Gouders
A patch here on the list made me look at
display_mode_esc_sequence_len()inutf8.cand I found two details in the file that are perhaps worth a fix:
Quoted 8 lines
1)
utf8_strnwidth()disregards the given len argument when fed with proper string and len.2) The comment for
utf8_strnwidth()is incorrect: it states the function returnsstrlen()for cases when it actually returns its len argument.Signed-off-by Dirk Gouders <[email protected]>
I had pointed out a few issues, but other than them the series looks in a very good shape. I can see we are getting closer to the finish line.
Thanks for working on this.