Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: b21da8d5a830a1f8b3772f25c8ffe1c5435107176d8f6cddaff07ad90653ff6f
Ticket: 6ef312dcf5b846c344911c04a1e41e52ec28efe2
memcpy() with NULL source in Tcl_CreateMathFunc()
User & Date: chrstphrchvz on 2021-12-16 04:31:11
Changes

  1. assignee changed to: "nobody"
  2. closer changed to: "nobody"
  3. cmimetype changed to: "text/x-fossil-wiki"
  4. comment changed to:
    If <tt>Tcl_CreateMathFunc()</tt> (generic/tclBasic.c) is called with 0 and <tt>NULL</tt> for <tt>numArgs</tt> and <tt>argTypes</tt> respectively, as done in <tt>Tcltest_Init()</tt> (generic/tclTest.c), this causes <tt>memcpy()</tt> to be called with <tt>NULL</tt> as the source, which is undefined behavior even though the number of bytes to copy is 0. [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks|UBSan (<tt>-fsanitize=nonnull-attribute</tt>)] complaint when used with GCC (as not all common standard library implementations declare <tt>memcpy()</tt> with source or destination pointers as non-<tt>NULL</tt>):
    
    <pre>
    $ ./tcltest
    <span style="font-weight: bold">tcl/generic/tclBasic.c:3557:2: <span style="color:red">runtime error:</span> null pointer passed as argument 2, which is declared to never be null</span>
    %
    </pre>
    
    To avoid this, I would only call <tt>memcpy()</tt> (and <tt>ckalloc()</tt>) when <tt>numArgs</tt> is positive:
    
    <pre>
    diff --git generic/tclBasic.c generic/tclBasic.c
    index fb8524180..45a25ca64 100644
    --- generic/tclBasic.c
    +++ generic/tclBasic.c
    @@ -3550,8 +3550,12 @@ Tcl_CreateMathFunc(
    <span> </span>
         data->proc = proc;
         data->numArgs = numArgs;
    <span style="color:red">-    data->argTypes = (Tcl_ValueType *)ckalloc(numArgs * sizeof(Tcl_ValueType));
    -    memcpy(data->argTypes, argTypes, numArgs * sizeof(Tcl_ValueType));</span>
    <span style="color:green">+    data->argTypes = NULL;
    +    if (0 < numArgs) {
    +	data->argTypes =
    +		(Tcl_ValueType *)ckalloc(numArgs * sizeof(Tcl_ValueType));
    +	memcpy(data->argTypes, argTypes, numArgs * sizeof(Tcl_ValueType));
    +    }</span>
         data->clientData = clientData;
    <span> </span>
         Tcl_DStringInit(&bigName);
    </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: "52. Portability Support"
  14. title changed to: "memcpy() with NULL source in Tcl_CreateMathFunc()"
  15. type changed to: "Patch"