• Chaithra Gopalareddy's avatar
    Bug #16119355: PREPARED STATEMENT: READ OF FREED MEMORY WITH · 5bf9b7d0
    Chaithra Gopalareddy authored
                                     STRING CONVERSION FUNCTIONS
                
    Problem:
    While executing the prepared statement, user variable is
    set to memory which would be freed at the end of
    execution.
    If the statement is executed again, valgrind throws
    error when accessing this pointer.
                      
    Analysis:
                    
    1. First time when Item_func_set_user_var::check is called,
       memory is allocated for "value" to store the result.
       (In the call to copy_if_not_alloced).
    2. While sending the result, Item_func_set_user_var::check
       is called again. But, this time, its called with
       "use_result_field" set to true. 
       As a result, we call result_field->val_str(&value).
    3. Here memory allocated for "value" gets freed. And "value"
       gets set to "result_field", with "str_length" being that of
       result_field's.
    4. In the call to JOIN::cleanup, result_field's memory gets
       freed as this is allocated in a chunk as part of the
       temporary table which is needed to execute the query.
    5. Next time, when execute of the same statement is called,
       "value" will be set to memory which is already freed.
       Valgrind error occurs as "str_length" is positive 
       (set at Step 3)
                      
    Note that user variables list is stored as part of the Lex object
    in set_var_list. Hence the persistance across executions.
                
    Solution:
    Patch for Bug#11764371 fixed in mysql-5.6+ fixes this problem 
    as well.So backporting the same.
                
    In the solution for Bug#11764371, we create another object of 
    user_var and repoint it to temp_table's field. As a result while 
    deleting the alloced buffer in Step 3, since the cloned object 
    does not own the buffer, deletion will not happen.
    So at step 5 when we execute the statement second time, the 
    original object will be used and since deletion did not happen 
    valgrind will not complain about dangling pointer.
    5bf9b7d0
sql_select.cc 556 KB