Skip to content

Commit ef6a6f5

Browse files
authored
Return an error instead of crashing when a connection is used after Close (#9)
Backport the closed-connection guards from mattn#1462 without acquiring c.mu in new callback-accessible checks, avoiding a deadlock during Close. Preserve the authorizer handle ownership fix from #6. Add regressions for calls after Close and calls from a rollback callback during Close.
1 parent b38e872 commit ef6a6f5

2 files changed

Lines changed: 186 additions & 0 deletions

File tree

‎sqlite3.go‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,16 @@ func (tx *SQLiteTx) Rollback() error {
681681
return err
682682
}
683683

684+
// errConnClosed is returned by methods called on a connection whose
685+
// Close has already run. SQLite dereferences the connection handle
686+
// without checking it, so calling into it with a released handle
687+
// crashes the process instead of reporting an error.
688+
//
689+
// The methods check c.db without taking c.mu, as they already pass it to
690+
// SQLite without it: Close holds c.mu while SQLite runs callbacks such as
691+
// the rollback hook, and these may call the methods.
692+
var errConnClosed = errors.New("sqlite connection is already closed")
693+
684694
// RegisterCollation makes a Go function available as a collation.
685695
//
686696
// cmp receives two UTF-8 strings, a and b. The result should be 0 if
@@ -694,6 +704,9 @@ func (tx *SQLiteTx) Rollback() error {
694704
// If cmp does not obey these constraints, sqlite3's behavior is
695705
// undefined when the collation is used.
696706
func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error {
707+
if c.db == nil {
708+
return errConnClosed
709+
}
697710
handle := newHandle(c, cmp)
698711
cname := C.CString(name)
699712
defer C.free(unsafe.Pointer(cname))
@@ -711,7 +724,12 @@ func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int
711724
// If there is an existing commit hook for this connection, it will be
712725
// removed. If callback is nil the existing hook (if any) will be removed
713726
// without creating a new one.
727+
//
728+
// The call is a no-op once the connection has been closed.
714729
func (c *SQLiteConn) RegisterCommitHook(callback func() int) {
730+
if c.db == nil {
731+
return
732+
}
715733
if callback == nil {
716734
C.sqlite3_commit_hook(c.db, nil, nil)
717735
} else {
@@ -724,7 +742,12 @@ func (c *SQLiteConn) RegisterCommitHook(callback func() int) {
724742
// If there is an existing rollback hook for this connection, it will be
725743
// removed. If callback is nil the existing hook (if any) will be removed
726744
// without creating a new one.
745+
//
746+
// The call is a no-op once the connection has been closed.
727747
func (c *SQLiteConn) RegisterRollbackHook(callback func()) {
748+
if c.db == nil {
749+
return
750+
}
728751
if callback == nil {
729752
C.sqlite3_rollback_hook(c.db, nil, nil)
730753
} else {
@@ -741,7 +764,12 @@ func (c *SQLiteConn) RegisterRollbackHook(callback func()) {
741764
// If there is an existing update hook for this connection, it will be
742765
// removed. If callback is nil the existing hook (if any) will be removed
743766
// without creating a new one.
767+
//
768+
// The call is a no-op once the connection has been closed.
744769
func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) {
770+
if c.db == nil {
771+
return
772+
}
745773
if callback == nil {
746774
C.sqlite3_update_hook(c.db, nil, nil)
747775
} else {
@@ -755,7 +783,12 @@ func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64
755783
// SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), and 1 to 3 arguments,
756784
// depending on operation. More details see:
757785
// https://www.sqlite.org/c3ref/c_alter_table.html
786+
//
787+
// The call is a no-op once the connection has been closed.
758788
func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, string) int) {
789+
if c.db == nil {
790+
return
791+
}
759792
c.authorizerMu.Lock()
760793
defer c.authorizerMu.Unlock()
761794

@@ -790,6 +823,9 @@ func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, strin
790823
//
791824
// See _example/go_custom_funcs for a detailed example.
792825
func (c *SQLiteConn) RegisterFunc(name string, impl any, pure bool) error {
826+
if c.db == nil {
827+
return errConnClosed
828+
}
793829
var fi functionInfo
794830
fi.f = reflect.ValueOf(impl)
795831
t := fi.f.Type()
@@ -872,6 +908,9 @@ func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTe
872908
//
873909
// See _example/go_custom_funcs for a detailed example.
874910
func (c *SQLiteConn) RegisterAggregator(name string, impl any, pure bool) error {
911+
if c.db == nil {
912+
return errConnClosed
913+
}
875914
var ai aggInfo
876915
ai.constructor = reflect.ValueOf(impl)
877916
t := ai.constructor.Type()
@@ -980,9 +1019,13 @@ func (c *SQLiteConn) RegisterAggregator(name string, impl any, pure bool) error
9801019
}
9811020

9821021
// AutoCommit return which currently auto commit or not.
1022+
// It reports false once the connection has been closed.
9831023
func (c *SQLiteConn) AutoCommit() bool {
9841024
c.mu.Lock()
9851025
defer c.mu.Unlock()
1026+
if c.db == nil {
1027+
return false
1028+
}
9861029
return int(C.sqlite3_get_autocommit(c.db)) != 0
9871030
}
9881031

@@ -2201,8 +2244,12 @@ const (
22012244
// GetFilename returns the absolute path to the file containing
22022245
// the requested schema. When passed an empty string, it will
22032246
// instead use the database's default schema: "main".
2247+
// It returns an empty string once the connection has been closed.
22042248
// See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html
22052249
func (c *SQLiteConn) GetFilename(schemaName string) string {
2250+
if c.db == nil {
2251+
return ""
2252+
}
22062253
if schemaName == "" {
22072254
schemaName = "main"
22082255
}
@@ -2212,15 +2259,23 @@ func (c *SQLiteConn) GetFilename(schemaName string) string {
22122259
}
22132260

22142261
// GetLimit returns the current value of a run-time limit.
2262+
// It returns -1 once the connection has been closed.
22152263
// See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
22162264
func (c *SQLiteConn) GetLimit(id int) int {
2265+
if c.db == nil {
2266+
return -1
2267+
}
22172268
return int(C._sqlite3_limit(c.db, C.int(id), C.int(-1)))
22182269
}
22192270

22202271
// SetLimit changes the value of a run-time limits.
22212272
// Then this method returns the prior value of the limit.
2273+
// It returns -1 once the connection has been closed.
22222274
// See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
22232275
func (c *SQLiteConn) SetLimit(id int, newVal int) int {
2276+
if c.db == nil {
2277+
return -1
2278+
}
22242279
return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
22252280
}
22262281

@@ -2237,6 +2292,9 @@ func (c *SQLiteConn) SetLimit(id int, newVal int) int {
22372292
//
22382293
// See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html
22392294
func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error {
2295+
if c.db == nil {
2296+
return errConnClosed
2297+
}
22402298
if dbName == "" {
22412299
dbName = "main"
22422300
}
@@ -2265,6 +2323,9 @@ func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error {
22652323
//
22662324
// See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html
22672325
func (c *SQLiteConn) SetFileControlInt64(dbName string, op int, arg int64) error {
2326+
if c.db == nil {
2327+
return errConnClosed
2328+
}
22682329
if dbName == "" {
22692330
dbName = "main"
22702331
}

‎sqlite3_test.go‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2990,3 +2990,128 @@ func benchmarkQueryParallel(b *testing.B) {
29902990
}
29912991
})
29922992
}
2993+
2994+
// TestConnMethodsAfterClose exercises the *SQLiteConn methods that reach
2995+
// into SQLite with the connection handle. SQLite dereferences that handle
2996+
// without checking it, so before these guards every one of them crashed
2997+
// the process when called on a connection captured from a ConnectHook and
2998+
// used after Close.
2999+
func TestConnMethodsAfterClose(t *testing.T) {
3000+
driverName := fmt.Sprintf("sqlite3_after_close_%d", time.Now().UnixNano())
3001+
var conn *SQLiteConn
3002+
sql.Register(driverName, &SQLiteDriver{
3003+
ConnectHook: func(c *SQLiteConn) error {
3004+
conn = c
3005+
return nil
3006+
},
3007+
})
3008+
db, err := sql.Open(driverName, ":memory:")
3009+
if err != nil {
3010+
t.Fatal(err)
3011+
}
3012+
if err := db.Ping(); err != nil {
3013+
db.Close()
3014+
t.Fatal(err)
3015+
}
3016+
if err := db.Close(); err != nil {
3017+
t.Fatal(err)
3018+
}
3019+
if conn == nil {
3020+
t.Fatal("ConnectHook did not run")
3021+
}
3022+
3023+
t.Run("errors", func(t *testing.T) {
3024+
cases := []struct {
3025+
name string
3026+
call func() error
3027+
}{
3028+
{"RegisterCollation", func() error {
3029+
return conn.RegisterCollation("c", func(string, string) int { return 0 })
3030+
}},
3031+
{"RegisterFunc", func() error {
3032+
return conn.RegisterFunc("f", func() int64 { return 1 }, true)
3033+
}},
3034+
{"RegisterAggregator", func() error {
3035+
return conn.RegisterAggregator("a", func() *sumAggregator {
3036+
var ret sumAggregator
3037+
return &ret
3038+
}, true)
3039+
}},
3040+
{"SetFileControlInt", func() error {
3041+
return conn.SetFileControlInt("", SQLITE_FCNTL_CHUNK_SIZE, 4096)
3042+
}},
3043+
{"SetFileControlInt64", func() error {
3044+
return conn.SetFileControlInt64("", SQLITE_FCNTL_CHUNK_SIZE, 4096)
3045+
}},
3046+
}
3047+
for _, tc := range cases {
3048+
if err := tc.call(); !errors.Is(err, errConnClosed) {
3049+
t.Errorf("%s error = %v, want %v", tc.name, err, errConnClosed)
3050+
}
3051+
}
3052+
})
3053+
3054+
t.Run("noops", func(t *testing.T) {
3055+
// These have no error to report, so they must simply do nothing.
3056+
conn.RegisterCommitHook(func() int { return 0 })
3057+
conn.RegisterRollbackHook(func() {})
3058+
conn.RegisterUpdateHook(func(int, string, string, int64) {})
3059+
conn.RegisterAuthorizer(func(int, string, string, string) int { return SQLITE_OK })
3060+
conn.RegisterAuthorizer(nil)
3061+
})
3062+
3063+
t.Run("values", func(t *testing.T) {
3064+
if got := conn.AutoCommit(); got {
3065+
t.Errorf("AutoCommit() = %v, want false", got)
3066+
}
3067+
if got := conn.GetFilename("main"); got != "" {
3068+
t.Errorf("GetFilename() = %q, want empty", got)
3069+
}
3070+
if got := conn.GetLimit(SQLITE_LIMIT_LENGTH); got != -1 {
3071+
t.Errorf("GetLimit() = %d, want -1", got)
3072+
}
3073+
if got := conn.SetLimit(SQLITE_LIMIT_LENGTH, 1000); got != -1 {
3074+
t.Errorf("SetLimit() = %d, want -1", got)
3075+
}
3076+
})
3077+
}
3078+
3079+
// TestConnMethodsDuringClose calls a connection method from a callback
3080+
// that SQLite runs while Close closes the connection: closing a connection
3081+
// with an open transaction rolls it back and runs the rollback hook. Close
3082+
// holds c.mu meanwhile, so a method that takes c.mu never returns. What the
3083+
// method returns is not checked: with sqlite_app_armor, SQLite refuses calls
3084+
// on a connection it is closing.
3085+
func TestConnMethodsDuringClose(t *testing.T) {
3086+
conn, err := (&SQLiteDriver{}).Open(":memory:")
3087+
if err != nil {
3088+
t.Fatal(err)
3089+
}
3090+
c := conn.(*SQLiteConn)
3091+
called := make(chan struct{}, 1)
3092+
c.RegisterRollbackHook(func() {
3093+
c.GetFilename("")
3094+
select {
3095+
case called <- struct{}{}:
3096+
default:
3097+
}
3098+
})
3099+
if _, err := c.Exec("BEGIN; CREATE TABLE foo (id INTEGER)", nil); err != nil {
3100+
t.Fatal(err)
3101+
}
3102+
closed := make(chan error, 1)
3103+
go func() { closed <- c.Close() }()
3104+
select {
3105+
case err := <-closed:
3106+
if err != nil {
3107+
t.Fatal(err)
3108+
}
3109+
case <-time.After(10 * time.Second):
3110+
t.Fatal("Close did not return")
3111+
}
3112+
select {
3113+
case <-called:
3114+
default:
3115+
t.Error("the rollback hook did not run")
3116+
}
3117+
}

0 commit comments

Comments
 (0)