Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: 4193cd708202c56793b58668384c1e0ce77938a171e39aeea2bdadcd891b8fed
Ticket: 1c7f179710d5dd791f4a161f2e6d34040d17bf4e
undefined behavior for INST_LSHIFT in ExecuteExtendedBinaryMathOp()
User & Date: chrstphrchvz on 2022-02-18 03:43:30
Changes

  1. assignee changed to: "nobody"
  2. closer changed to: "nobody"
  3. cmimetype changed to: "text/x-fossil-wiki"
  4. comment changed to:
    Analogous to [b0f84119c8] for left-shifting a value represented by a <tt>Tcl_WideInt</tt> (and not a <tt>long</tt> or a bignum) when <tt>Tcl_WideInt</tt> is <tt>long long</tt> (because <tt>long</tt> is only 32-bit):
    
    <ul><li>Left-shifting by 0 causes signed integer overflow (undefined behavior detected by UBSan <tt>-fsanitize=shift-base</tt>) in the expression:
    
    <blockquote><pre>
        ((Tcl_WideInt)1) &lt;&lt; (CHAR_BIT*sizeof(Tcl_WideInt) - 1 - shift)
    </pre></blockquote>
    
    i.e. 1 is shifted left (64-1-0)=63 times, which overflows; and signed integer overflow (undefined behavior detected by UBSan <tt>-fsanitize=signed-integer-overflow</tt>) when the overflowed result <tt>WIDE_MIN</tt> of the above expression is negated.</li>
    
    <li>If the left-shifted value is negative, then there is left-shifting of a negative value (undefined behavior detected by UBSan <tt>-fsanitize=shift-base</tt>).</li></ul>
    
    Example command (left operand is in the range &#91;<tt>WIDE_MIN</tt>,<tt>LONG_MIN</tt>) &cup; (<tt>LONG_MAX</tt>,<tt>WIDE_MAX</tt>&#93;); the test suite does not contain an affected example):
    
    <blockquote><pre>
    % ::tcl::mathop::&lt;&lt; -0x80000001 0
    <span style="font-weight: bold">tcl/generic/tclExecute.c:8665:4:<span style="color:firebrick"> runtime error:</span> left shift of 1 by 63 places cannot be represented in type 'long long int'</span>
    <span style="font-weight: bold">tcl/generic/tclExecute.c:8664:6:<span style="color:firebrick"> runtime error: </span>negation of -9223372036854775808 cannot be represented in type 'long long int'; cast to an unsigned type to negate this value to itself</span>
    <span style="font-weight: bold">tcl/generic/tclExecute.c:8666:7:<span style="color:firebrick"> runtime error: </span>left shift of negative value -2147483649</span>
    -2147483649
    </pre></blockquote>
    
    The attached patch avoids this by casting to <tt>Tcl_WideUInt</tt> in a couple of places before shifting.
    
  5. foundin changed to: "core-8-6-branch"
  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: "48. Number Handling"
  14. title changed to:
    undefined behavior for INST_LSHIFT in ExecuteExtendedBinaryMathOp()
    
  15. type changed to: "Patch"