Debian Codegraph @

callback.go

raw
1 // Copyright (C) 2019 Yasuhiro Matsumoto <[email protected]>.
2 //
3 // Use of this source code is governed by an MIT-style
4 // license that can be found in the LICENSE file.
5
6 package sqlite3
7
8 // You can't export a Go function to C and have definitions in the C
9 // preamble in the same file, so we have to have callbackTrampoline in
10 // its own file. Because we need a separate file anyway, the support
11 // code for SQLite custom functions is in here.
12
13 /*
14 #ifndef USE_LIBSQLITE3
15 #include "sqlite3-binding.h"
16 #else
17 #include <sqlite3.h>
18 #endif
19 #include <stdlib.h>
20
21 void _sqlite3_result_text(sqlite3_context* ctx, const char* s, int n);
22 void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l);
23 */
24 import "C"
25
26 import (
27 "errors"
28 "fmt"
29 "math"
30 "reflect"
31 "sync"
32 "sync/atomic"
33 "unsafe"
34 )
35
36 //export callbackTrampoline
37 func callbackTrampoline(ctx *C.sqlite3_context, argc C.int, argv **C.sqlite3_value) {
38 args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:int(argc):int(argc)]
39 fi := lookupHandle(C.sqlite3_user_data(ctx)).(*functionInfo)
40 fi.Call(ctx, args)
41 }
42
43 //export stepTrampoline
44 func stepTrampoline(ctx *C.sqlite3_context, argc C.int, argv **C.sqlite3_value) {
45 args := (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.sqlite3_value)(nil))]*C.sqlite3_value)(unsafe.Pointer(argv))[:int(argc):int(argc)]
46 ai := lookupHandle(C.sqlite3_user_data(ctx)).(*aggInfo)
47 ai.Step(ctx, args)
48 }
49
50 //export doneTrampoline
51 func doneTrampoline(ctx *C.sqlite3_context) {
52 ai := lookupHandle(C.sqlite3_user_data(ctx)).(*aggInfo)
53 ai.Done(ctx)
54 }
55
56 //export compareTrampoline
57 func compareTrampoline(handlePtr unsafe.Pointer, la C.int, a *C.char, lb C.int, b *C.char) C.int {
58 cmp := lookupHandle(handlePtr).(func(string, string) int)
59 return C.int(cmp(C.GoStringN(a, la), C.GoStringN(b, lb)))
60 }
61
62 //export commitHookTrampoline
63 func commitHookTrampoline(handle unsafe.Pointer) C.int {
64 callback := lookupHandle(handle).(func() int)
65 return C.int(callback())
66 }
67
68 //export rollbackHookTrampoline
69 func rollbackHookTrampoline(handle unsafe.Pointer) {
70 callback := lookupHandle(handle).(func())
71 callback()
72 }
73
74 //export updateHookTrampoline
75 func updateHookTrampoline(handle unsafe.Pointer, op C.int, db *C.char, table *C.char, rowid int64) {
76 callback := lookupHandle(handle).(func(int, string, string, int64))
77 callback(int(op), C.GoString(db), C.GoString(table), rowid)
78 }
79
80 //export authorizerTrampoline
81 func authorizerTrampoline(handle unsafe.Pointer, op C.int, arg1 *C.char, arg2 *C.char, arg3 *C.char) C.int {
82 callback := lookupHandle(handle).(func(int, string, string, string) int)
83 return C.int(callback(int(op), C.GoString(arg1), C.GoString(arg2), C.GoString(arg3)))
84 }
85
86 //export preUpdateHookTrampoline
87 func preUpdateHookTrampoline(handle unsafe.Pointer, dbHandle uintptr, op C.int, db *C.char, table *C.char, oldrowid int64, newrowid int64) {
88 hval := lookupHandleVal(handle)
89 data := SQLitePreUpdateData{
90 Conn: hval.db,
91 Op: int(op),
92 DatabaseName: C.GoString(db),
93 TableName: C.GoString(table),
94 OldRowID: oldrowid,
95 NewRowID: newrowid,
96 }
97 callback := hval.val.(func(SQLitePreUpdateData))
98 callback(data)
99 }
100
101 // Use handles to avoid passing Go pointers to C.
102 type handleVal struct {
103 db *SQLiteConn
104 val any
105 }
106
107 var handleLock sync.Mutex
108 var handleVals atomic.Value // stores map[unsafe.Pointer]handleVal
109
110 func newHandle(db *SQLiteConn, v any) unsafe.Pointer {
111 val := handleVal{db: db, val: v}
112 var p unsafe.Pointer = C.malloc(C.size_t(1))
113 if p == nil {
114 panic("can't allocate 'cgo-pointer hack index pointer': ptr == nil")
115 }
116
117 handleLock.Lock()
118 defer handleLock.Unlock()
119
120 next := cloneHandleVals(len(loadHandleVals()) + 1)
121 next[p] = val
122 handleVals.Store(next)
123 return p
124 }
125
126 func lookupHandleVal(handle unsafe.Pointer) handleVal {
127 return loadHandleVals()[handle]
128 }
129
130 func lookupHandle(handle unsafe.Pointer) any {
131 return lookupHandleVal(handle).val
132 }
133
134 // deleteHandle releases a single handle created by newHandle. It is a no-op
135 // if the handle is unknown (e.g. already released).
136 func deleteHandle(handle unsafe.Pointer) {
137 handleLock.Lock()
138 defer handleLock.Unlock()
139
140 current := loadHandleVals()
141 if _, ok := current[handle]; !ok {
142 return
143 }
144 next := make(map[unsafe.Pointer]handleVal, len(current)-1)
145 for h, v := range current {
146 if h == handle {
147 continue
148 }
149 next[h] = v
150 }
151 handleVals.Store(next)
152 C.free(handle)
153 }
154
155 func deleteHandles(db *SQLiteConn) {
156 handleLock.Lock()
157 defer handleLock.Unlock()
158
159 current := loadHandleVals()
160 if len(current) == 0 {
161 return
162 }
163
164 next := make(map[unsafe.Pointer]handleVal, len(current))
165 for handle, val := range current {
166 if val.db == db {
167 C.free(handle)
168 continue
169 }
170 next[handle] = val
171 }
172 handleVals.Store(next)
173 }
174
175 func loadHandleVals() map[unsafe.Pointer]handleVal {
176 m, _ := handleVals.Load().(map[unsafe.Pointer]handleVal)
177 return m
178 }
179
180 func cloneHandleVals(size int) map[unsafe.Pointer]handleVal {
181 next := make(map[unsafe.Pointer]handleVal, size)
182 for handle, val := range loadHandleVals() {
183 next[handle] = val
184 }
185 return next
186 }
187
188 // This is only here so that tests can refer to it.
189 type callbackArgRaw C.sqlite3_value
190
191 type callbackArgConverter func(*C.sqlite3_value) (reflect.Value, error)
192
193 type callbackArgCast struct {
194 f callbackArgConverter
195 typ reflect.Type
196 }
197
198 func (c callbackArgCast) Run(v *C.sqlite3_value) (reflect.Value, error) {
199 val, err := c.f(v)
200 if err != nil {
201 return reflect.Value{}, err
202 }
203 if !val.Type().ConvertibleTo(c.typ) {
204 return reflect.Value{}, fmt.Errorf("cannot convert %s to %s", val.Type(), c.typ)
205 }
206 return val.Convert(c.typ), nil
207 }
208
209 func callbackArgInt64(v *C.sqlite3_value) (reflect.Value, error) {
210 if C.sqlite3_value_type(v) != C.SQLITE_INTEGER {
211 return reflect.Value{}, fmt.Errorf("argument must be an INTEGER")
212 }
213 return reflect.ValueOf(int64(C.sqlite3_value_int64(v))), nil
214 }
215
216 func callbackArgBool(v *C.sqlite3_value) (reflect.Value, error) {
217 if C.sqlite3_value_type(v) != C.SQLITE_INTEGER {
218 return reflect.Value{}, fmt.Errorf("argument must be an INTEGER")
219 }
220 i := int64(C.sqlite3_value_int64(v))
221 val := false
222 if i != 0 {
223 val = true
224 }
225 return reflect.ValueOf(val), nil
226 }
227
228 func callbackArgFloat64(v *C.sqlite3_value) (reflect.Value, error) {
229 if C.sqlite3_value_type(v) != C.SQLITE_FLOAT {
230 return reflect.Value{}, fmt.Errorf("argument must be a FLOAT")
231 }
232 return reflect.ValueOf(float64(C.sqlite3_value_double(v))), nil
233 }
234
235 func callbackArgBytes(v *C.sqlite3_value) (reflect.Value, error) {
236 switch C.sqlite3_value_type(v) {
237 case C.SQLITE_BLOB:
238 l := C.sqlite3_value_bytes(v)
239 p := C.sqlite3_value_blob(v)
240 return reflect.ValueOf(C.GoBytes(p, l)), nil
241 case C.SQLITE_TEXT:
242 l := C.sqlite3_value_bytes(v)
243 c := unsafe.Pointer(C.sqlite3_value_text(v))
244 return reflect.ValueOf(C.GoBytes(c, l)), nil
245 default:
246 return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT")
247 }
248 }
249
250 func callbackArgString(v *C.sqlite3_value) (reflect.Value, error) {
251 switch C.sqlite3_value_type(v) {
252 case C.SQLITE_BLOB:
253 p := (*C.char)(C.sqlite3_value_blob(v))
254 l := C.sqlite3_value_bytes(v)
255 return reflect.ValueOf(C.GoStringN(p, l)), nil
256 case C.SQLITE_TEXT:
257 c := (*C.char)(unsafe.Pointer(C.sqlite3_value_text(v)))
258 l := C.sqlite3_value_bytes(v)
259 return reflect.ValueOf(C.GoStringN(c, l)), nil
260 default:
261 return reflect.Value{}, fmt.Errorf("argument must be BLOB or TEXT")
262 }
263 }
264
265 func callbackArgGeneric(v *C.sqlite3_value) (reflect.Value, error) {
266 switch C.sqlite3_value_type(v) {
267 case C.SQLITE_INTEGER:
268 return callbackArgInt64(v)
269 case C.SQLITE_FLOAT:
270 return callbackArgFloat64(v)
271 case C.SQLITE_TEXT:
272 return callbackArgString(v)
273 case C.SQLITE_BLOB:
274 return callbackArgBytes(v)
275 case C.SQLITE_NULL:
276 // Interpret NULL as a nil byte slice.
277 var ret []byte
278 return reflect.ValueOf(ret), nil
279 default:
280 panic("unreachable")
281 }
282 }
283
284 // callbackArgConvert returns conv as-is when the parameter type is the
285 // canonical type conv produces, and wraps it with a cast for named types
286 // (e.g. time.Duration), which reflect.Call would otherwise panic on.
287 func callbackArgConvert(conv callbackArgConverter, typ, canonical reflect.Type) callbackArgConverter {
288 if typ == canonical {
289 return conv
290 }
291 return callbackArgCast{conv, typ}.Run
292 }
293
294 func callbackArg(typ reflect.Type) (callbackArgConverter, error) {
295 switch typ.Kind() {
296 case reflect.Interface:
297 if typ.NumMethod() != 0 {
298 return nil, errors.New("the only supported interface type is any")
299 }
300 return callbackArgGeneric, nil
301 case reflect.Slice:
302 if typ.Elem().Kind() != reflect.Uint8 {
303 return nil, errors.New("the only supported slice type is []byte")
304 }
305 return callbackArgConvert(callbackArgBytes, typ, reflect.TypeOf([]byte(nil))), nil
306 case reflect.String:
307 return callbackArgConvert(callbackArgString, typ, reflect.TypeOf("")), nil
308 case reflect.Bool:
309 return callbackArgConvert(callbackArgBool, typ, reflect.TypeOf(false)), nil
310 case reflect.Int64:
311 return callbackArgConvert(callbackArgInt64, typ, reflect.TypeOf(int64(0))), nil
312 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
313 c := callbackArgCast{callbackArgInt64, typ}
314 return c.Run, nil
315 case reflect.Float64:
316 return callbackArgConvert(callbackArgFloat64, typ, reflect.TypeOf(float64(0))), nil
317 case reflect.Float32:
318 c := callbackArgCast{callbackArgFloat64, typ}
319 return c.Run, nil
320 default:
321 return nil, fmt.Errorf("don't know how to convert to %s", typ)
322 }
323 }
324
325 func callbackConvertArgs(argv []*C.sqlite3_value, converters []callbackArgConverter, variadic callbackArgConverter) ([]reflect.Value, error) {
326 var args []reflect.Value
327
328 if len(argv) < len(converters) {
329 return nil, fmt.Errorf("function requires at least %d arguments", len(converters))
330 }
331
332 for i, arg := range argv[:len(converters)] {
333 v, err := converters[i](arg)
334 if err != nil {
335 return nil, err
336 }
337 args = append(args, v)
338 }
339
340 if variadic != nil {
341 for _, arg := range argv[len(converters):] {
342 v, err := variadic(arg)
343 if err != nil {
344 return nil, err
345 }
346 args = append(args, v)
347 }
348 }
349 return args, nil
350 }
351
352 type callbackRetConverter func(*C.sqlite3_context, reflect.Value) error
353
354 func callbackRetInteger(ctx *C.sqlite3_context, v reflect.Value) error {
355 switch v.Type().Kind() {
356 case reflect.Int64:
357 case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
358 v = v.Convert(reflect.TypeOf(int64(0)))
359 case reflect.Bool:
360 if v.Bool() {
361 v = reflect.ValueOf(int64(1))
362 } else {
363 v = reflect.ValueOf(int64(0))
364 }
365 default:
366 return fmt.Errorf("cannot convert %s to INTEGER", v.Type())
367 }
368
369 C.sqlite3_result_int64(ctx, C.sqlite3_int64(v.Int()))
370 return nil
371 }
372
373 func callbackRetFloat(ctx *C.sqlite3_context, v reflect.Value) error {
374 switch v.Type().Kind() {
375 case reflect.Float64:
376 case reflect.Float32:
377 v = v.Convert(reflect.TypeOf(float64(0)))
378 default:
379 return fmt.Errorf("cannot convert %s to FLOAT", v.Type())
380 }
381
382 C.sqlite3_result_double(ctx, C.double(v.Float()))
383 return nil
384 }
385
386 func callbackRetBlob(ctx *C.sqlite3_context, v reflect.Value) error {
387 if v.Type().Kind() != reflect.Slice || v.Type().Elem().Kind() != reflect.Uint8 {
388 return fmt.Errorf("cannot convert %s to BLOB", v.Type())
389 }
390 bs := v.Bytes()
391 if len(bs) == 0 {
392 C.sqlite3_result_null(ctx)
393 } else {
394 if i64 && len(bs) > math.MaxInt32 {
395 C.sqlite3_result_error_toobig(ctx)
396 return nil
397 }
398 C._sqlite3_result_blob(ctx, unsafe.Pointer(&bs[0]), C.int(len(bs)))
399 }
400 return nil
401 }
402
403 func callbackRetText(ctx *C.sqlite3_context, v reflect.Value) error {
404 if v.Type().Kind() != reflect.String {
405 return fmt.Errorf("cannot convert %s to TEXT", v.Type())
406 }
407 s := v.String()
408 if i64 && len(s) > math.MaxInt32 {
409 C.sqlite3_result_error_toobig(ctx)
410 return nil
411 }
412 cstr := C.CString(s)
413 C._sqlite3_result_text(ctx, cstr, C.int(len(s)))
414 return nil
415 }
416
417 func callbackRetNil(ctx *C.sqlite3_context, v reflect.Value) error {
418 return nil
419 }
420
421 func callbackRetGeneric(ctx *C.sqlite3_context, v reflect.Value) error {
422 if v.IsNil() {
423 C.sqlite3_result_null(ctx)
424 return nil
425 }
426
427 cb, err := callbackRet(v.Elem().Type())
428 if err != nil {
429 return err
430 }
431
432 return cb(ctx, v.Elem())
433 }
434
435 func callbackRet(typ reflect.Type) (callbackRetConverter, error) {
436 switch typ.Kind() {
437 case reflect.Interface:
438 errorInterface := reflect.TypeOf((*error)(nil)).Elem()
439 if typ.Implements(errorInterface) {
440 return callbackRetNil, nil
441 }
442
443 if typ.NumMethod() == 0 {
444 return callbackRetGeneric, nil
445 }
446
447 fallthrough
448 case reflect.Slice:
449 if typ.Elem().Kind() != reflect.Uint8 {
450 return nil, errors.New("the only supported slice type is []byte")
451 }
452 return callbackRetBlob, nil
453 case reflect.String:
454 return callbackRetText, nil
455 case reflect.Bool, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Int, reflect.Uint:
456 return callbackRetInteger, nil
457 case reflect.Float32, reflect.Float64:
458 return callbackRetFloat, nil
459 default:
460 return nil, fmt.Errorf("don't know how to convert to %s", typ)
461 }
462 }
463
464 func callbackError(ctx *C.sqlite3_context, err error) {
465 cstr := C.CString(err.Error())
466 defer C.free(unsafe.Pointer(cstr))
467 C.sqlite3_result_error(ctx, cstr, C.int(-1))
468 }
469
470 // Test support code. Tests are not allowed to import "C", so we can't
471 // declare any functions that use C.sqlite3_value.
472 func callbackSyntheticForTests(v reflect.Value, err error) callbackArgConverter {
473 return func(*C.sqlite3_value) (reflect.Value, error) {
474 return v, err
475 }
476 }