Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: b7c9496e3b36f89ec1122beb8d35903de5162574edc07c0ad086b32ab3f60a7e
Ticket: d1434179b5a377ecf00b088d0b9e216184c97cda
avoid signed integer overflow in AppendUtfToUtfRep()
User & Date: chrstphrchvz on 2021-12-12 00:52:40
Changes

  1. assignee changed to: "nobody"
  2. closer changed to: "nobody"
  3. cmimetype changed to: "text/x-fossil-wiki"
  4. comment changed to:
    <tt>AppendUtfToUtfRep()</tt> aborts if there was signed integer overflow when <tt>int newLength</tt> was computed, but this relies on undefined behavior (as Tcl normally isn’t compiled with e.g. <tt>-fwrapv</tt>). [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks|UBSan (<tt>-fsanitize=signed-integer-overflow</tt>)] complaint:
    
    <blockquote><pre>
    % set 1GiB_string [string repeat { } [expr {1 << 30}]]
    % puts [string bytelength $1GiB_string]
    1073741824
    % set 2GiB_string [string cat $1GiB_string $1GiB_string]
    <span style="font-weight:bold">tcl/generic/tclStringObj.c:1725:26: <span style="color:red">runtime error:</span> signed integer overflow: 1073741824 + 1073741824 cannot be represented in type 'int'</span>
    SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior tcl/generic/tclStringObj.c:1725:26 in 
    max size for a Tcl value (2147483647 bytes) exceeded
    </pre>
    
    (<tt>tclsh8.6</tt> aborted)
    </blockquote>
    
    The overflow check should instead be done before <tt>newLength</tt> is computed (as similarly done elsewhere in Tcl 8.6):
    <pre>
    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;
    <span style="color:green">+    if (numBytes > INT_MAX - oldLength) {</span>
    <span style="color:green">+       Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);</span>
    <span style="color:green">+    }</span>
         newLength = numBytes + oldLength;
    <span style="color:red">-    if (newLength < 0) {</span>
    <span style="color:red">-       Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);</span>
    <span style="color:red">-    }</span>
     
         stringPtr = GET_STRING(objPtr);
         if (newLength > stringPtr->allocated) {
    </pre>
    
  5. foundin changed to: "8.6.12"
  6. is_private changed to: "0"
  7. login: "chrstphrchvz"
  8. priority changed to: "5 Medium"
  9. resolution changed to: "None"
  10. severity changed to: "Minor"
  11. status changed to: "Open"
  12. submitter changed to: "chrstphrchvz"
  13. subsystem changed to: "44. UTF-8 Strings"
  14. title changed to:
    avoid signed integer overflow in AppendUtfToUtfRep()
    
  15. type changed to: "Patch"