Skip to content
Tcl Source Code View Ticket
Login

View Ticket

Fix unsafe buffer lifetime

Closed / Fixed24b918147808e33e9bdb31a516fd29daaddd7149Created 6 years agoUpdated 6 years ago
Descriptionplain2021-05-03 18:40:04
tl;dr this patch fixes a lifetime bug detected in trunk versions of Clang:

$ git diff generic/tclIO.c
diff --git a/generic/tclIO.c b/generic/tclIO.c
index dc028b522..a23fff80f 100644
--- a/generic/tclIO.c
+++ b/generic/tclIO.c
@@ -4296,9 +4296,10 @@ Write(
        nextNewLine = (char *)memchr(src, '\n', srcLen);
     }
 
+    char safe[BUFFER_PADDING];
     while (srcLen + saved + endEncoding > 0) {
        ChannelBuffer *bufPtr;
-       char *dst, safe[BUFFER_PADDING];
+       char *dst;
        int result, srcRead, dstLen, dstWrote, srcLimit = srcLen;
 
        if (nextNewLine) {

Longer summary: a recent update to clang improves optimizations related to memcpy:
https://github.com/llvm/llvm-project/commit/f5446b769a7929806f72256fccd4826d66502e59.

When we upgraded to a version of clang that includes this optimization, we
encountered a build error from a step that was consuming the output of a tcl/tk
script, and found that the tcl script was producing junk output. Upon further
inspection, this is because the tcl interpreter built by clang was entirely
optimizing away the "safe" buffer in the patch above. This appears to be valid,
as the lifetime of the "safe" buffer ends at the closing of the for loop, and
is not guaranteed to be preserved on the next loop iteration. Moving the buffer
outside of the for loop will preserve the "safe" buffer for the necessary
lifetime.
Referenced by4
  • 84d6c2b9d5Closed ticket [8139aa83a4]: tclsh wrong result in string output when built with clang plus 7 other changes ticket2023-01-06 15:43:22
  • 309347677fTicket [206e58994f] tcl builds with clang but fails to run correctly status still Open with 3 other changes ticket2021-12-05 08:38:34
  • f6468f7763Fix [24b9181478]: Fix unsafe buffer lifetime check-in2021-05-03 19:42:03
  • 98af80f133Fix [24b9181478]: Fix unsafe buffer lifetime check-in2021-05-03 19:36:22
jan.nijtmanswiki2021-05-03 19:55:07

Well, this but can be traced back to Tcl 8.5 (and probably much further back in history). Thanks for this detailed explanation and for the fix.

Fixed now in all active branches (8.5 and up)

dkfwiki2021-05-04 07:31:13

Good catch; that code was wrong.

Log in (anonymous is fine) to add a comment.