Skip to content

Commit c278474

Browse files
gh-89289: Harden sqlite3.Connection init (#92214)
- Make sure SQLite resources are freed if database open fails - Remove unneeded branches if init is aborted
1 parent 2eca5da commit c278474

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

Modules/_sqlite/connection.c

+15-8
Original file line numberDiff line numberDiff line change
@@ -226,27 +226,27 @@ pysqlite_connection_init_impl(pysqlite_Connection *self,
226226
pysqlite_state *state = pysqlite_get_state_by_type(Py_TYPE(self));
227227
if (rc != SQLITE_OK) {
228228
_pysqlite_seterror(state, db);
229-
return -1;
229+
goto error;
230230
}
231231

232232
// Create LRU statement cache; returns a new reference.
233233
PyObject *statement_cache = new_statement_cache(self, state, cache_size);
234234
if (statement_cache == NULL) {
235-
return -1;
235+
goto error;
236236
}
237237

238238
/* Create lists of weak references to cursors and blobs */
239239
PyObject *cursors = PyList_New(0);
240240
if (cursors == NULL) {
241-
Py_XDECREF(statement_cache);
242-
return -1;
241+
Py_DECREF(statement_cache);
242+
goto error;
243243
}
244244

245245
PyObject *blobs = PyList_New(0);
246246
if (blobs == NULL) {
247-
Py_XDECREF(statement_cache);
248-
Py_XDECREF(cursors);
249-
return -1;
247+
Py_DECREF(statement_cache);
248+
Py_DECREF(cursors);
249+
goto error;
250250
}
251251

252252
// Init connection state members.
@@ -279,11 +279,18 @@ pysqlite_connection_init_impl(pysqlite_Connection *self,
279279
self->NotSupportedError = state->NotSupportedError;
280280

281281
if (PySys_Audit("sqlite3.connect/handle", "O", self) < 0) {
282-
return -1;
282+
return -1; // Don't goto error; at this point, dealloc will clean up.
283283
}
284284

285285
self->initialized = 1;
286286
return 0;
287+
288+
error:
289+
// There are no statements or other SQLite objects attached to the
290+
// database, so sqlite3_close() should always return SQLITE_OK.
291+
rc = sqlite3_close(db);
292+
assert(rc == SQLITE_OK), rc;
293+
return -1;
287294
}
288295

289296
#define VISIT_CALLBACK_CONTEXT(ctx) \

0 commit comments

Comments
 (0)