• Sergei Petrunia's avatar
    MDEV-31432 tmp_table field accessed after free · 8aaacb55
    Sergei Petrunia authored
    Before this patch, the code in Item_field::print() used
    this convention (described in sql_explain.h:ExplainDataStructureLifetime):
    
    - By default, the table that Item_field refers to is accessible.
    - ANALYZE and SHOW {EXPLAIN|ANALYZE} may print Items after some
      temporary tables have been dropped. They use
      QT_DONT_ACCESS_TMP_TABLES flag. When it is ON, Item_field::print
      will not access the table it refers to, if it is a temp.table
    
    The bug was that EXPLAIN statement also may compute subqueries (depending
    on subquery context and @@expensive_subquery_limit setting). After the
    computation, the subquery calls JOIN::cleanup(true) which drops some of
    its temporary tables. Calling Item_field::print() that refer to such table
    will cause an access to free'd memory.
    
    In this patch, we take into account that query optimization can compute
    a subquery and discard its temporary tables. Item_field::print() now
    assumes that any temporary table might have already been dropped.
    This means QT_DONT_ACCESS_TMP_TABLES flag is not needed - we imply it is
    always present.
    
    But we also make one exception: derived tables are not freed in
    JOIN::cleanup() call. They are freed later in close_thread_tables(),
    at the same time when regular tables are closed.
    Because of that, Item_field::print may assume that temp.tables
    representing derived tables are available.
    
    Initial patch by: Rex Jonston
    Reviewed by: Monty <monty@mariadb.org>
    8aaacb55
sql_base.cc 317 KB