Skip to content

Commit b9ff97d

Browse files
authored
Fix segfault for failing to open a db (#246)
1 parent 4e41f56 commit b9ff97d

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

c_src/sqlite3_nif.c

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -189,10 +189,12 @@ exqlite_open(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
189189
{
190190
assert(env);
191191

192+
int flags;
192193
int rc = 0;
193194
int size = 0;
194-
int flags;
195195
connection_t* conn = NULL;
196+
sqlite3* db = NULL;
197+
ErlNifMutex* mutex = NULL;
196198
char filename[MAX_PATHNAME];
197199
ERL_NIF_TERM result;
198200

@@ -205,28 +207,31 @@ exqlite_open(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
205207
return make_error_tuple(env, "invalid_filename");
206208
}
207209

208-
conn = enif_alloc_resource(connection_type, sizeof(connection_t));
209-
if (!conn) {
210-
return make_error_tuple(env, "out_of_memory");
211-
}
212-
213210
if (!enif_get_int(env, argv[1], &flags)) {
214211
return make_error_tuple(env, "invalid flags");
215212
}
216213

217-
rc = sqlite3_open_v2(filename, &conn->db, flags, NULL);
214+
rc = sqlite3_open_v2(filename, &db, flags, NULL);
218215
if (rc != SQLITE_OK) {
219-
enif_release_resource(conn);
220216
return make_error_tuple(env, "database_open_failed");
221217
}
222218

223-
conn->mutex = enif_mutex_create("exqlite:connection");
224-
if (conn->mutex == NULL) {
225-
enif_release_resource(conn);
219+
mutex = enif_mutex_create("exqlite:connection");
220+
if (mutex == NULL) {
221+
sqlite3_close_v2(db);
226222
return make_error_tuple(env, "failed_to_create_mutex");
227223
}
228224

229-
sqlite3_busy_timeout(conn->db, 2000);
225+
sqlite3_busy_timeout(db, 2000);
226+
227+
conn = enif_alloc_resource(connection_type, sizeof(connection_t));
228+
if (!conn) {
229+
sqlite3_close_v2(db);
230+
enif_mutex_destroy(mutex);
231+
return make_error_tuple(env, "out_of_memory");
232+
}
233+
conn->db = db;
234+
conn->mutex = mutex;
230235

231236
result = enif_make_resource(env, conn);
232237
enif_release_resource(conn);

0 commit comments

Comments
 (0)