From b5a30b9fce85828b970d39167128cfd101a6621b Mon Sep 17 00:00:00 2001 From: Yasuhiro Matsumoto Date: Fri, 6 Nov 2026 09:00:25 +0800 Subject: [PATCH 1/3] Return an error instead of crashing when a connection is used after Close SQLite dereferences the connection handle without checking it, so every *SQLiteConn method that passes c.db into the C API crashed the process once Close had released the handle and set it to nil. Ordinary code reaches this: a connection captured in a ConnectHook outlives its *sql.DB. The affected methods now check the handle first with dbConnOpen, which reads it under c.mu and does not hold c.mu across the C call. Methods that return an error report errConnClosed, the hook and authorizer registrations, which have no error to report, do nothing, and AutoCommit, GetFilename, GetLimit and SetLimit return a documented value. Affected: RegisterCollation, RegisterCommitHook, RegisterRollbackHook, RegisterUpdateHook, RegisterAuthorizer, RegisterFunc, RegisterAggregator, AutoCommit, GetFilename, GetLimit, SetLimit, SetFileControlInt and SetFileControlInt64. This is go-sqlite3 commit a5779f8d (mattn/go-sqlite3#1462) with its test. Upstream applies it after 068ac771, which rewrites the body of RegisterAuthorizer; here the check is added to the current body. --- sqlite3.go | 57 +++++++++++++++++++++++++++++++++ sqlite3_test.go | 85 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 142 insertions(+) diff --git a/sqlite3.go b/sqlite3.go index a4aaf7d3..3e712655 100644 --- a/sqlite3.go +++ b/sqlite3.go @@ -676,6 +676,12 @@ func (tx *SQLiteTx) Rollback() error { return err } +// errConnClosed is returned by methods called on a connection whose +// Close has already run. SQLite dereferences the connection handle +// without checking it, so calling into it with a released handle +// crashes the process instead of reporting an error. +var errConnClosed = errors.New("sqlite connection is already closed") + // RegisterCollation makes a Go function available as a collation. // // cmp receives two UTF-8 strings, a and b. The result should be 0 if @@ -689,6 +695,9 @@ func (tx *SQLiteTx) Rollback() error { // If cmp does not obey these constraints, sqlite3's behavior is // undefined when the collation is used. func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error { + if !c.dbConnOpen() { + return errConnClosed + } handle := newHandle(c, cmp) cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) @@ -706,7 +715,12 @@ func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int // If there is an existing commit hook for this connection, it will be // removed. If callback is nil the existing hook (if any) will be removed // without creating a new one. +// +// The call is a no-op once the connection has been closed. func (c *SQLiteConn) RegisterCommitHook(callback func() int) { + if !c.dbConnOpen() { + return + } if callback == nil { C.sqlite3_commit_hook(c.db, nil, nil) } else { @@ -719,7 +733,12 @@ func (c *SQLiteConn) RegisterCommitHook(callback func() int) { // If there is an existing rollback hook for this connection, it will be // removed. If callback is nil the existing hook (if any) will be removed // without creating a new one. +// +// The call is a no-op once the connection has been closed. func (c *SQLiteConn) RegisterRollbackHook(callback func()) { + if !c.dbConnOpen() { + return + } if callback == nil { C.sqlite3_rollback_hook(c.db, nil, nil) } else { @@ -736,7 +755,12 @@ func (c *SQLiteConn) RegisterRollbackHook(callback func()) { // If there is an existing update hook for this connection, it will be // removed. If callback is nil the existing hook (if any) will be removed // without creating a new one. +// +// The call is a no-op once the connection has been closed. func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) { + if !c.dbConnOpen() { + return + } if callback == nil { C.sqlite3_update_hook(c.db, nil, nil) } else { @@ -750,7 +774,12 @@ func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64 // SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), and 1 to 3 arguments, // depending on operation. More details see: // https://www.sqlite.org/c3ref/c_alter_table.html +// +// The call is a no-op once the connection has been closed. func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, string) int) { + if !c.dbConnOpen() { + return + } if callback == nil { C.sqlite3_set_authorizer(c.db, nil, nil) } else { @@ -774,6 +803,9 @@ func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, strin // // See _example/go_custom_funcs for a detailed example. func (c *SQLiteConn) RegisterFunc(name string, impl any, pure bool) error { + if !c.dbConnOpen() { + return errConnClosed + } var fi functionInfo fi.f = reflect.ValueOf(impl) t := fi.f.Type() @@ -856,6 +888,9 @@ func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTe // // See _example/go_custom_funcs for a detailed example. func (c *SQLiteConn) RegisterAggregator(name string, impl any, pure bool) error { + if !c.dbConnOpen() { + return errConnClosed + } var ai aggInfo ai.constructor = reflect.ValueOf(impl) t := ai.constructor.Type() @@ -964,9 +999,13 @@ func (c *SQLiteConn) RegisterAggregator(name string, impl any, pure bool) error } // AutoCommit return which currently auto commit or not. +// It reports false once the connection has been closed. func (c *SQLiteConn) AutoCommit() bool { c.mu.Lock() defer c.mu.Unlock() + if c.db == nil { + return false + } return int(C.sqlite3_get_autocommit(c.db)) != 0 } @@ -2181,8 +2220,12 @@ const ( // GetFilename returns the absolute path to the file containing // the requested schema. When passed an empty string, it will // instead use the database's default schema: "main". +// It returns an empty string once the connection has been closed. // See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html func (c *SQLiteConn) GetFilename(schemaName string) string { + if !c.dbConnOpen() { + return "" + } if schemaName == "" { schemaName = "main" } @@ -2192,15 +2235,23 @@ func (c *SQLiteConn) GetFilename(schemaName string) string { } // GetLimit returns the current value of a run-time limit. +// It returns -1 once the connection has been closed. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html func (c *SQLiteConn) GetLimit(id int) int { + if !c.dbConnOpen() { + return -1 + } return int(C._sqlite3_limit(c.db, C.int(id), C.int(-1))) } // SetLimit changes the value of a run-time limits. // Then this method returns the prior value of the limit. +// It returns -1 once the connection has been closed. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html func (c *SQLiteConn) SetLimit(id int, newVal int) int { + if !c.dbConnOpen() { + return -1 + } return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal))) } @@ -2217,6 +2268,9 @@ func (c *SQLiteConn) SetLimit(id int, newVal int) int { // // See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error { + if !c.dbConnOpen() { + return errConnClosed + } if dbName == "" { dbName = "main" } @@ -2245,6 +2299,9 @@ func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error { // // See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html func (c *SQLiteConn) SetFileControlInt64(dbName string, op int, arg int64) error { + if !c.dbConnOpen() { + return errConnClosed + } if dbName == "" { dbName = "main" } diff --git a/sqlite3_test.go b/sqlite3_test.go index 4e7cf58d..b6798ea7 100644 --- a/sqlite3_test.go +++ b/sqlite3_test.go @@ -2872,3 +2872,88 @@ func benchmarkQueryParallel(b *testing.B) { } }) } + +// TestConnMethodsAfterClose exercises the *SQLiteConn methods that reach +// into SQLite with the connection handle. SQLite dereferences that handle +// without checking it, so before these guards every one of them crashed +// the process when called on a connection captured from a ConnectHook and +// used after Close. +func TestConnMethodsAfterClose(t *testing.T) { + driverName := fmt.Sprintf("sqlite3_after_close_%d", time.Now().UnixNano()) + var conn *SQLiteConn + sql.Register(driverName, &SQLiteDriver{ + ConnectHook: func(c *SQLiteConn) error { + conn = c + return nil + }, + }) + db, err := sql.Open(driverName, ":memory:") + if err != nil { + t.Fatal(err) + } + if err := db.Ping(); err != nil { + db.Close() + t.Fatal(err) + } + if err := db.Close(); err != nil { + t.Fatal(err) + } + if conn == nil { + t.Fatal("ConnectHook did not run") + } + + t.Run("errors", func(t *testing.T) { + cases := []struct { + name string + call func() error + }{ + {"RegisterCollation", func() error { + return conn.RegisterCollation("c", func(string, string) int { return 0 }) + }}, + {"RegisterFunc", func() error { + return conn.RegisterFunc("f", func() int64 { return 1 }, true) + }}, + {"RegisterAggregator", func() error { + return conn.RegisterAggregator("a", func() *sumAggregator { + var ret sumAggregator + return &ret + }, true) + }}, + {"SetFileControlInt", func() error { + return conn.SetFileControlInt("", SQLITE_FCNTL_CHUNK_SIZE, 4096) + }}, + {"SetFileControlInt64", func() error { + return conn.SetFileControlInt64("", SQLITE_FCNTL_CHUNK_SIZE, 4096) + }}, + } + for _, tc := range cases { + if err := tc.call(); !errors.Is(err, errConnClosed) { + t.Errorf("%s error = %v, want %v", tc.name, err, errConnClosed) + } + } + }) + + t.Run("noops", func(t *testing.T) { + // These have no error to report, so they must simply do nothing. + conn.RegisterCommitHook(func() int { return 0 }) + conn.RegisterRollbackHook(func() {}) + conn.RegisterUpdateHook(func(int, string, string, int64) {}) + conn.RegisterAuthorizer(func(int, string, string, string) int { return SQLITE_OK }) + conn.RegisterAuthorizer(nil) + }) + + t.Run("values", func(t *testing.T) { + if got := conn.AutoCommit(); got { + t.Errorf("AutoCommit() = %v, want false", got) + } + if got := conn.GetFilename("main"); got != "" { + t.Errorf("GetFilename() = %q, want empty", got) + } + if got := conn.GetLimit(SQLITE_LIMIT_LENGTH); got != -1 { + t.Errorf("GetLimit() = %d, want -1", got) + } + if got := conn.SetLimit(SQLITE_LIMIT_LENGTH, 1000); got != -1 { + t.Errorf("SetLimit() = %d, want -1", got) + } + }) +} From e7f88a322f55973f3c25ff9e98f0fb206be405e3 Mon Sep 17 00:00:00 2001 From: Jin Xu Date: Fri, 6 Nov 2026 09:24:49 +0800 Subject: [PATCH 2/3] Check for a closed connection without taking c.mu The guards of the previous commit call dbConnOpen, which takes c.mu. Close holds c.mu while sqlite3_close_v2 runs, and SQLite runs callbacks from there: closing a connection with an open transaction rolls it back and calls the rollback hook, and with sqlite_trace the trace callback gets a close event. A callback that calls GetFilename, GetLimit or another guarded method then waits for c.mu forever and Close never returns; before the guards the call worked. The methods already read c.db without c.mu to pass it to SQLite, so they now check it the same way: they still report a closed connection, and take no lock. AutoCommit took c.mu before the guards and is unchanged. go-sqlite3 has the same deadlock since a5779f8d. --- sqlite3.go | 28 ++++++++++++++++------------ sqlite3_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 12 deletions(-) diff --git a/sqlite3.go b/sqlite3.go index 3e712655..f474fb13 100644 --- a/sqlite3.go +++ b/sqlite3.go @@ -680,6 +680,10 @@ func (tx *SQLiteTx) Rollback() error { // Close has already run. SQLite dereferences the connection handle // without checking it, so calling into it with a released handle // crashes the process instead of reporting an error. +// +// The methods check c.db without taking c.mu, as they already pass it to +// SQLite without it: Close holds c.mu while SQLite runs callbacks such as +// the rollback hook, and these may call the methods. var errConnClosed = errors.New("sqlite connection is already closed") // RegisterCollation makes a Go function available as a collation. @@ -695,7 +699,7 @@ var errConnClosed = errors.New("sqlite connection is already closed") // If cmp does not obey these constraints, sqlite3's behavior is // undefined when the collation is used. func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error { - if !c.dbConnOpen() { + if c.db == nil { return errConnClosed } handle := newHandle(c, cmp) @@ -718,7 +722,7 @@ func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int // // The call is a no-op once the connection has been closed. func (c *SQLiteConn) RegisterCommitHook(callback func() int) { - if !c.dbConnOpen() { + if c.db == nil { return } if callback == nil { @@ -736,7 +740,7 @@ func (c *SQLiteConn) RegisterCommitHook(callback func() int) { // // The call is a no-op once the connection has been closed. func (c *SQLiteConn) RegisterRollbackHook(callback func()) { - if !c.dbConnOpen() { + if c.db == nil { return } if callback == nil { @@ -758,7 +762,7 @@ func (c *SQLiteConn) RegisterRollbackHook(callback func()) { // // The call is a no-op once the connection has been closed. func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) { - if !c.dbConnOpen() { + if c.db == nil { return } if callback == nil { @@ -777,7 +781,7 @@ func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64 // // The call is a no-op once the connection has been closed. func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, string) int) { - if !c.dbConnOpen() { + if c.db == nil { return } if callback == nil { @@ -803,7 +807,7 @@ func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, strin // // See _example/go_custom_funcs for a detailed example. func (c *SQLiteConn) RegisterFunc(name string, impl any, pure bool) error { - if !c.dbConnOpen() { + if c.db == nil { return errConnClosed } var fi functionInfo @@ -888,7 +892,7 @@ func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTe // // See _example/go_custom_funcs for a detailed example. func (c *SQLiteConn) RegisterAggregator(name string, impl any, pure bool) error { - if !c.dbConnOpen() { + if c.db == nil { return errConnClosed } var ai aggInfo @@ -2223,7 +2227,7 @@ const ( // It returns an empty string once the connection has been closed. // See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html func (c *SQLiteConn) GetFilename(schemaName string) string { - if !c.dbConnOpen() { + if c.db == nil { return "" } if schemaName == "" { @@ -2238,7 +2242,7 @@ func (c *SQLiteConn) GetFilename(schemaName string) string { // It returns -1 once the connection has been closed. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html func (c *SQLiteConn) GetLimit(id int) int { - if !c.dbConnOpen() { + if c.db == nil { return -1 } return int(C._sqlite3_limit(c.db, C.int(id), C.int(-1))) @@ -2249,7 +2253,7 @@ func (c *SQLiteConn) GetLimit(id int) int { // It returns -1 once the connection has been closed. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html func (c *SQLiteConn) SetLimit(id int, newVal int) int { - if !c.dbConnOpen() { + if c.db == nil { return -1 } return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal))) @@ -2268,7 +2272,7 @@ func (c *SQLiteConn) SetLimit(id int, newVal int) int { // // See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error { - if !c.dbConnOpen() { + if c.db == nil { return errConnClosed } if dbName == "" { @@ -2299,7 +2303,7 @@ func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error { // // See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html func (c *SQLiteConn) SetFileControlInt64(dbName string, op int, arg int64) error { - if !c.dbConnOpen() { + if c.db == nil { return errConnClosed } if dbName == "" { diff --git a/sqlite3_test.go b/sqlite3_test.go index b6798ea7..611e3a96 100644 --- a/sqlite3_test.go +++ b/sqlite3_test.go @@ -2957,3 +2957,46 @@ func TestConnMethodsAfterClose(t *testing.T) { } }) } + +// TestConnMethodsDuringClose calls a connection method from a callback +// that SQLite runs while Close closes the connection: closing a connection +// with an open transaction rolls it back and runs the rollback hook. Close +// holds c.mu meanwhile, so a method that takes c.mu never returns. +func TestConnMethodsDuringClose(t *testing.T) { + filename := TempFilename(t) + defer os.Remove(filename) + conn, err := (&SQLiteDriver{}).Open(filename) + if err != nil { + t.Fatal(err) + } + c := conn.(*SQLiteConn) + want := c.GetFilename("") + got := make(chan string, 1) + c.RegisterRollbackHook(func() { + select { + case got <- c.GetFilename(""): + default: + } + }) + if _, err := c.Exec("BEGIN; CREATE TABLE foo (id INTEGER)", nil); err != nil { + t.Fatal(err) + } + closed := make(chan error, 1) + go func() { closed <- c.Close() }() + select { + case err := <-closed: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("Close did not return") + } + select { + case name := <-got: + if name != want { + t.Errorf("GetFilename() = %q, want %q", name, want) + } + default: + t.Error("the rollback hook did not run") + } +} From efc4711a22f7ee471d7de74d5eeee1143bb99da4 Mon Sep 17 00:00:00 2001 From: Jin Xu Date: Fri, 6 Nov 2026 09:33:33 +0800 Subject: [PATCH 3/3] Check only that Close returns when a callback calls a method With sqlite_app_armor, which the full tag set of the workflow includes, SQLite refuses calls on a connection it is closing, so GetFilename returned an empty name in the rollback hook and TestConnMethodsDuringClose failed. The test is about Close returning; it no longer checks what the method returns. --- sqlite3_test.go | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/sqlite3_test.go b/sqlite3_test.go index 611e3a96..e3269b58 100644 --- a/sqlite3_test.go +++ b/sqlite3_test.go @@ -2961,20 +2961,20 @@ func TestConnMethodsAfterClose(t *testing.T) { // TestConnMethodsDuringClose calls a connection method from a callback // that SQLite runs while Close closes the connection: closing a connection // with an open transaction rolls it back and runs the rollback hook. Close -// holds c.mu meanwhile, so a method that takes c.mu never returns. +// holds c.mu meanwhile, so a method that takes c.mu never returns. What the +// method returns is not checked: with sqlite_app_armor, SQLite refuses calls +// on a connection it is closing. func TestConnMethodsDuringClose(t *testing.T) { - filename := TempFilename(t) - defer os.Remove(filename) - conn, err := (&SQLiteDriver{}).Open(filename) + conn, err := (&SQLiteDriver{}).Open(":memory:") if err != nil { t.Fatal(err) } c := conn.(*SQLiteConn) - want := c.GetFilename("") - got := make(chan string, 1) + called := make(chan struct{}, 1) c.RegisterRollbackHook(func() { + c.GetFilename("") select { - case got <- c.GetFilename(""): + case called <- struct{}{}: default: } }) @@ -2992,10 +2992,7 @@ func TestConnMethodsDuringClose(t *testing.T) { t.Fatal("Close did not return") } select { - case name := <-got: - if name != want { - t.Errorf("GetFilename() = %q, want %q", name, want) - } + case <-called: default: t.Error("the rollback hook did not run") }