Skip to content
Tcl Source Code View Ticket
Login

View Ticket

Tcl_UtfPrev flaws

Closed / Fixedc61818e4c9b710bdf9f947c1a40563aeab85357aCreated 7 years agoUpdated 7 years ago
Descriptionplain2020-04-06 20:40:11
Demo script:

interp alias {} bytes {} encoding convertfrom identity
set demo [bytes foo\xc0\x80\x88]
set map [list \u0000 U \x88 V [bytes \x88] W]
puts "Tcl [package present Tcl]"
puts [string map $map $demo]
puts [string map $map [string trimright $demo x]]

Outputs:

Tcl 8.5.9
fooUW
fooUW

Tcl 8.5.10
fooUW
fooU

Blame the rewrite in checkin

https://core.tcl-lang.org/tcl/info/c48b1de113
Referenced by11
  • 859648c476Open ticket [debd088e48]: llength split is different from string length plus 3 other changes ticket2021-02-12 14:05:22
  • 4227206dc3Apply first fix of [c61818e4c9] and adjust tests. check-in2020-04-20 04:40:38
  • b8f4831925We know the Tcl 8.5.19 suffers from [c61818e4c9] where Tcl_UtfPrev uncritically accepts all bytes >= 0xC0 as valid lead bytes and makes no check in the number of trail bytes. check-in2020-04-19 23:12:02
  • 4b26bc65dcAdd test-case for bug [c61818e4c9] check-in2020-04-14 11:59:02
  • 6f0a816449[c61818e4c9] Fix regression in Tcl_UtfPrev from 2001. Many tests. check-in2020-04-13 19:45:49
  • d15a2b241e[c61818e4c9] [string trimright] robustly handle backing up over incomplete or malformed byte sequences. check-in2020-04-13 02:28:24
  • aa03cde0d2added test case covering [c61818e4c9] - string trim for not valid utf-8 sequence (mistakenly considers NTS-zero char as a continuation of utf-8 pair) check-in2020-04-13 00:09:43
  • e8bfb4c2bafixes [c61818e4c9] for all variants of string trim check-in2020-04-07 20:05:24
  • 325ac81dd2added test case covering [c61818e4c9] - string trim for not valid utf-8 sequence (mistakenly considers NTS-zero char as a continuation of utf-8 pair) check-in2020-04-07 20:04:25
  • 27fc84ab98Set of tests demonstrating flaws in Tcl_UtfPrev (as viewed through a fragile implementation of [string trimright]). See ticket [c61818e4c9]. check-in2020-04-07 19:36:54
  • 6d7a13ed20closes regression in string trimright [c61818e4c9] without modifying of Tcl_UtfPrev (so certain inconsistency by Tcl_UtfPrev/TclUtfToUniChar still remains) check-in2020-04-07 18:27:20
dgpplain2020-04-06 21:10:11
The two implementations fail differently, but they both fail for the same reason.
Change the last command to:

puts [string map $map [string trimright $demo \u0000]]

Tcl 8.5.9
fooUW
fooÀ

Tcl 8.5.10
fooUW
foo
dgpplain2020-04-06 21:13:45
Both implementations presume that the routines

p = Tcl_UtfPrev(p, bytes);

p += TclUtfToUniChar(p, &ch);

are inverses and take p back where it started. That is not true.

Tcl_UtfPrev appears to be buggy handling nonconformant bytes
like those in this demo, though it is hard to say because it is diffcult
to untangle the docs and comments to decide just what Tcl_UtfPrev
claims to be doing.
dgpplain2020-04-06 21:20:49
Callers appear to assume that when src == start,

Tcl_UtfPrev(src, start)

will return start, and otherwise it will return the latest pointer in the
range [start, src -1] that Tcl will interpret as the start of a character
when it scans the string starting at start.

In a pathological case like the one constructed, it fails to do that.
dgpplain2020-04-07 20:40:33
The point was always to demonstrate flaws in Tcl_UtfPrev, not to prompt
workarounds of them.
sebreswiki2020-04-08 12:58:49

I think my new branch (e. g. [cdffcbaec97b94d2]) restores ultimately the consistency between Tcl_UtfPrev/Tcl_UtfToUniChar and so fixes now all test cases (inclusive utf-7.11.1)...
but as for utf-7.11.1 I'm unsure, because correct behavior of Tcl_UtfPrev strictly following Tcl_UtfToUniChar would be to change line 705 91d7ab8dbaee9821&ln=705 to:

   - if (o >= i) {
   + if (o == i) {
but then test utf-7.11.1 would fail with:
   testutfprev A\xE8\xA0\xA0\xA0 3
   ---- Result was:
   2
   ---- Result should have been (exact matching):
   1
   ==== utf-7.11.1 FAILED
The backwards compatibility is one thing, but it could be worse (or even dangerous) if Tcl_UtfPrev would find a char with offset larger than current position (just imagine it would be outside of the end).

... I'll try yet to remove some optimizations in string trim's (made to circumvent the inconsistency), still unsure it will be possible... and will push it to my branch if it would work.

sebreswiki2020-04-08 13:35:44

Normally all the string trim changes would have been indeed revertible (that is a good sign that the fix is correct), so I removed the part with length comparison, but have left other parts as appropriate more safe optimizations, that could be important in some cases still not covered by current or some future implementation of Tcl_UtfPrev/Tcl_UtfToUniChar.

sebreswiki2020-04-08 15:54:32

As for suggested definition to handle max search depth (max number of iterations) in cycle of Tcl_UtfPrev correctly, [f10ba6b7ac2b709c] introduced it now (called UTF_TO_UNI_MAX), so it is 3 now for default 8.5th build (unless TCL_UTF_MAX gets specified greater than 3, where UTF_TO_UNI_MAX becomes 4 then in 8.5).
All tests still passed.

And for the case if the solution from branch sebres-utf-prev-fix should be used for versions >= 8.6 too, the definition of UTF_TO_UNI_MAX should be then adjusted further to maximally possible return value of Tcl_UtfToUniChar, corresponding its logic depended from specified TCL_UTF_MAX.

dgpplain2020-04-08 16:28:45
A key milestone in the history of the Tcl_UtfPrev routine.

https://core.tcl-lang.org/tcl/info/5f02e9a154f7f71e
dgpplain2020-04-08 16:35:11
That change eliminated a test

    if (totalBytes[byte] != i + 1) {

when it would have been more correct to change it to

    if (totalBytes[byte] <= i + 1) {

That would have prevented the bug in the original comment here.
dgpplain2020-04-08 17:05:56
oops! make that

    if (totalBytes[byte] < i + 1) {

or

    if (totalBytes[byte] <= i) {

according to taste.
dgpplain2020-04-08 17:43:27
The two tests that still fail can be addressed by re-defining the result to be
correct.  If we specify that Tcl_UtfPrev returns a pointer to a byte that

1) will begin a character when scanning from start.
2) May possibly be a character containing the byte (src - 1)
3) Is the earliest such pointer >= start.

This leaves open the possibility that 

Tcl_UtfNext( Tcl_UtfPrev( src, start) )

may return a result that is strictly less than src.

We should look for any callers that do not expect that.

Note that it cannot be expected that Tcl_UtfNext and Tcl_UtfPrev are precise
inverses of each other if we also expect each of them to accept mid-character
pointers as input, yet always produce lead-byte pointers as results.
dgpplain2020-04-08 18:27:00
Origin of that flawed bug fix is here

https://core.tcl-lang.org/tk/tktview?name=450504
sebreswiki2020-04-08 18:37:50

The question may be rather whether Tcl_UtfNext and Tcl_UtfPrev are precise inverses of each other if we'd exclude "artificial" cases of starting from the mid-character...
For example what is the middle by some "broken" (not valid, surrogate) utf-8 sequence, but enclosed between two correct single byte ascii-chars...
Sure it is not really normal case, but at least one would expect if Next(Next) reaches the right boundary, that the Prev(Prev) starting from there would reach the left boundary (no matter how many nested calls needed, it is always the same count forwards and backwards).

If it is not guaranteed - it may be (or rather should be) considered as a bug.

Therefore in such precedence question I'm for consistency over backwards compatibility.

dgpplain2020-04-08 19:45:49
When we have strings that contain invalid byte sequences, callers of
Tcl_UtfPrev already have bugs like this one.

% interp alias {} bytes {} encoding convertfrom identity
bytes
% set demo [bytes "abc def\xE0\xA9ghi"]
abc defà©ghi
% string index $demo 10
h
% string is word [bytes \xA9]
0
% string index $demo [string wordstart $demo 10]
e

The answer ought to be "g". A second best answer might be "d".

With the candidate fix, we get....

% string index $demo [string wordstart $demo 10]
e

...the same wrong result.

I think our aim should be to get on a path to reach the day when we reject invalid
byte sequences, so making Tcl handle them more correctly isn't a productive plan.

More interested in any examples where the change leads to segfaults, etc.
dgpplain2020-04-08 22:34:47
Indeed most callers of Tcl_UtfPrev are expecting it to be a tool to help
deal with incomplete characters at the end of some string.  To continue
to be useful, the routine needs to continue returning the earliest pointer
that points to some lead byte that might consume all the bytes up through
src - 1, at least for some values that might be in or might come to be in src.
dgpplain2020-04-08 22:43:14
By contrast the few callers who are trying to use Tcl_UtfPrev as a reliable
backward iterator over characters in a string are all no more vulnerable to
failure because of malformed byte sequences than they already were.

As long as we continue to semi-tolerate broken string input data, these
routines will break handling them. They already did. They still will under
this proposed bug fix.

The safety feature of Tcl_UtfPrev(src, start) that it will never return a 
pointer earlier than start gives us good confidence it is not going to lead
to pointer accesses out of bounds.
dgpplain2020-04-13 19:46:13
Fix committed for 8.5.
dgpplain2020-04-13 22:12:18
Re-opened to record issues merging the fix forward.
dgpplain2020-04-13 22:19:49
Fixing the bugs in Tcl_UtfPrev in Tcl 8.5 involved restoring the use of
the totalBytes array to control how each lead byte is handled. Early on
that array was a straightforward lookup table of how many total bytes
a complete, well-formed character should require in UTF-8 given the
value of its lead byte.

After the regression bug stopped the use of the totalBytes array by
Tcl_UtfPrev, the only user has been Tcl_UtfComplete, and in Tcl 8.6
the contents of the array have evolved away from the simple meaning
to cater to only the (increasingly complex) needs of Tcl_UtfComplete.

Now that the corrected Tcl_UtfPrev is trying to use the table again, those
conflicting needs are a problem.

That's why the bug fix merged to 8.6 is failing its tests.

The most simple-minded fix may be two tables for two needs.  Not clear
whether that raises its own set of synchronization issues.
sebreswiki2020-04-14 14:53:09

@Jan: (not directly belonging to this, but...) as for [e9f5ff2f6a]:

  • I think usage of encoding "identity" is justified in "encoding.test"...
  • anyway I noticed that the test "encoding-15.3" (as it was re-implemented in [e9f5ff2f6a]) would never cover something - it used not existing command "teststringbytes" (should it be "testbytesstring"?)... But if so, it is not an opposite to get same result as a conversion to identity encoding (rather using "testbytesstring" it'd result to 00 and not to c080)...
So I partially reverted it in [ab7e9e03e9] and split it there to 3 new cases illustrating the results.

jan.nijtmansplain2020-04-14 16:23:45
@Sebres:   Well-noted. Actually, I wanted to use the "testtringbytes" command from 8.7, but forgot to backport this.  We are not testing the "identity" encoding in this testcase, but the UtfToUtf encoder/decoder. Those test-cases test the handlingof the NULL byte through this encoder/decoder, so 2 test-cases (for both directions) are enough here.

Should be fixed now in all branches.
jan.nijtmanswiki2020-04-14 16:36:06

It looks that in Tcl 8.5 and 8.6 everything is fine now. But in 8.7 I still had to mark the encoding 20.7 and 20.8 test-cases as "knownBug". Something is still wrong there, it's not clear to me where the upmerging of the bug-fixes went wrong. There are no surrogates involved here, so it should just work as in 8.5 and 8.6 .... ;-(

Still some work to do ....

dgpplain2020-04-14 16:48:55
Do you see a failing test?
dgpplain2020-04-14 16:51:27
Oh geez. knownBug?!

So all my testing is doing nothing.
dgpplain2020-04-14 16:52:42
knownBug is for when we've given up, not for when we're working out the problems.
dgpplain2020-04-14 17:00:58
string-20.7 looks like a change in whether [string map] makes its replacements
based on UTF-8 equality or UCS-2 equality.
dgpplain2020-04-14 17:06:13
% package present Tcl
8.6.10
% string map [list \x88 YES] [testbytestring \x88]
YES

% package present Tcl
8.7a4
% string map [list \x88 YES] [testbytestring \x88]
ˆ

We could use some other conversion to make the test
outputs more readable.
dgpplain2020-04-14 17:29:38
ok, need a different single byte for the test. The meaning of a bare \x88 has changed.

Used to be interpreted as \u0088 according to ISO-8859-1.

Now is interpreted as something else according to some WIndows code page.

A battle for another time. For now we should dodge with a different test case.
jan.nijtmansplain2020-04-14 17:59:56
Oh Yes, the fallback to cp1252. That's described in TIP #389 (fifth '*' of specification).  Makes sense to me now.

Thanks for fixing the test-case. I knew it was something completely different!

So, this issue can be closed now?
dgp Closed ticket [c61818e4c9]. [History diff]2020-04-14 18:09:23
Log in (anonymous is fine) to add a comment.