Skip to content

Commit faa9540

Browse files
committed
If a Result is freed after it's Client, allow it to free the Client's
underlying MYSQL* structure to prevent leaks. This will be pretty rare but needs to be accounted for.
1 parent b241f54 commit faa9540

File tree

3 files changed

+9
-2
lines changed

3 files changed

+9
-2
lines changed

ext/mysql2/client.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,9 +185,10 @@ static VALUE nogvl_close(void *ptr) {
185185
static void rb_mysql_client_free(void * ptr) {
186186
mysql_client_wrapper *wrapper = (mysql_client_wrapper *)ptr;
187187

188-
if (wrapper->refcount == 0) {
189-
nogvl_close(wrapper);
188+
wrapper->freed = 1;
189+
nogvl_close(wrapper);
190190

191+
if (wrapper->refcount == 0) {
191192
xfree(wrapper->client);
192193
xfree(ptr);
193194
}
@@ -203,6 +204,7 @@ static VALUE allocate(VALUE klass) {
203204
wrapper->connected = 0; /* means that a database connection is open */
204205
wrapper->initialized = 0; /* means that that the wrapper is initialized */
205206
wrapper->refcount = 0;
207+
wrapper->freed = 0;
206208
wrapper->client = (MYSQL*)xmalloc(sizeof(MYSQL));
207209
return obj;
208210
}

ext/mysql2/client.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ typedef struct {
3939
int connected;
4040
int initialized;
4141
int refcount;
42+
int freed;
4243
MYSQL *client;
4344
} mysql_client_wrapper;
4445

ext/mysql2/result.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,10 @@ static void rb_mysql_result_free_result(mysql2_result_wrapper * wrapper) {
7373
mysql_free_result(wrapper->result);
7474
wrapper->resultFreed = 1;
7575
wrapper->client_wrapper->refcount--;
76+
if (wrapper->client_wrapper->refcount == 0 && wrapper->client_wrapper->freed) {
77+
xfree(wrapper->client_wrapper->client);
78+
xfree(wrapper->client_wrapper);
79+
}
7680
}
7781
}
7882

0 commit comments

Comments
 (0)