From 2882c5f9f1f1c81a5a2bae35825d81070bb10164 Mon Sep 17 00:00:00 2001
From: Scott Griepentrog <sgriepentrog@digium.com>
Date: Thu, 19 Dec 2013 16:33:09 +0000
Subject: [PATCH] astdb: crash in sqlite3 during shutdown
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

When Asterisk is shut down, the astdb_atexit() function releases
(finalize) the previously initiated (prepared) SQL statements in
sqlite3.  Another thread making a subsequent request can cause a
crash in sqlite3.  This patch eliminates that issue by resetting
the statement pointer after it is released/cleared.  The sqlite3
code detects the null pointer, and aborts the operation cleanly.

(closes issue AST-1265)
Reported by: Alexander Hömig
(closes issue ASTERISK-22350)
Reported by: Birger "WIMPy" Harzenetter
Review: https://reviewboard.asterisk.org/r/3078/
........

Merged revisions 404344 from http://svn.asterisk.org/svn/asterisk/branches/11
........

Merged revisions 404345 from http://svn.asterisk.org/svn/asterisk/branches/12


git-svn-id: https://origsvn.digium.com/svn/asterisk/trunk@404346 65c4cc65-6c06-0410-ace0-fbb531ad65f3
---
 main/db.c | 24 +++++++++++++-----------
 1 file changed, 13 insertions(+), 11 deletions(-)

diff --git a/main/db.c b/main/db.c
index 4fe249b102..df3398ab2a 100644
--- a/main/db.c
+++ b/main/db.c
@@ -145,12 +145,14 @@ static int init_stmt(sqlite3_stmt **stmt, const char *sql, size_t len)
  * \brief Clean up the prepared SQLite3 statement
  * \note dblock should already be locked prior to calling this method
  */
-static int clean_stmt(sqlite3_stmt *stmt, const char *sql)
+static int clean_stmt(sqlite3_stmt **stmt, const char *sql)
 {
-	if (sqlite3_finalize(stmt) != SQLITE_OK) {
+	if (sqlite3_finalize(*stmt) != SQLITE_OK) {
 		ast_log(LOG_WARNING, "Couldn't finalize statement '%s': %s\n", sql, sqlite3_errmsg(astdb));
+		*stmt = NULL;
 		return -1;
 	}
+	*stmt = NULL;
 	return 0;
 }
 
@@ -160,15 +162,15 @@ static int clean_stmt(sqlite3_stmt *stmt, const char *sql)
  */
 static void clean_statements(void)
 {
-	clean_stmt(get_stmt, get_stmt_sql);
-	clean_stmt(del_stmt, del_stmt_sql);
-	clean_stmt(deltree_stmt, deltree_stmt_sql);
-	clean_stmt(deltree_all_stmt, deltree_all_stmt_sql);
-	clean_stmt(gettree_stmt, gettree_stmt_sql);
-	clean_stmt(gettree_all_stmt, gettree_all_stmt_sql);
-	clean_stmt(showkey_stmt, showkey_stmt_sql);
-	clean_stmt(put_stmt, put_stmt_sql);
-	clean_stmt(create_astdb_stmt, create_astdb_stmt_sql);
+	clean_stmt(&get_stmt, get_stmt_sql);
+	clean_stmt(&del_stmt, del_stmt_sql);
+	clean_stmt(&deltree_stmt, deltree_stmt_sql);
+	clean_stmt(&deltree_all_stmt, deltree_all_stmt_sql);
+	clean_stmt(&gettree_stmt, gettree_stmt_sql);
+	clean_stmt(&gettree_all_stmt, gettree_all_stmt_sql);
+	clean_stmt(&showkey_stmt, showkey_stmt_sql);
+	clean_stmt(&put_stmt, put_stmt_sql);
+	clean_stmt(&create_astdb_stmt, create_astdb_stmt_sql);
 }
 
 static int init_statements(void)
-- 
GitLab