Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: 81c1a49514072476977d5815e2da35db8a38b94337e38db954dac060ead73757
Ticket: 90612089d8423b75a50197df1cdd29d5aef2f062
signed integer overflow in ExprRandFunc()
User & Date: chrstphrchvz on 2021-12-15 09:46:14
Changes

  1. assignee changed to: "nobody"
  2. closer changed to: "nobody"
  3. cmimetype changed to: "text/x-fossil-wiki"
  4. comment changed to:
    There is signed integer overflow happening in <tt>ExprRandFunc()</tt> (generic/tclBasic.c). UBSan (<tt>-fsanitize=shift-base</tt>) complaint:
    
    <pre>
    % puts [expr {rand()}]
    <span style="font-weight:bold">tcl/generic/tclBasic.c:7784:69: <span style="color:red">runtime error:</span> left shift of 404780544 by 12 places cannot be represented in type 'int'</span>
    SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior tcl/generic/tclBasic.c:7784:69 in 
    0.6984060833688853
    </pre>
    
    The signed integer overflow can be avoided by instead using <tt>PTR2UINT()</tt>:
    <pre>
    diff --git generic/tclBasic.c generic/tclBasic.c
    index fb8524180..4a2fc04b3 100644
    --- generic/tclBasic.c
    +++ generic/tclBasic.c
    @@ -7781,7 +7781,7 @@ ExprRandFunc(
     	 * take into consideration the thread this interp is running in.
     	 */
    <span> </span>
    <span style="color:red">-	iPtr->randSeed = TclpGetClicks() + (PTR2INT(Tcl_GetCurrentThread())<<12);</span>
    <span style="color:green">+	iPtr->randSeed = TclpGetClicks() + (PTR2UINT(Tcl_GetCurrentThread())<<12);</span>
    <span> </span>
     	/*
     	 * Make sure 1 <= randSeed <= (2^31) - 2. See below.
    </pre>
    
    Though I wonder if it is intentional to have <tt>Tcl_GetCurrentThread()</tt> contribute at most (32-12)-1=19 bits (assuming <tt>sizeof(int)==4</tt>) to the seed (even fewer in practice due to lower order bits tending to be identical between threads, depending on the alignment of the struct underlying <tt>pthread_t</tt>, and/or spacing between <tt>pthread_t</tt> instances being a multiple of not very small powers of 2: I observe that for glibc NPTL on Linux i386, it is 2**12—i.e. 4kib page size—so as few as ((32-12)-12)-1=7 useful bits are incorporated in the seed). If this statement should be changed to incorporate more useful bits from <tt>Tcl_GetCurrentThread()</tt>, can the behavior of this statement be changed in 8.6?
    
  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: "16. Commands A-H"
  14. title changed to: "signed integer overflow in ExprRandFunc()"
  15. type changed to: "Patch"