Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: 595ba0ab03d42de9a387d1f0f9f48afb93a2f6a688400ec6ec84f694caf7291c
Ticket: 41b1406f515e092067103439e63caad5843039e3
AppendUtfToUtfRep(): undefined behavior involving pointers
User & Date: chrstphrchvz on 2021-12-12 10:35:02
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> (generic/tclStringObj.c) tries to check if the source string <tt>bytes</tt> is within the destination string buffer <tt>objPtr-&gt;bytes</tt>, since extending the destination string’s buffer may move the source string and require updating <tt>bytes</tt>:
    
    <pre>
    	if (bytes && bytes >= objPtr->bytes
    		&& bytes <= <span style="font-weight:bold">objPtr->bytes + objPtr->length</span>) {
    	    offset = bytes - objPtr->bytes;
    	}
    </pre>
    
    The pointer arithmetic in the range check is performed even when <tt>objPtr-&gt;bytes</tt> is <tt>NULL</tt>, which is undefined behavior. [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks|UBSan (<tt>-fsanitize=pointer-arithmetic</tt>)] complains:
    
    <pre>
    $ ./tcltest ../tests/stringObj.test 
    <span style="font-weight:bold">tcl/generic/tclStringObj.c:1741:29: <span style="color:red">runtime error:</span> applying zero offset to null pointer</span>
    SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior tcl/generic/tclStringObj.c:1741:29 in 
    stringObj.test:	Total	68	Passed	68	Skipped	0	Failed	0
    </pre>
    
    Also, I believe the range check resembles the problem described in [https://devblogs.microsoft.com/oldnewthing/20170927-00/?p=97095]: either the pointers are for the same buffer and the check is always true, or the pointers are to different buffers and the check is undefined behavior. If this is the case, I’m not aware of a good workaround: the suggestion of casting to <tt>uintptr_t</tt> requires C99; and at least one caller of <tt>AppendUtfToUtfRep()</tt>, <tt>Tcl_AppendLimitedToObj()</tt>, is a public API which has no knowledge of whether its <tt>bytes</tt> argument points to the same buffer as <tt>objPtr-&gt;bytes</tt>.
    
    See [https://core.tcl-lang.org/tk/tktview?name=156e58bc6e] for a similar issue.
    
  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:
    AppendUtfToUtfRep(): undefined behavior involving pointers
    
  15. type changed to: "Bug"