Skip to content
Tcl Source Code View Ticket
Login

View Ticket

avoid signed integer overflow in AppendUtfToUtfRep()

Closed / Fixedd1434179b5a377ecf00b088d0b9e216184c97cdaCreated 5 years agoUpdated 5 years ago
Descriptionwiki2021-12-12 00:52:40
AppendUtfToUtfRep() aborts if there was signed integer overflow when int newLength was computed, but this relies on undefined behavior (as Tcl normally isn’t compiled with e.g. -fwrapv). UBSan (-fsanitize=signed-integer-overflow) complaint:
% set 1GiB_string [string repeat { } [expr {1 << 30}]]
% puts [string bytelength $1GiB_string]
1073741824
% set 2GiB_string [string cat $1GiB_string $1GiB_string]
tcl/generic/tclStringObj.c:1725:26: runtime error: signed integer overflow: 1073741824 + 1073741824 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior tcl/generic/tclStringObj.c:1725:26 in 
max size for a Tcl value (2147483647 bytes) exceeded

(tclsh8.6 aborted)

The overflow check should instead be done before newLength is computed (as similarly done elsewhere in Tcl 8.6):

diff --git generic/tclStringObj.c generic/tclStringObj.c
index 22e025c9b..7c04385f4 100644
--- generic/tclStringObj.c
+++ generic/tclStringObj.c
@@ -1722,10 +1722,10 @@ AppendUtfToUtfRep(
        objPtr->length = 0;
     }
     oldLength = objPtr->length;
+    if (numBytes > INT_MAX - oldLength) {
+       Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
+    }
     newLength = numBytes + oldLength;
-    if (newLength < 0) {
-       Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
-    }

stringPtr = GET_STRING(objPtr); if (newLength > stringPtr->allocated) {
Referenced by1
  • 8340945434Fix [d1434179b5]: avoid signed integer overflow in AppendUtfToUtfRep() check-in2021-12-16 21:25:52
jan.nijtmanswiki2021-12-16 21:29:37

Fixed [here]. Thanks for the report and for the patch!

chrstphrchvzwiki2021-12-18 12:11:46

Thanks for accepting this, however the description for check-in [8340945434] currently refers to [b0f84119c8] rather than this ticket, can it be revised?

jan.nijtmanswiki2021-12-18 14:54:25

Revised now. Thanks!

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