Skip to content

Commit 533bf74

Browse files
committed
Fix resource initialization order to prevent UB in destructor
Move tw_init(&conn->cancel_tw) before interrupt_mutex creation. If interrupt_mutex creation fails, enif_release_resource triggers the destructor, which calls tw_destroy on conn->cancel_tw. Without this change, tw_destroy would be called on an uninitialized condvar.
1 parent f302f47 commit 533bf74

1 file changed

Lines changed: 10 additions & 7 deletions

File tree

c_src/sqlite3_nif.c

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -548,20 +548,23 @@ exqlite_open(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
548548
}
549549
conn->db = db;
550550
conn->mutex = mutex;
551-
conn->interrupt_mutex = enif_mutex_create("exqlite:interrupt");
551+
conn->interrupt_mutex = NULL;
552552
memset(conn->authorizer_deny, 0, sizeof(conn->authorizer_deny));
553-
if (conn->interrupt_mutex == NULL) {
554-
// conn->db and conn->mutex are set; the destructor will clean them up.
555-
enif_release_resource(conn);
556-
return make_error_tuple(env, am_failed_to_create_mutex);
557-
}
558553

559-
// Initialize cancellable busy handler
554+
// Initialize cancellable busy handler fields early so destructor can safely
555+
// call tw_destroy even if subsequent initialization steps fail.
560556
tw_init(&conn->cancel_tw);
561557
conn->cancelled = 0;
562558
conn->busy_timeout_ms = 2000; // default matches sqlite3_busy_timeout(db, 2000)
563559
conn->callback_env = NULL;
564560

561+
conn->interrupt_mutex = enif_mutex_create("exqlite:interrupt");
562+
if (conn->interrupt_mutex == NULL) {
563+
// conn->db, conn->mutex, and conn->cancel_tw are set; destructor will clean them up.
564+
enif_release_resource(conn);
565+
return make_error_tuple(env, am_failed_to_create_mutex);
566+
}
567+
565568
// Install our custom busy handler + progress handler
566569
sqlite3_busy_handler(db, exqlite_busy_handler, conn);
567570
sqlite3_progress_handler(db, 1000, exqlite_progress_handler, conn);

0 commit comments

Comments
 (0)