Bug #77076 mysql_close causes stack corruption
Submitted: 18 May 2015 16:45 Modified: 19 Jun 2015 15:02
Reporter: Doug Schultz Email Updates:
Status: No Feedback Impact on me:
None 
Category:MySQL Server: Embedded Library ( libmysqld ) Severity:S3 (Non-critical)
Version:MySQL Connector.C 6.1 OS:Windows (Windows 7)
Assigned to: CPU Architecture:Any

[18 May 2015 16:45] Doug Schultz
Description:
*Note: first I want to declare this a poor design. Memory allocation and de-allocation should be separated out from _init and _close. But since it is there...

mysql_init needs to set the MYSQL.free_me flag to true if a user passes NULL otherwise it should be set to false.
mysql_close needs to check the MYSQL.free_me to see if it should call free() to deallocate memory.

mysql_close documentation states that it will delete the MYSQL object if it was allocated by msyql_init(...) or msyql_connect(...)

However, mysql_init never sets the free_me flag and mysql_close never checks it. Thus, it will attempt to delete an object declared on the stack.

How to repeat:
void mysql_stack_corruption_bug()
{
    MYSQL temp;
    mysql_init(&temp);
    // you might call mysql_real_connect(...) but not necessary to reproduce
    // the bug.
    mysql_close(&temp); // causes stack corruption
}

I found this using Boost Test Framework which checks for stack corruption.

Suggested fix:
mysql_init needs to set the MYSQL.free_me flag to true if a user passes NULL otherwise it should be set to false.
mysql_close needs to check the MYSQL.free_me to see if it should call free() to deallocate memory.
[19 May 2015 15:02] MySQL Verification Team
Hi,

There seems to be a problem here, partially instigated by us. Regarding the "Category" field. libmysqld is a server library that you can use to make your program running without using a separate server deamon.

But, as you are using here C Connector, I guess that it is libmysql that you are using.

In versions 5.6 and 5.7 of MySQL, `free_me` field is used extensively where  it is supposed to be used.

Here is the relevant excerpt from mysql_init():
---
  if (!mysql)
  {
    if (!(mysql=(MYSQL*) my_malloc(key_memory_MYSQL,
                                   sizeof(*mysql),MYF(MY_WME | MY_ZEROFILL))))
    {
      set_mysql_error(NULL, CR_OUT_OF_MEMORY, unknown_sqlstate);
      return 0;
    }
    mysql->free_me=1;
  }
----

And here is the relevant excerpt from mysql_close():
---

    if (mysql->free_me)
      my_free(mysql);

---

Hence, everything is just fine. So, it would be nice to know which library did you use exactly and how did you observe the effect of stack corruption.

Thanks in advance.
[20 Jun 2015 1:00] Bugs System
No feedback was provided for this bug for over a month, so it is
being suspended automatically. If you are able to provide the
information that was originally requested, please do so and change
the status of the bug back to "Open".