Debian Codegraph @

ext/jni/src/c/sqlite3-jni.c

raw
1 /*
2 ** 2023-07-21
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file implements the JNI bindings declared in
13 ** org.sqlite.jni.capi.CApi (from which sqlite3-jni.h is generated).
14 */
15
16 /*
17 ** If you found this comment by searching the code for
18 ** CallStaticObjectMethod because it appears in console output then
19 ** you're probably the victim of an OpenJDK bug:
20 **
21 ** https://bugs.openjdk.org/browse/JDK-8130659
22 **
23 ** It's known to happen with OpenJDK v8 but not with v19. It was
24 ** triggered by this code long before it made any use of
25 ** CallStaticObjectMethod().
26 */
27
28 /*
29 ** Define any SQLITE_... config defaults we want if they aren't
30 ** overridden by the builder. Please keep these alphabetized.
31 */
32
33 /**********************************************************************/
34 /* SQLITE_D... */
35 #ifndef SQLITE_DEFAULT_CACHE_SIZE
36 # define SQLITE_DEFAULT_CACHE_SIZE -16384
37 #endif
38 #if !defined(SQLITE_DEFAULT_PAGE_SIZE)
39 # define SQLITE_DEFAULT_PAGE_SIZE 8192
40 #endif
41 #ifndef SQLITE_DQS
42 # define SQLITE_DQS 0
43 #endif
44
45 /**********************************************************************/
46 /* SQLITE_ENABLE_... */
47 /*
48 ** Unconditionally enable API_ARMOR in the JNI build. It ensures that
49 ** public APIs behave predictable in the face of passing illegal NULLs
50 ** or ranges which might otherwise invoke undefined behavior.
51 */
52 #undef SQLITE_ENABLE_API_ARMOR
53 #define SQLITE_ENABLE_API_ARMOR 1
54
55 #ifndef SQLITE_ENABLE_BYTECODE_VTAB
56 # define SQLITE_ENABLE_BYTECODE_VTAB 1
57 #endif
58 #ifndef SQLITE_ENABLE_DBPAGE_VTAB
59 # define SQLITE_ENABLE_DBPAGE_VTAB 1
60 #endif
61 #ifndef SQLITE_ENABLE_DBSTAT_VTAB
62 # define SQLITE_ENABLE_DBSTAT_VTAB 1
63 #endif
64 #ifndef SQLITE_ENABLE_EXPLAIN_COMMENTS
65 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
66 #endif
67 #ifndef SQLITE_ENABLE_MATH_FUNCTIONS
68 # define SQLITE_ENABLE_MATH_FUNCTIONS 1
69 #endif
70 #ifndef SQLITE_ENABLE_OFFSET_SQL_FUNC
71 # define SQLITE_ENABLE_OFFSET_SQL_FUNC 1
72 #endif
73 #ifndef SQLITE_ENABLE_RTREE
74 # define SQLITE_ENABLE_RTREE 1
75 #endif
76 //#ifndef SQLITE_ENABLE_SESSION
77 //# define SQLITE_ENABLE_SESSION 1
78 //#endif
79 #ifndef SQLITE_ENABLE_STMTVTAB
80 # define SQLITE_ENABLE_STMTVTAB 1
81 #endif
82 //#ifndef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
83 //# define SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
84 //#endif
85
86 /**********************************************************************/
87 /* SQLITE_J... */
88 #ifdef SQLITE_JNI_FATAL_OOM
89 #if !SQLITE_JNI_FATAL_OOM
90 #undef SQLITE_JNI_FATAL_OOM
91 #endif
92 #endif
93
94 /**********************************************************************/
95 /* SQLITE_O... */
96 #ifndef SQLITE_OMIT_DEPRECATED
97 # define SQLITE_OMIT_DEPRECATED 1
98 #endif
99 #ifndef SQLITE_OMIT_LOAD_EXTENSION
100 # define SQLITE_OMIT_LOAD_EXTENSION 1
101 #endif
102 #ifndef SQLITE_OMIT_SHARED_CACHE
103 # define SQLITE_OMIT_SHARED_CACHE 1
104 #endif
105 #ifdef SQLITE_OMIT_UTF16
106 /* UTF16 is required for java */
107 # undef SQLITE_OMIT_UTF16 1
108 #endif
109
110 /**********************************************************************/
111 /* SQLITE_S... */
112 #ifndef SQLITE_STRICT_SUBTYPE
113 # define SQLITE_STRICT_SUBTYPE 1
114 #endif
115
116 /**********************************************************************/
117 /* SQLITE_T... */
118 #ifndef SQLITE_TEMP_STORE
119 # define SQLITE_TEMP_STORE 2
120 #endif
121 #ifndef SQLITE_THREADSAFE
122 # define SQLITE_THREADSAFE 1
123 #endif
124
125 /**********************************************************************/
126 /* SQLITE_USE_... */
127 #ifndef SQLITE_USE_URI
128 # define SQLITE_USE_URI 1
129 #endif
130
131
132 /*
133 ** Which sqlite3.c we're using needs to be configurable to enable
134 ** building against a custom copy, e.g. the SEE variant. We have to
135 ** include sqlite3.c, as opposed to sqlite3.h, in order to get access
136 ** to some interal details like SQLITE_MAX_... and friends. This
137 ** increases the rebuild time considerably but we need this in order
138 ** to access some internal functionality and keep the to-Java-exported
139 ** values of SQLITE_MAX_... and SQLITE_LIMIT_... in sync with the C
140 ** build.
141 */
142 #ifndef SQLITE_C
143 # define SQLITE_C sqlite3.c
144 #endif
145 #define INC__STRINGIFY_(f) #f
146 #define INC__STRINGIFY(f) INC__STRINGIFY_(f)
147 #include INC__STRINGIFY(SQLITE_C)
148 #undef INC__STRINGIFY_
149 #undef INC__STRINGIFY
150 #undef SQLITE_C
151
152 /*
153 ** End of the sqlite3 lib setup. What follows is JNI-specific.
154 */
155
156 #include "sqlite3-jni.h"
157 #include <assert.h>
158 #include <stdio.h> /* only for testing/debugging */
159 #include <stdint.h> /* intptr_t for 32-bit builds */
160
161 /* Only for debugging */
162 #define MARKER(pfexp) \
163 do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__); \
164 printf pfexp; \
165 } while(0)
166
167 /*
168 ** Creates a verbose JNI function name. Suffix must be
169 ** the JNI-mangled form of the function's name, minus the
170 ** prefix seen in this macro.
171 */
172 #define JniFuncName(Suffix) \
173 Java_org_sqlite_jni_capi_CApi_sqlite3_ ## Suffix
174
175 /* Prologue for JNI function declarations and definitions. */
176 #define JniDecl(ReturnType,Suffix) \
177 JNIEXPORT ReturnType JNICALL JniFuncName(Suffix)
178
179 /*
180 ** S3JniApi's intent is that CFunc be the C API func(s) the
181 ** being-declared JNI function is wrapping, making it easier to find
182 ** that function's JNI-side entry point. The other args are for JniDecl.
183 ** See the many examples in this file.
184 */
185 #define S3JniApi(CFunc,ReturnType,Suffix) JniDecl(ReturnType,Suffix)
186
187 /*
188 ** S3JniCast_L2P and P2L cast jlong (64-bit) to/from pointers. This is
189 ** required for casting warning-free on 32-bit builds, where we
190 ** otherwise get complaints that we're casting between different-sized
191 ** int types.
192 **
193 ** This use of intptr_t is the _only_ reason we require <stdint.h>
194 ** which, in turn, requires building with -std=c99 (or later).
195 **
196 ** See also: the notes for LongPtrGet_T.
197 */
198 #define S3JniCast_L2P(JLongAsPtr) (void*)((intptr_t)(JLongAsPtr))
199 #define S3JniCast_P2L(PTR) (jlong)((intptr_t)(PTR))
200
201 /*
202 ** Shortcuts for the first 2 parameters to all JNI bindings.
203 **
204 ** The type of the jSelf arg differs, but no docs seem to mention
205 ** this: for static methods it's of type jclass and for non-static
206 ** it's jobject. jobject actually works for all funcs, in the sense
207 ** that it compiles and runs so long as we don't use jSelf (which is
208 ** only rarely needed in this code), but to be pedantically correct we
209 ** need the proper type in the signature.
210 **
211 ** https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/design.html#jni_interface_functions_and_pointers
212 */
213 #define JniArgsEnvObj JNIEnv * env, jobject jSelf
214 #define JniArgsEnvClass JNIEnv * env, jclass jKlazz
215 /*
216 ** Helpers to account for -Xcheck:jni warnings about not having
217 ** checked for exceptions.
218 */
219 #define S3JniIfThrew if( (*env)->ExceptionCheck(env) )
220 #define S3JniExceptionClear (*env)->ExceptionClear(env)
221 #define S3JniExceptionReport (*env)->ExceptionDescribe(env)
222 #define S3JniExceptionIgnore S3JniIfThrew S3JniExceptionClear
223 #define S3JniExceptionWarnIgnore \
224 S3JniIfThrew {S3JniExceptionReport; S3JniExceptionClear;}(void)0
225 #define S3JniExceptionWarnCallbackThrew(STR) \
226 MARKER(("WARNING: " STR " MUST NOT THROW.\n")); \
227 (*env)->ExceptionDescribe(env)
228
229 /** To be used for cases where we're _really_ not expecting an
230 exception, e.g. looking up well-defined Java class members. */
231 #define S3JniExceptionIsFatal(MSG) S3JniIfThrew {\
232 S3JniExceptionReport; S3JniExceptionClear; \
233 (*env)->FatalError(env, MSG); \
234 }
235
236 /*
237 ** Declares local var env = s3jni_env(). All JNI calls involve a
238 ** JNIEnv somewhere, always named env, and many of our macros assume
239 ** env is in scope. Where it's not, but should be, use this to make it
240 ** so.
241 */
242 #define S3JniDeclLocal_env JNIEnv * const env = s3jni_env()
243
244 /* Fail fatally with an OOM message. */
245 static inline void s3jni_oom(JNIEnv * const env){
246 (*env)->FatalError(env, "SQLite3 JNI is out of memory.") /* does not return */;
247 }
248
249 /*
250 ** sqlite3_malloc() proxy which fails fatally on OOM. This should
251 ** only be used for routines which manage global state and have no
252 ** recovery strategy for OOM. For sqlite3 API which can reasonably
253 ** return SQLITE_NOMEM, s3jni_malloc() should be used instead.
254 */
255 static void * s3jni_malloc_or_die(JNIEnv * const env, size_t n){
256 void * const rv = sqlite3_malloc(n);
257 if( n && !rv ) s3jni_oom(env);
258 return rv;
259 }
260
261 /*
262 ** Works like sqlite3_malloc() unless built with SQLITE_JNI_FATAL_OOM,
263 ** in which case it calls s3jni_oom() on OOM.
264 */
265 #ifdef SQLITE_JNI_FATAL_OOM
266 #define s3jni_malloc(SIZE) s3jni_malloc_or_die(env, SIZE)
267 #else
268 #define s3jni_malloc(SIZE) sqlite3_malloc(((void)env,(SIZE)))
269 /* the ((void)env) trickery here is to avoid ^^^^^^ an otherwise
270 unused arg in at least one place. */
271 #endif
272
273 /*
274 ** Works like sqlite3_realloc() unless built with SQLITE_JNI_FATAL_OOM,
275 ** in which case it calls s3jni_oom() on OOM.
276 */
277 #ifdef SQLITE_JNI_FATAL_OOM
278 static void * s3jni_realloc_or_die(JNIEnv * const env, void * p, size_t n){
279 void * const rv = sqlite3_realloc(p, (int)n);
280 if( n && !rv ) s3jni_oom(env);
281 return rv;
282 }
283 #define s3jni_realloc(MEM,SIZE) s3jni_realloc_or_die(env, (MEM), (SIZE))
284 #else
285 #define s3jni_realloc(MEM,SIZE) sqlite3_realloc((MEM), ((void)env, (SIZE)))
286 #endif
287
288 /* Fail fatally if !EXPR. */
289 #define s3jni_oom_fatal(EXPR) if( !(EXPR) ) s3jni_oom(env)
290 /* Maybe fail fatally if !EXPR. */
291 #ifdef SQLITE_JNI_FATAL_OOM
292 #define s3jni_oom_check s3jni_oom_fatal
293 #else
294 #define s3jni_oom_check(EXPR)
295 #endif
296 //#define S3JniDb_oom(pDb,EXPR) ((EXPR) ? sqlite3OomFault(pDb) : 0)
297
298 #define s3jni_db_oom(pDb) (void)((pDb) ? ((pDb)->mallocFailed=1) : 0)
299
300 /* Helpers for Java value reference management. */
301 static jobject s3jni_ref_global(JNIEnv * const env, jobject const v){
302 jobject const rv = v ? (*env)->NewGlobalRef(env, v) : NULL;
303 s3jni_oom_fatal( v ? !!rv : 1 );
304 return rv;
305 }
306 static jobject s3jni_ref_local(JNIEnv * const env, jobject const v){
307 jobject const rv = v ? (*env)->NewLocalRef(env, v) : NULL;
308 s3jni_oom_fatal( v ? !!rv : 1 );
309 return rv;
310 }
311 static inline void s3jni_unref_global(JNIEnv * const env, jobject const v){
312 if( v ) (*env)->DeleteGlobalRef(env, v);
313 }
314 static inline void s3jni_unref_local(JNIEnv * const env, jobject const v){
315 if( v ) (*env)->DeleteLocalRef(env, v);
316 }
317 #define S3JniRefGlobal(VAR) s3jni_ref_global(env, (VAR))
318 #define S3JniRefLocal(VAR) s3jni_ref_local(env, (VAR))
319 #define S3JniUnrefGlobal(VAR) s3jni_unref_global(env, (VAR))
320 #define S3JniUnrefLocal(VAR) s3jni_unref_local(env, (VAR))
321
322 /*
323 ** Lookup key type for use with s3jni_nphop() and a cache of a
324 ** frequently-needed Java-side class reference and one or two Java
325 ** class member IDs.
326 */
327 typedef struct S3JniNphOp S3JniNphOp;
328 struct S3JniNphOp {
329 const int index /* index into S3JniGlobal.nph[] */;
330 const char * const zName /* Full Java name of the class */;
331 const char * const zMember /* Name of member property */;
332 const char * const zTypeSig /* JNI type signature of zMember */;
333 /*
334 ** klazz is a global ref to the class represented by pRef.
335 **
336 ** According to:
337 **
338 ** https://developer.ibm.com/articles/j-jni/
339 **
340 ** > ... the IDs returned for a given class don't change for the
341 ** lifetime of the JVM process. But the call to get the field or
342 ** method can require significant work in the JVM, because fields
343 ** and methods might have been inherited from superclasses, making
344 ** the JVM walk up the class hierarchy to find them. Because the
345 ** IDs are the same for a given class, you should look them up
346 ** once and then reuse them. Similarly, looking up class objects
347 ** can be expensive, so they should be cached as well.
348 */
349 jclass klazz;
350 volatile jfieldID fidValue /* NativePointerHolder.nativePointer or
351 ** OutputPointer.T.value */;
352 volatile jmethodID midCtor /* klazz's no-arg constructor. Used by
353 ** NativePointerHolder_new(). */;
354 };
355
356 /*
357 ** Cache keys for each concrete NativePointerHolder subclasses and
358 ** OutputPointer.T types. The members are to be used with s3jni_nphop()
359 ** and friends, and each one's member->index corresponds to its index
360 ** in the S3JniGlobal.nph[] array.
361 */
362 static const struct {
363 const S3JniNphOp sqlite3;
364 const S3JniNphOp sqlite3_backup;
365 const S3JniNphOp sqlite3_blob;
366 const S3JniNphOp sqlite3_context;
367 const S3JniNphOp sqlite3_stmt;
368 const S3JniNphOp sqlite3_value;
369 const S3JniNphOp OutputPointer_Bool;
370 const S3JniNphOp OutputPointer_Int32;
371 const S3JniNphOp OutputPointer_Int64;
372 const S3JniNphOp OutputPointer_sqlite3;
373 const S3JniNphOp OutputPointer_sqlite3_blob;
374 const S3JniNphOp OutputPointer_sqlite3_stmt;
375 const S3JniNphOp OutputPointer_sqlite3_value;
376 const S3JniNphOp OutputPointer_String;
377 #ifdef SQLITE_ENABLE_FTS5
378 const S3JniNphOp OutputPointer_ByteArray;
379 const S3JniNphOp Fts5Context;
380 const S3JniNphOp Fts5ExtensionApi;
381 const S3JniNphOp fts5_api;
382 const S3JniNphOp fts5_tokenizer;
383 const S3JniNphOp Fts5Tokenizer;
384 #endif
385 } S3JniNphOps = {
386 #define MkRef(INDEX, KLAZZ, MEMBER, SIG) \
387 { INDEX, "org/sqlite/jni/" KLAZZ, MEMBER, SIG }
388 /* NativePointerHolder ref */
389 #define RefN(INDEX, KLAZZ) MkRef(INDEX, KLAZZ, "nativePointer", "J")
390 /* OutputPointer.T ref */
391 #define RefO(INDEX, KLAZZ, SIG) MkRef(INDEX, KLAZZ, "value", SIG)
392 RefN(0, "capi/sqlite3"),
393 RefN(1, "capi/sqlite3_backup"),
394 RefN(2, "capi/sqlite3_blob"),
395 RefN(3, "capi/sqlite3_context"),
396 RefN(4, "capi/sqlite3_stmt"),
397 RefN(5, "capi/sqlite3_value"),
398 RefO(6, "capi/OutputPointer$Bool", "Z"),
399 RefO(7, "capi/OutputPointer$Int32", "I"),
400 RefO(8, "capi/OutputPointer$Int64", "J"),
401 RefO(9, "capi/OutputPointer$sqlite3",
402 "Lorg/sqlite/jni/capi/sqlite3;"),
403 RefO(10, "capi/OutputPointer$sqlite3_blob",
404 "Lorg/sqlite/jni/capi/sqlite3_blob;"),
405 RefO(11, "capi/OutputPointer$sqlite3_stmt",
406 "Lorg/sqlite/jni/capi/sqlite3_stmt;"),
407 RefO(12, "capi/OutputPointer$sqlite3_value",
408 "Lorg/sqlite/jni/capi/sqlite3_value;"),
409 RefO(13, "capi/OutputPointer$String", "Ljava/lang/String;"),
410 #ifdef SQLITE_ENABLE_FTS5
411 RefO(14, "capi/OutputPointer$ByteArray", "[B"),
412 RefN(15, "fts5/Fts5Context"),
413 RefN(16, "fts5/Fts5ExtensionApi"),
414 RefN(17, "fts5/fts5_api"),
415 RefN(18, "fts5/fts5_tokenizer"),
416 RefN(19, "fts5/Fts5Tokenizer")
417 #endif
418 #undef MkRef
419 #undef RefN
420 #undef RefO
421 };
422
423 #define S3JniNph(T) &S3JniNphOps.T
424
425 enum {
426 /*
427 ** Size of the NativePointerHolder cache. Need enough space for
428 ** (only) the library's NativePointerHolder and OutputPointer types,
429 ** a fixed count known at build-time. This value needs to be
430 ** exactly the number of S3JniNphOp entries in the S3JniNphOps
431 ** object.
432 */
433 S3Jni_NphCache_size = sizeof(S3JniNphOps) / sizeof(S3JniNphOp)
434 };
435
436 /*
437 ** State for binding C callbacks to Java methods.
438 */
439 typedef struct S3JniHook S3JniHook;
440 struct S3JniHook{
441 jobject jObj /* global ref to Java instance */;
442 jmethodID midCallback /* callback method. Signature depends on
443 ** jObj's type */;
444 /* We lookup the jObj.xDestroy() method as-needed for contexts which
445 ** support custom finalizers. Fundamentally we can support them for
446 ** any Java type, but we only want to expose support for them where
447 ** the C API does. */
448 jobject jExtra /* Global ref to a per-hook-type value */;
449 int doXDestroy /* If true then S3JniHook_unref() will call
450 jObj->xDestroy() if it's available. */;
451 S3JniHook * pNext /* Next entry in S3Global.hooks.aFree */;
452 };
453 /* For clean bitwise-copy init of local instances. */
454 static const S3JniHook S3JniHook_empty = {0,0,0,0,0};
455
456 /*
457 ** Per-(sqlite3*) state for various JNI bindings. This state is
458 ** allocated as needed, cleaned up in sqlite3_close(_v2)(), and
459 ** recycled when possible.
460 **
461 ** Trivia: vars and parameters of this type are often named "ps"
462 ** because this class used to have a name for which that abbreviation
463 ** made sense.
464 */
465 typedef struct S3JniDb S3JniDb;
466 struct S3JniDb {
467 sqlite3 *pDb /* The associated db handle */;
468 jobject jDb /* A global ref of the output object which gets
469 returned from sqlite3_open(_v2)(). We need this in
470 order to have an object to pass to routines like
471 sqlite3_collation_needed()'s callback, or else we
472 have to dynamically create one for that purpose,
473 which would be fine except that it would be a
474 different instance (and maybe even a different
475 class) than the one the user may expect to
476 receive. */;
477 char * zMainDbName /* Holds the string allocated on behalf of
478 SQLITE_DBCONFIG_MAINDBNAME. */;
479 struct {
480 S3JniHook busyHandler;
481 S3JniHook collationNeeded;
482 S3JniHook commit;
483 S3JniHook progress;
484 S3JniHook rollback;
485 S3JniHook trace;
486 S3JniHook update;
487 S3JniHook auth;
488 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
489 S3JniHook preUpdate;
490 #endif
491 } hooks;
492 #ifdef SQLITE_ENABLE_FTS5
493 /* FTS5-specific state */
494 struct {
495 jobject jApi /* global ref to s3jni_fts5_api_from_db() */;
496 } fts;
497 #endif
498 S3JniDb * pNext /* Next entry in SJG.perDb.aFree */;
499 };
500
501 static const char * const S3JniDb_clientdata_key = "S3JniDb";
502 #define S3JniDb_from_clientdata(pDb) \
503 (pDb ? sqlite3_get_clientdata(pDb, S3JniDb_clientdata_key) : 0)
504
505 /*
506 ** Cache for per-JNIEnv (i.e. per-thread) data.
507 **
508 ** Trivia: vars and parameters of this type are often named "jc"
509 ** because this class used to have a name for which that abbreviation
510 ** made sense.
511 */
512 typedef struct S3JniEnv S3JniEnv;
513 struct S3JniEnv {
514 JNIEnv *env /* JNIEnv in which this cache entry was created */;
515 /*
516 ** pdbOpening is used to coordinate the Java/DB connection of a
517 ** being-open()'d db in the face of auto-extensions.
518 ** Auto-extensions run before we can bind the C db to its Java
519 ** representation, but auto-extensions require that binding to pass
520 ** on to their Java-side callbacks. We handle this as follows:
521 **
522 ** - In the JNI side of sqlite3_open(), allocate the Java side of
523 ** that connection and set pdbOpening to point to that
524 ** object.
525 **
526 ** - Call sqlite3_open(), which triggers the auto-extension
527 ** handler. That handler uses pdbOpening to connect the native
528 ** db handle which it receives with pdbOpening.
529 **
530 ** - When sqlite3_open() returns, check whether pdbOpening->pDb is
531 ** NULL. If it isn't, auto-extension handling set it up. If it
532 ** is, complete the Java/C binding unless sqlite3_open() returns
533 ** a NULL db, in which case free pdbOpening.
534 */
535 S3JniDb * pdbOpening;
536 S3JniEnv * pNext /* Next entry in SJG.envCache.aHead or
537 SJG.envCache.aFree */;
538 };
539
540 /*
541 ** State for proxying sqlite3_auto_extension() in Java. This was
542 ** initially a separate class from S3JniHook and now the older name is
543 ** retained for readability in the APIs which use this, as well as for
544 ** its better code-searchability.
545 */
546 typedef S3JniHook S3JniAutoExtension;
547
548 /*
549 ** Type IDs for SQL function categories.
550 */
551 enum UDFType {
552 UDF_UNKNOWN_TYPE = 0/*for error propagation*/,
553 UDF_SCALAR,
554 UDF_AGGREGATE,
555 UDF_WINDOW
556 };
557
558 /*
559 ** State for binding Java-side UDFs.
560 */
561 typedef struct S3JniUdf S3JniUdf;
562 struct S3JniUdf {
563 jobject jObj /* SQLFunction instance */;
564 char * zFuncName /* Only for error reporting and debug logging */;
565 enum UDFType type /* UDF type */;
566 /** Method IDs for the various UDF methods. */
567 jmethodID jmidxFunc /* xFunc method (scalar) */;
568 jmethodID jmidxStep /* xStep method (aggregate/window) */;
569 jmethodID jmidxFinal /* xFinal method (aggregate/window) */;
570 jmethodID jmidxValue /* xValue method (window) */;
571 jmethodID jmidxInverse /* xInverse method (window) */;
572 S3JniUdf * pNext /* Next entry in SJG.udf.aFree. */;
573 };
574
575 #if defined(SQLITE_JNI_ENABLE_METRICS) && 0==SQLITE_JNI_ENABLE_METRICS
576 # undef SQLITE_JNI_ENABLE_METRICS
577 #endif
578
579 /*
580 ** If true, modifying S3JniGlobal.metrics is protected by a mutex,
581 ** else it isn't.
582 */
583 #ifdef SQLITE_DEBUG
584 # define S3JNI_METRICS_MUTEX SQLITE_THREADSAFE
585 #else
586 # define S3JNI_METRICS_MUTEX 0
587 #endif
588 #ifndef SQLITE_JNI_ENABLE_METRICS
589 # undef S3JNI_METRICS_MUTEX
590 # define S3JNI_METRICS_MUTEX 0
591 #endif
592
593 /*
594 ** Global state, e.g. caches and metrics.
595 */
596 typedef struct S3JniGlobalType S3JniGlobalType;
597 struct S3JniGlobalType {
598 /*
599 ** According to: https://developer.ibm.com/articles/j-jni/
600 **
601 ** > A thread can get a JNIEnv by calling GetEnv() using the JNI
602 ** invocation interface through a JavaVM object. The JavaVM object
603 ** itself can be obtained by calling the JNI GetJavaVM() method
604 ** using a JNIEnv object and can be cached and shared across
605 ** threads. Caching a copy of the JavaVM object enables any thread
606 ** with access to the cached object to get access to its own
607 ** JNIEnv when necessary.
608 */
609 JavaVM * jvm;
610 /*
611 ** Global mutex. It must not be used for anything which might call
612 ** back into the JNI layer.
613 */
614 sqlite3_mutex * mutex;
615 /*
616 ** Cache of references to Java classes and method IDs for
617 ** NativePointerHolder subclasses and OutputPointer.T types.
618 */
619 struct {
620 S3JniNphOp list[S3Jni_NphCache_size];
621 sqlite3_mutex * mutex; /* mutex for this->list */
622 volatile void const * locker; /* sanity-checking-only context object
623 for this->mutex */
624 } nph;
625 /*
626 ** Cache of per-thread state.
627 */
628 struct {
629 S3JniEnv * aHead /* Linked list of in-use instances */;
630 S3JniEnv * aFree /* Linked list of free instances */;
631 sqlite3_mutex * mutex /* mutex for aHead and aFree. */;
632 volatile void const * locker /* env mutex is held on this
633 object's behalf. Used only for
634 sanity checking. */;
635 } envCache;
636 /*
637 ** Per-db state. This can move into the core library once we can tie
638 ** client-defined state to db handles there.
639 */
640 struct {
641 S3JniDb * aFree /* Linked list of free instances */;
642 sqlite3_mutex * mutex /* mutex for aHead and aFree */;
643 volatile void const * locker
644 /* perDb mutex is held on this object's behalf. Used only for
645 sanity checking. Note that the mutex is at the class level, not
646 instance level. */;
647 } perDb;
648 struct {
649 S3JniUdf * aFree /* Head of the free-item list. Guarded by global
650 mutex. */;
651 } udf;
652 /*
653 ** Refs to global classes and methods. Obtained during static init
654 ** and never released.
655 */
656 struct {
657 jclass cLong /* global ref to java.lang.Long */;
658 jclass cString /* global ref to java.lang.String */;
659 jobject oCharsetUtf8 /* global ref to StandardCharset.UTF_8 */;
660 jmethodID ctorLong1 /* the Long(long) constructor */;
661 jmethodID ctorStringBA /* the String(byte[],Charset) constructor */;
662 jmethodID stringGetBytes /* the String.getBytes(Charset) method */;
663
664 /*
665 ByteBuffer may or may not be supported via JNI on any given
666 platform:
667
668 https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#nio_support
669
670 We only store a ref to byteBuffer.klazz if JNI support for
671 ByteBuffer is available (which we determine during static init).
672 */
673 struct {
674 jclass klazz /* global ref to java.nio.ByteBuffer */;
675 jmethodID midAlloc /* ByteBuffer.allocateDirect() */;
676 jmethodID midLimit /* ByteBuffer.limit() */;
677 } byteBuffer;
678 } g;
679 /*
680 ** The list of Java-side auto-extensions
681 ** (org.sqlite.jni.capi.AutoExtensionCallback objects).
682 */
683 struct {
684 S3JniAutoExtension *aExt /* The auto-extension list. It is
685 maintained such that all active
686 entries are in the first contiguous
687 nExt array elements. */;
688 int nAlloc /* number of entries allocated for aExt,
689 as distinct from the number of active
690 entries. */;
691 int nExt /* number of active entries in aExt, all in the
692 first nExt'th array elements. */;
693 sqlite3_mutex * mutex /* mutex for manipulation/traversal of aExt */;
694 volatile const void * locker /* object on whose behalf the mutex
695 is held. Only for sanity checking
696 in debug builds. */;
697 } autoExt;
698 #ifdef SQLITE_ENABLE_FTS5
699 struct {
700 volatile jobject jExt /* Global ref to Java singleton for the
701 Fts5ExtensionApi instance. */;
702 struct {
703 jfieldID fidA /* Fts5Phrase::a member */;
704 jfieldID fidB /* Fts5Phrase::b member */;
705 } jPhraseIter;
706 } fts5;
707 #endif
708 struct {
709 #ifdef SQLITE_ENABLE_SQLLOG
710 S3JniHook sqllog /* sqlite3_config(SQLITE_CONFIG_SQLLOG) callback */;
711 #endif
712 S3JniHook configlog /* sqlite3_config(SQLITE_CONFIG_LOG) callback */;
713 S3JniHook * aFree /* free-item list, for recycling. */;
714 sqlite3_mutex * mutex /* mutex for aFree */;
715 volatile const void * locker /* object on whose behalf the mutex
716 is held. Only for sanity checking
717 in debug builds. */;
718 } hook;
719 #ifdef SQLITE_JNI_ENABLE_METRICS
720 /* Internal metrics. */
721 struct {
722 volatile unsigned nEnvHit;
723 volatile unsigned nEnvMiss;
724 volatile unsigned nEnvAlloc;
725 volatile unsigned nMutexEnv /* number of times envCache.mutex was entered for
726 a S3JniEnv operation. */;
727 volatile unsigned nMutexNph /* number of times SJG.mutex was entered */;
728 volatile unsigned nMutexHook /* number of times SJG.mutex hooks.was entered */;
729 volatile unsigned nMutexPerDb /* number of times perDb.mutex was entered */;
730 volatile unsigned nMutexAutoExt /* number of times autoExt.mutex was entered */;
731 volatile unsigned nMutexGlobal /* number of times global mutex was entered. */;
732 volatile unsigned nMutexUdf /* number of times global mutex was entered
733 for UDFs. */;
734 volatile unsigned nDestroy /* xDestroy() calls across all types */;
735 volatile unsigned nPdbAlloc /* Number of S3JniDb alloced. */;
736 volatile unsigned nPdbRecycled /* Number of S3JniDb reused. */;
737 volatile unsigned nUdfAlloc /* Number of S3JniUdf alloced. */;
738 volatile unsigned nUdfRecycled /* Number of S3JniUdf reused. */;
739 volatile unsigned nHookAlloc /* Number of S3JniHook alloced. */;
740 volatile unsigned nHookRecycled /* Number of S3JniHook reused. */;
741 struct {
742 /* Number of calls for each type of UDF callback. */
743 volatile unsigned nFunc;
744 volatile unsigned nStep;
745 volatile unsigned nFinal;
746 volatile unsigned nValue;
747 volatile unsigned nInverse;
748 } udf;
749 unsigned nMetrics /* Total number of mutex-locked
750 metrics increments. */;
751 #if S3JNI_METRICS_MUTEX
752 sqlite3_mutex * mutex;
753 #endif
754 } metrics;
755 #endif /* SQLITE_JNI_ENABLE_METRICS */
756 };
757 static S3JniGlobalType S3JniGlobal = {};
758 #define SJG S3JniGlobal
759
760 /* Increments *p, possibly protected by a mutex. */
761 #ifndef SQLITE_JNI_ENABLE_METRICS
762 #define s3jni_incr(PTR)
763 #elif S3JNI_METRICS_MUTEX
764 static void s3jni_incr( volatile unsigned int * const p ){
765 sqlite3_mutex_enter(SJG.metrics.mutex);
766 ++SJG.metrics.nMetrics;
767 ++(*p);
768 sqlite3_mutex_leave(SJG.metrics.mutex);
769 }
770 #else
771 #define s3jni_incr(PTR) ++(*(PTR))
772 #endif
773
774 /* Helpers for working with specific mutexes. */
775 #if SQLITE_THREADSAFE
776 #define s3jni_mutex_enter2(M, Metric) \
777 sqlite3_mutex_enter( M ); \
778 s3jni_incr( &SJG.metrics.Metric )
779 #define s3jni_mutex_leave2(M) \
780 sqlite3_mutex_leave( M )
781
782 #define s3jni_mutex_enter(M, L, Metric) \
783 assert( (void*)env != (void*)L && "Invalid use of " #L); \
784 s3jni_mutex_enter2( M, Metric ); \
785 L = env
786 #define s3jni_mutex_leave(M, L) \
787 assert( (void*)env == (void*)L && "Invalid use of " #L); \
788 L = 0; \
789 s3jni_mutex_leave2( M )
790
791 #define S3JniEnv_mutex_assertLocked \
792 assert( 0 != SJG.envCache.locker && "Misuse of S3JniGlobal.envCache.mutex" )
793 #define S3JniEnv_mutex_assertLocker \
794 assert( (env) == SJG.envCache.locker && "Misuse of S3JniGlobal.envCache.mutex" )
795 #define S3JniEnv_mutex_assertNotLocker \
796 assert( (env) != SJG.envCache.locker && "Misuse of S3JniGlobal.envCache.mutex" )
797
798 #define S3JniEnv_mutex_enter \
799 s3jni_mutex_enter( SJG.envCache.mutex, SJG.envCache.locker, nMutexEnv )
800 #define S3JniEnv_mutex_leave \
801 s3jni_mutex_leave( SJG.envCache.mutex, SJG.envCache.locker )
802
803 #define S3JniAutoExt_mutex_enter \
804 s3jni_mutex_enter( SJG.autoExt.mutex, SJG.autoExt.locker, nMutexAutoExt )
805 #define S3JniAutoExt_mutex_leave \
806 s3jni_mutex_leave( SJG.autoExt.mutex, SJG.autoExt.locker )
807 #define S3JniAutoExt_mutex_assertLocker \
808 assert( env == SJG.autoExt.locker && "Misuse of S3JniGlobal.autoExt.mutex" )
809
810 #define S3JniGlobal_mutex_enter \
811 s3jni_mutex_enter2( SJG.mutex, nMutexGlobal )
812 #define S3JniGlobal_mutex_leave \
813 s3jni_mutex_leave2( SJG.mutex )
814
815 #define S3JniHook_mutex_enter \
816 s3jni_mutex_enter( SJG.hook.mutex, SJG.hook.locker, nMutexHook )
817 #define S3JniHook_mutex_leave \
818 s3jni_mutex_leave( SJG.hook.mutex, SJG.hook.locker )
819
820 #define S3JniNph_mutex_enter \
821 s3jni_mutex_enter( SJG.nph.mutex, SJG.nph.locker, nMutexNph )
822 #define S3JniNph_mutex_leave \
823 s3jni_mutex_leave( SJG.nph.mutex, SJG.nph.locker )
824
825 #define S3JniDb_mutex_assertLocker \
826 assert( (env) == SJG.perDb.locker && "Misuse of S3JniGlobal.perDb.mutex" )
827 #define S3JniDb_mutex_enter \
828 s3jni_mutex_enter( SJG.perDb.mutex, SJG.perDb.locker, nMutexPerDb )
829 #define S3JniDb_mutex_leave \
830 s3jni_mutex_leave( SJG.perDb.mutex, SJG.perDb.locker )
831
832 #else /* SQLITE_THREADSAFE==0 */
833 #define S3JniAutoExt_mutex_assertLocker
834 #define S3JniAutoExt_mutex_enter
835 #define S3JniAutoExt_mutex_leave
836 #define S3JniDb_mutex_assertLocker
837 #define S3JniDb_mutex_enter
838 #define S3JniDb_mutex_leave
839 #define S3JniEnv_mutex_assertLocked
840 #define S3JniEnv_mutex_assertLocker
841 #define S3JniEnv_mutex_assertNotLocker
842 #define S3JniEnv_mutex_enter
843 #define S3JniEnv_mutex_leave
844 #define S3JniGlobal_mutex_enter
845 #define S3JniGlobal_mutex_leave
846 #define S3JniHook_mutex_enter
847 #define S3JniHook_mutex_leave
848 #define S3JniNph_mutex_enter
849 #define S3JniNph_mutex_leave
850 #endif
851
852 /* Helpers for jstring and jbyteArray. */
853 static const char * s3jni__jstring_to_mutf8(JNIEnv * const env, jstring v ){
854 const char *z = v ? (*env)->GetStringUTFChars(env, v, NULL) : 0;
855 s3jni_oom_check( v ? !!z : !z );
856 return z;
857 }
858
859 #define s3jni_jstring_to_mutf8(ARG) s3jni__jstring_to_mutf8(env, (ARG))
860 #define s3jni_mutf8_release(ARG,VAR) if( VAR ) (*env)->ReleaseStringUTFChars(env, ARG, VAR)
861
862 /*
863 ** If jBA is not NULL then its GetByteArrayElements() value is
864 ** returned. If jBA is not NULL and nBA is not NULL then *nBA is set
865 ** to the GetArrayLength() of jBA. If GetByteArrayElements() requires
866 ** an allocation and that allocation fails then this function either
867 ** fails fatally or returns 0, depending on build-time options.
868 */
869 static jbyte * s3jni__jbyteArray_bytes2(JNIEnv * const env, jbyteArray jBA, jsize * nBA ){
870 jbyte * const rv = jBA ? (*env)->GetByteArrayElements(env, jBA, NULL) : 0;
871 s3jni_oom_check( jBA ? !!rv : 1 );
872 if( jBA && nBA ) *nBA = (*env)->GetArrayLength(env, jBA);
873 return rv;
874 }
875
876 #define s3jni_jbyteArray_bytes2(jByteArray,ptrToSz) \
877 s3jni__jbyteArray_bytes2(env, (jByteArray), (ptrToSz))
878 #define s3jni_jbyteArray_bytes(jByteArray) s3jni__jbyteArray_bytes2(env, (jByteArray), 0)
879 #define s3jni_jbyteArray_release(jByteArray,jBytes) \
880 if( jBytes ) (*env)->ReleaseByteArrayElements(env, jByteArray, jBytes, JNI_ABORT)
881 #define s3jni_jbyteArray_commit(jByteArray,jBytes) \
882 if( jBytes ) (*env)->ReleaseByteArrayElements(env, jByteArray, jBytes, JNI_COMMIT)
883
884 /*
885 ** If jbb is-a java.nio.Buffer object and the JNI environment supports
886 ** it, *pBuf is set to the buffer's memory and *pN is set to its
887 ** limit() (as opposed to its capacity()). If jbb is NULL, not a
888 ** Buffer, or the JNI environment does not support that operation,
889 ** *pBuf is set to 0 and *pN is set to 0.
890 **
891 ** Note that the length of the buffer can be larger than SQLITE_LIMIT
892 ** but this function does not know what byte range of the buffer is
893 ** required so cannot check for that violation. The caller is required
894 ** to ensure that any to-be-bind()ed range fits within SQLITE_LIMIT.
895 **
896 ** Sidebar: it is unfortunate that we cannot get ByteBuffer.limit()
897 ** via a JNI method like we can for ByteBuffer.capacity(). We instead
898 ** have to call back into Java to get the limit(). Depending on how
899 ** the ByteBuffer is used, the limit and capacity might be the same,
900 ** but when reusing a buffer, the limit may well change whereas the
901 ** capacity is fixed. The problem with, e.g., read()ing blob data to a
902 ** ByteBuffer's memory based on its capacity is that Java-level code
903 ** is restricted to accessing the range specified in
904 ** ByteBuffer.limit(). If we were to honor only the capacity, we
905 ** could end up writing to, or reading from, parts of a ByteBuffer
906 ** which client code itself cannot access without explicitly modifying
907 ** the limit. The penalty we pay for this correctness is that we must
908 ** call into Java to get the limit() of every ByteBuffer we work with.
909 **
910 ** An alternative to having to call into ByteBuffer.limit() from here
911 ** would be to add private native impls of all ByteBuffer-using
912 ** methods, each of which adds a jint parameter which _must_ be set to
913 ** theBuffer.limit() by public Java APIs which use those private impls
914 ** to do the real work.
915 */
916 static void s3jni__get_nio_buffer(JNIEnv * const env, jobject jbb, void **pBuf, jint * pN ){
917 *pBuf = 0;
918 *pN = 0;
919 if( jbb ){
920 *pBuf = (*env)->GetDirectBufferAddress(env, jbb);
921 if( *pBuf ){
922 /*
923 ** Maintenance reminder: do not use
924 ** (*env)->GetDirectBufferCapacity(env,jbb), even though it
925 ** would be much faster, for reasons explained in this
926 ** function's comments.
927 */
928 *pN = (*env)->CallIntMethod(env, jbb, SJG.g.byteBuffer.midLimit);
929 S3JniExceptionIsFatal("Error calling ByteBuffer.limit() method.");
930 }
931 }
932 }
933 #define s3jni_get_nio_buffer(JOBJ,vpOut,jpOut) \
934 s3jni__get_nio_buffer(env,(JOBJ),(vpOut),(jpOut))
935
936 /*
937 ** Returns the current JNIEnv object. Fails fatally if it cannot find
938 ** the object.
939 */
940 static JNIEnv * s3jni_env(void){
941 JNIEnv * env = 0;
942 if( (*SJG.jvm)->GetEnv(SJG.jvm, (void **)&env,
943 JNI_VERSION_1_8) ){
944 fprintf(stderr, "Fatal error: cannot get current JNIEnv.\n");
945 abort();
946 }
947 return env;
948 }
949
950 /*
951 ** Fetches the S3JniGlobal.envCache row for the given env, allocing a
952 ** row if needed. When a row is allocated, its state is initialized
953 ** insofar as possible. Calls (*env)->FatalError() if allocation of an
954 ** entry fails. That's hypothetically possible but "shouldn't happen."
955 */
956 static S3JniEnv * S3JniEnv__get(JNIEnv * const env){
957 struct S3JniEnv * row;
958 S3JniEnv_mutex_enter;
959 row = SJG.envCache.aHead;
960 for( ; row; row = row->pNext ){
961 if( row->env == env ){
962 s3jni_incr( &SJG.metrics.nEnvHit );
963 S3JniEnv_mutex_leave;
964 return row;
965 }
966 }
967 s3jni_incr( &SJG.metrics.nEnvMiss );
968 row = SJG.envCache.aFree;
969 if( row ){
970 SJG.envCache.aFree = row->pNext;
971 }else{
972 row = s3jni_malloc_or_die(env, sizeof(*row));
973 s3jni_incr( &SJG.metrics.nEnvAlloc );
974 }
975 memset(row, 0, sizeof(*row));
976 row->pNext = SJG.envCache.aHead;
977 SJG.envCache.aHead = row;
978 row->env = env;
979
980 S3JniEnv_mutex_leave;
981 return row;
982 }
983
984 #define S3JniEnv_get() S3JniEnv__get(env)
985
986 /*
987 ** This function is NOT part of the sqlite3 public API. It is strictly
988 ** for use by the sqlite project's own Java/JNI bindings.
989 **
990 ** For purposes of certain hand-crafted JNI function bindings, we
991 ** need a way of reporting errors which is consistent with the rest of
992 ** the C API, as opposed to throwing Java exceptions. To that end, this
993 ** internal-use-only function is a thin proxy around
994 ** sqlite3ErrorWithMessage(). The intent is that it only be used from
995 ** JNI bindings such as sqlite3_prepare_v2/v3(), and definitely not
996 ** from client code.
997 **
998 ** Returns err_code.
999 */
1000 static int s3jni_db_error(sqlite3* const db, int err_code,
1001 const char * const zMsg){
1002 if( db!=0 ){
1003 if( 0==zMsg ){
1004 sqlite3Error(db, err_code);
1005 }else{
1006 const int nMsg = sqlite3Strlen30(zMsg);
1007 sqlite3_mutex_enter(sqlite3_db_mutex(db));
1008 sqlite3ErrorWithMsg(db, err_code, "%.*s", nMsg, zMsg);
1009 sqlite3_mutex_leave(sqlite3_db_mutex(db));
1010 }
1011 }
1012 return err_code;
1013 }
1014
1015 /*
1016 ** Creates a new jByteArray of length nP, copies p's contents into it,
1017 ** and returns that byte array (NULL on OOM unless fail-fast alloc
1018 ** errors are enabled). p may be NULL, in which case the array is
1019 ** created but no bytes are filled.
1020 */
1021 static jbyteArray s3jni__new_jbyteArray(JNIEnv * const env,
1022 const void * const p, int nP){
1023 jbyteArray jba = (*env)->NewByteArray(env, (jint)nP);
1024
1025 s3jni_oom_check( jba );
1026 if( jba && p ){
1027 (*env)->SetByteArrayRegion(env, jba, 0, (jint)nP, (const jbyte*)p);
1028 }
1029 return jba;
1030 }
1031
1032 #define s3jni_new_jbyteArray(P,n) s3jni__new_jbyteArray(env, P, n)
1033
1034
1035 /*
1036 ** Uses the java.lang.String(byte[],Charset) constructor to create a
1037 ** new String from UTF-8 string z. n is the number of bytes to
1038 ** copy. If n<0 then sqlite3Strlen30() is used to calculate it.
1039 **
1040 ** Returns NULL if z is NULL or on OOM, else returns a new jstring
1041 ** owned by the caller.
1042 **
1043 ** Sidebar: this is a painfully inefficient way to convert from
1044 ** standard UTF-8 to a Java string, but JNI offers only algorithms for
1045 ** working with MUTF-8, not UTF-8.
1046 */
1047 static jstring s3jni__utf8_to_jstring(JNIEnv * const env,
1048 const char * const z, int n){
1049 jstring rv = NULL;
1050 if( 0==n || (n<0 && z && !z[0]) ){
1051 /* Fast-track the empty-string case via the MUTF-8 API. We could
1052 hypothetically do this for any strings where n<4 and z is
1053 NUL-terminated and none of z[0..3] are NUL bytes. */
1054 rv = (*env)->NewStringUTF(env, "");
1055 s3jni_oom_check( rv );
1056 }else if( z ){
1057 jbyteArray jba;
1058 if( n<0 ) n = sqlite3Strlen30(z);
1059 jba = s3jni_new_jbyteArray((unsigned const char *)z, n);
1060 if( jba ){
1061 rv = (*env)->NewObject(env, SJG.g.cString, SJG.g.ctorStringBA,
1062 jba, SJG.g.oCharsetUtf8);
1063 S3JniIfThrew{
1064 S3JniExceptionReport;
1065 S3JniExceptionClear;
1066 }
1067 S3JniUnrefLocal(jba);
1068 }
1069 s3jni_oom_check( rv );
1070 }
1071 return rv;
1072 }
1073 #define s3jni_utf8_to_jstring(CStr,n) s3jni__utf8_to_jstring(env, CStr, n)
1074
1075 /*
1076 ** Converts the given java.lang.String object into a NUL-terminated
1077 ** UTF-8 C-string by calling jstr.getBytes(StandardCharset.UTF_8).
1078 ** Returns NULL if jstr is NULL or on allocation error. If jstr is not
1079 ** NULL and nLen is not NULL then nLen is set to the length of the
1080 ** returned string, not including the terminating NUL. If jstr is not
1081 ** NULL and it returns NULL, this indicates an allocation error. In
1082 ** that case, if nLen is not NULL then it is either set to 0 (if
1083 ** fetching of jstr's bytes fails to allocate) or set to what would
1084 ** have been the length of the string had C-string allocation
1085 ** succeeded.
1086 **
1087 ** The returned memory is allocated from sqlite3_malloc() and
1088 ** ownership is transferred to the caller.
1089 */
1090 static char * s3jni__jstring_to_utf8(JNIEnv * const env,
1091 jstring jstr, int *nLen){
1092 jbyteArray jba;
1093 jsize nBA;
1094 char *rv;
1095
1096 if( !jstr ) return 0;
1097 jba = (*env)->CallObjectMethod(env, jstr, SJG.g.stringGetBytes,
1098 SJG.g.oCharsetUtf8);
1099
1100 if( (*env)->ExceptionCheck(env) || !jba
1101 /* order of these checks is significant for -Xlint:jni */ ) {
1102 S3JniExceptionReport;
1103 s3jni_oom_check( jba );
1104 if( nLen ) *nLen = 0;
1105 return 0;
1106 }
1107 nBA = (*env)->GetArrayLength(env, jba);
1108 if( nLen ) *nLen = (int)nBA;
1109 rv = s3jni_malloc( nBA + 1 );
1110 if( rv ){
1111 (*env)->GetByteArrayRegion(env, jba, 0, nBA, (jbyte*)rv);
1112 rv[nBA] = 0;
1113 }
1114 S3JniUnrefLocal(jba);
1115 return rv;
1116 }
1117 #define s3jni_jstring_to_utf8(JStr,n) s3jni__jstring_to_utf8(env, JStr, n)
1118
1119 /*
1120 ** Expects to be passed a pointer from sqlite3_column_text16() or
1121 ** sqlite3_value_text16() and a byte-length value from
1122 ** sqlite3_column_bytes16() or sqlite3_value_bytes16(). It creates a
1123 ** Java String of exactly half that character length, returning NULL
1124 ** if !p or (*env)->NewString() fails.
1125 */
1126 static jstring s3jni_text16_to_jstring(JNIEnv * const env, const void * const p, int nP){
1127 jstring const rv = p
1128 ? (*env)->NewString(env, (const jchar *)p, (jsize)(nP/2))
1129 : NULL;
1130 s3jni_oom_check( p ? !!rv : 1 );
1131 return rv;
1132 }
1133
1134 /*
1135 ** Creates a new ByteBuffer instance with a capacity of n. assert()s
1136 ** that SJG.g.byteBuffer.klazz is not 0 and n>0.
1137 */
1138 static jobject s3jni__new_ByteBuffer(JNIEnv * const env, int n){
1139 jobject rv = 0;
1140 assert( SJG.g.byteBuffer.klazz );
1141 assert( SJG.g.byteBuffer.midAlloc );
1142 assert( n > 0 );
1143 rv = (*env)->CallStaticObjectMethod(env, SJG.g.byteBuffer.klazz,
1144 SJG.g.byteBuffer.midAlloc, (jint)n);
1145 S3JniIfThrew {
1146 S3JniExceptionReport;
1147 S3JniExceptionClear;
1148 }
1149 s3jni_oom_check( rv );
1150 return rv;
1151 }
1152
1153 /*
1154 ** If n>0 and sqlite3_jni_supports_nio() is true then this creates a
1155 ** new ByteBuffer object and copies n bytes from p to it. Returns NULL
1156 ** if n is 0, sqlite3_jni_supports_nio() is false, or on allocation
1157 ** error (unless fatal alloc failures are enabled).
1158 */
1159 static jobject s3jni__blob_to_ByteBuffer(JNIEnv * const env,
1160 const void * p, int n){
1161 jobject rv = NULL;
1162 assert( n >= 0 );
1163 if( 0==n || !SJG.g.byteBuffer.klazz ){
1164 return NULL;
1165 }
1166 rv = s3jni__new_ByteBuffer(env, n);
1167 if( rv ){
1168 void * tgt = (*env)->GetDirectBufferAddress(env, rv);
1169 memcpy(tgt, p, (size_t)n);
1170 }
1171 return rv;
1172 }
1173
1174
1175 /*
1176 ** Requires jx to be a Throwable. Calls its toString() method and
1177 ** returns its value converted to a UTF-8 string. The caller owns the
1178 ** returned string and must eventually sqlite3_free() it. Returns 0
1179 ** if there is a problem fetching the info or on OOM.
1180 **
1181 ** Design note: we use toString() instead of getMessage() because the
1182 ** former includes the exception type's name:
1183 **
1184 ** Exception e = new RuntimeException("Hi");
1185 ** System.out.println(e.toString()); // java.lang.RuntimeException: Hi
1186 ** System.out.println(e.getMessage()); // Hi
1187 */
1188 static char * s3jni_exception_error_msg(JNIEnv * const env, jthrowable jx){
1189 jmethodID mid;
1190 jstring msg;
1191 char * zMsg;
1192 jclass const klazz = (*env)->GetObjectClass(env, jx);
1193 mid = (*env)->GetMethodID(env, klazz, "toString", "()Ljava/lang/String;");
1194 S3JniUnrefLocal(klazz);
1195 S3JniIfThrew{
1196 S3JniExceptionReport;
1197 S3JniExceptionClear;
1198 return 0;
1199 }
1200 msg = (*env)->CallObjectMethod(env, jx, mid);
1201 S3JniIfThrew{
1202 S3JniExceptionReport;
1203 S3JniExceptionClear;
1204 return 0;
1205 }
1206 zMsg = s3jni_jstring_to_utf8( msg, 0);
1207 S3JniUnrefLocal(msg);
1208 return zMsg;
1209 }
1210
1211 /*
1212 ** Extracts env's current exception, sets ps->pDb's error message to
1213 ** its message string, and clears the exception. If errCode is non-0,
1214 ** it is used as-is, else SQLITE_ERROR is assumed. If there's a
1215 ** problem extracting the exception's message, it's treated as
1216 ** non-fatal and zDfltMsg is used in its place.
1217 **
1218 ** Locks the global S3JniDb mutex.
1219 **
1220 ** This must only be called if a JNI exception is pending.
1221 **
1222 ** Returns errCode unless it is 0, in which case SQLITE_ERROR is
1223 ** returned.
1224 */
1225 static int s3jni__db_exception(JNIEnv * const env, sqlite3 * const pDb,
1226 int errCode, const char *zDfltMsg){
1227 jthrowable const ex = (*env)->ExceptionOccurred(env);
1228
1229 if( 0==errCode ) errCode = SQLITE_ERROR;
1230 if( ex ){
1231 char * zMsg;
1232 S3JniExceptionClear;
1233 zMsg = s3jni_exception_error_msg(env, ex);
1234 s3jni_db_error(pDb, errCode, zMsg ? zMsg : zDfltMsg);
1235 sqlite3_free(zMsg);
1236 S3JniUnrefLocal(ex);
1237 }else if( zDfltMsg ){
1238 s3jni_db_error(pDb, errCode, zDfltMsg);
1239 }
1240 return errCode;
1241 }
1242 #define s3jni_db_exception(pDb,ERRCODE,DFLTMSG) \
1243 s3jni__db_exception(env, (pDb), (ERRCODE), (DFLTMSG) )
1244
1245 /*
1246 ** Extracts the (void xDestroy()) method from jObj and applies it to
1247 ** jObj. If jObj is NULL, this is a no-op. The lack of an xDestroy()
1248 ** method is silently ignored. Any exceptions thrown by xDestroy()
1249 ** trigger a warning to stdout or stderr and then the exception is
1250 ** suppressed.
1251 */
1252 static void s3jni__call_xDestroy(JNIEnv * const env, jobject jObj){
1253 if( jObj ){
1254 jclass const klazz = (*env)->GetObjectClass(env, jObj);
1255 jmethodID method = (*env)->GetMethodID(env, klazz, "xDestroy", "()V");
1256
1257 S3JniUnrefLocal(klazz);
1258 if( method ){
1259 s3jni_incr( &SJG.metrics.nDestroy );
1260 (*env)->CallVoidMethod(env, jObj, method);
1261 S3JniIfThrew{
1262 S3JniExceptionWarnCallbackThrew("xDestroy() callback");
1263 S3JniExceptionClear;
1264 }
1265 }else{
1266 /* Non-fatal. */
1267 S3JniExceptionClear;
1268 }
1269 }
1270 }
1271 #define s3jni_call_xDestroy(JOBJ) s3jni__call_xDestroy(env, (JOBJ))
1272
1273 /*
1274 ** Internal helper for many hook callback impls. Locks the S3JniDb
1275 ** mutex, makes a copy of src into dest, with a some differences: (1)
1276 ** if src->jObj or src->jExtra are not NULL then dest will be a new
1277 ** LOCAL ref to it instead of a copy of the prior GLOBAL ref. (2)
1278 ** dest->doXDestroy is always false.
1279 **
1280 ** If dest->jObj is not NULL when this returns then the caller is
1281 ** obligated to eventually free the new ref by passing *dest to
1282 ** S3JniHook_localundup(). The dest pointer must NOT be passed to
1283 ** S3JniHook_unref(), as that routine assumes that dest->jObj/jExtra
1284 ** are GLOBAL refs (it's illegal to try to unref the wrong ref type).
1285 **
1286 ** Background: when running a hook we need a call-local copy lest
1287 ** another thread modify the hook while we're running it. That copy
1288 ** has to have its own Java reference, but it need only be call-local.
1289 */
1290 static void S3JniHook__localdup( JNIEnv * const env, S3JniHook const * const src,
1291 S3JniHook * const dest ){
1292 S3JniHook_mutex_enter;
1293 *dest = *src;
1294 if(src->jObj) dest->jObj = S3JniRefLocal(src->jObj);
1295 if(src->jExtra) dest->jExtra = S3JniRefLocal(src->jExtra);
1296 dest->doXDestroy = 0;
1297 S3JniHook_mutex_leave;
1298 }
1299 #define S3JniHook_localdup(src,dest) S3JniHook__localdup(env,src,dest)
1300
1301 static void S3JniHook__localundup( JNIEnv * const env, S3JniHook * const h ){
1302 S3JniUnrefLocal(h->jObj);
1303 S3JniUnrefLocal(h->jExtra);
1304 *h = S3JniHook_empty;
1305 }
1306 #define S3JniHook_localundup(HOOK) S3JniHook__localundup(env, &(HOOK))
1307
1308 /*
1309 ** Removes any Java references from s and clears its state. If
1310 ** doXDestroy is true and s->jObj is not NULL, s->jObj
1311 ** is passed to s3jni_call_xDestroy() before any references are
1312 ** cleared. It is legal to call this when the object has no Java
1313 ** references. s must not be NULL.
1314 */
1315 static void S3JniHook__unref(JNIEnv * const env, S3JniHook * const s){
1316 if( s->jObj ){
1317 if( s->doXDestroy ){
1318 s3jni_call_xDestroy(s->jObj);
1319 }
1320 S3JniUnrefGlobal(s->jObj);
1321 S3JniUnrefGlobal(s->jExtra);
1322 }else{
1323 assert( !s->jExtra );
1324 }
1325 *s = S3JniHook_empty;
1326 }
1327 #define S3JniHook_unref(hook) S3JniHook__unref(env, (hook))
1328
1329 /*
1330 ** Allocates one blank S3JniHook object from the recycling bin, if
1331 ** available, else from the heap. Returns NULL or dies on OOM,
1332 ** depending on build options. Locks on SJG.hooks.mutex.
1333 */
1334 static S3JniHook *S3JniHook__alloc(JNIEnv * const env){
1335 S3JniHook * p = 0;
1336 S3JniHook_mutex_enter;
1337 if( SJG.hook.aFree ){
1338 p = SJG.hook.aFree;
1339 SJG.hook.aFree = p->pNext;
1340 p->pNext = 0;
1341 s3jni_incr(&SJG.metrics.nHookRecycled);
1342 }
1343 S3JniHook_mutex_leave;
1344 if( 0==p ){
1345 p = s3jni_malloc(sizeof(S3JniHook));
1346 if( p ){
1347 s3jni_incr(&SJG.metrics.nHookAlloc);
1348 }
1349 }
1350 if( p ){
1351 *p = S3JniHook_empty;
1352 }
1353 return p;
1354 }
1355 #define S3JniHook_alloc() S3JniHook__alloc(env)
1356
1357 /*
1358 ** The rightful fate of all results from S3JniHook_alloc(). Locks on
1359 ** SJG.hook.mutex.
1360 */
1361 static void S3JniHook__free(JNIEnv * const env, S3JniHook * const p){
1362 if(p){
1363 assert( !p->pNext );
1364 S3JniHook_unref(p);
1365 S3JniHook_mutex_enter;
1366 p->pNext = SJG.hook.aFree;
1367 SJG.hook.aFree = p;
1368 S3JniHook_mutex_leave;
1369 }
1370 }
1371 #define S3JniHook_free(hook) S3JniHook__free(env, hook)
1372
1373 #if 0
1374 /* S3JniHook__free() without the lock: caller must hold the global mutex */
1375 static void S3JniHook__free_unlocked(JNIEnv * const env, S3JniHook * const p){
1376 if(p){
1377 assert( !p->pNext );
1378 assert( p->pNext != SJG.hook.aFree );
1379 S3JniHook_unref(p);
1380 p->pNext = SJG.hook.aFree;
1381 SJG.hook.aFree = p;
1382 }
1383 }
1384 #define S3JniHook_free_unlocked(hook) S3JniHook__free_unlocked(env, hook)
1385 #endif
1386
1387 /*
1388 ** Clears all of s's state. Requires that that the caller has locked
1389 ** S3JniGlobal.perDb.mutex. Make sure to do anything needed with
1390 ** s->pNext and s->pPrev before calling this, as this clears them.
1391 */
1392 static void S3JniDb_clear(JNIEnv * const env, S3JniDb * const s){
1393 S3JniDb_mutex_assertLocker;
1394 sqlite3_free( s->zMainDbName );
1395 #define UNHOOK(MEMBER) \
1396 S3JniHook_unref(&s->hooks.MEMBER)
1397 UNHOOK(auth);
1398 UNHOOK(busyHandler);
1399 UNHOOK(collationNeeded);
1400 UNHOOK(commit);
1401 UNHOOK(progress);
1402 UNHOOK(rollback);
1403 UNHOOK(trace);
1404 UNHOOK(update);
1405 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1406 UNHOOK(preUpdate);
1407 #endif
1408 #undef UNHOOK
1409 S3JniUnrefGlobal(s->jDb);
1410 memset(s, 0, sizeof(S3JniDb));
1411 }
1412
1413 /*
1414 ** Clears s's state and moves it to the free-list. Requires that
1415 ** S3JniGlobal.perDb.mutex is locked.
1416 */
1417 static void S3JniDb__set_aside_unlocked(JNIEnv * const env, S3JniDb * const s){
1418 assert( s );
1419 S3JniDb_mutex_assertLocker;
1420 if( s ){
1421 S3JniDb_clear(env, s);
1422 s->pNext = SJG.perDb.aFree;
1423 SJG.perDb.aFree = s;
1424 }
1425 }
1426 #define S3JniDb_set_aside_unlocked(JniDb) S3JniDb__set_aside_unlocked(env, JniDb)
1427
1428 static void S3JniDb__set_aside(JNIEnv * const env, S3JniDb * const s){
1429 S3JniDb_mutex_enter;
1430 S3JniDb_set_aside_unlocked(s);
1431 S3JniDb_mutex_leave;
1432 }
1433 #define S3JniDb_set_aside(JNIDB) S3JniDb__set_aside(env, JNIDB)
1434
1435 /*
1436 ** Uncache any state for the given JNIEnv, clearing all Java
1437 ** references the cache owns. Returns true if env was cached and false
1438 ** if it was not found in the cache. Ownership of the S3JniEnv object
1439 ** associated with the given argument is transferred to this function,
1440 ** which makes it free for re-use.
1441 **
1442 ** Requires that the env mutex be locked.
1443 */
1444 static int S3JniEnv_uncache(JNIEnv * const env){
1445 struct S3JniEnv * row;
1446 struct S3JniEnv * pPrev = 0;
1447
1448 S3JniEnv_mutex_assertLocked;
1449 row = SJG.envCache.aHead;
1450 for( ; row; pPrev = row, row = row->pNext ){
1451 if( row->env == env ){
1452 break;
1453 }
1454 }
1455 if( !row ){
1456 return 0;
1457 }
1458 if( pPrev) pPrev->pNext = row->pNext;
1459 else{
1460 assert( SJG.envCache.aHead == row );
1461 SJG.envCache.aHead = row->pNext;
1462 }
1463 memset(row, 0, sizeof(S3JniEnv));
1464 row->pNext = SJG.envCache.aFree;
1465 SJG.envCache.aFree = row;
1466 return 1;
1467 }
1468
1469 /*
1470 ** Fetches the given nph-ref from cache the cache and returns the
1471 ** object with its klazz member set. This is an O(1) operation except
1472 ** on the first call for a given pRef, during which pRef->klazz and
1473 ** pRef->pRef are initialized thread-safely. In the latter case it's
1474 ** still effectively O(1), but with a much longer 1.
1475 **
1476 ** It is up to the caller to populate the other members of the
1477 ** returned object if needed, taking care to lock the modification
1478 ** with S3JniNph_mutex_enter/leave.
1479 **
1480 ** This simple cache catches >99% of searches in the current
1481 ** (2023-07-31) tests.
1482 */
1483 static S3JniNphOp * s3jni__nphop(JNIEnv * const env, S3JniNphOp const* pRef){
1484 S3JniNphOp * const pNC = &SJG.nph.list[pRef->index];
1485
1486 assert( (void*)pRef>=(void*)&S3JniNphOps && (void*)pRef<(void*)(&S3JniNphOps + 1)
1487 && "pRef is out of range" );
1488 assert( pRef->index>=0
1489 && (pRef->index < (sizeof(S3JniNphOps) / sizeof(S3JniNphOp)))
1490 && "pRef->index is out of range" );
1491 if( !pNC->klazz ){
1492 S3JniNph_mutex_enter;
1493 if( !pNC->klazz ){
1494 jclass const klazz = (*env)->FindClass(env, pRef->zName);
1495 //printf("FindClass %s\n", pRef->zName);
1496 S3JniExceptionIsFatal("FindClass() unexpectedly threw");
1497 pNC->klazz = S3JniRefGlobal(klazz);
1498 }
1499 S3JniNph_mutex_leave;
1500 }
1501 assert( pNC->klazz );
1502 return pNC;
1503 }
1504
1505 #define s3jni_nphop(PRef) s3jni__nphop(env, PRef)
1506
1507 /*
1508 ** Common code for accessor functions for NativePointerHolder and
1509 ** OutputPointer types. pRef must be a pointer from S3JniNphOps. jOut
1510 ** must be an instance of that class (Java's type safety takes care of
1511 ** that requirement). If necessary, this fetches the jfieldID for
1512 ** jOut's pRef->zMember, which must be of the type represented by the
1513 ** JNI type signature pRef->zTypeSig, and stores it in
1514 ** S3JniGlobal.nph.list[pRef->index]. Fails fatally if the pRef->zMember
1515 ** property is not found, as that presents a serious internal misuse.
1516 **
1517 ** Property lookups are cached on a per-pRef basis.
1518 */
1519 static jfieldID s3jni_nphop_field(JNIEnv * const env, S3JniNphOp const* pRef){
1520 S3JniNphOp * const pNC = s3jni_nphop(pRef);
1521
1522 if( !pNC->fidValue ){
1523 S3JniNph_mutex_enter;
1524 if( !pNC->fidValue ){
1525 pNC->fidValue = (*env)->GetFieldID(env, pNC->klazz,
1526 pRef->zMember, pRef->zTypeSig);
1527 S3JniExceptionIsFatal("Code maintenance required: missing "
1528 "required S3JniNphOp::fidValue.");
1529 }
1530 S3JniNph_mutex_leave;
1531 }
1532 assert( pNC->fidValue );
1533 return pNC->fidValue;
1534 }
1535
1536 /*
1537 ** Sets a native ptr value in NativePointerHolder object jNph,
1538 ** which must be of the native type described by pRef. jNph
1539 ** may not be NULL.
1540 */
1541 static void NativePointerHolder__set(JNIEnv * const env, S3JniNphOp const* pRef,
1542 jobject jNph, const void * p){
1543 assert( jNph );
1544 (*env)->SetLongField(env, jNph, s3jni_nphop_field(env, pRef),
1545 S3JniCast_P2L(p));
1546 S3JniExceptionIsFatal("Could not set NativePointerHolder.nativePointer.");
1547 }
1548
1549 #define NativePointerHolder_set(PREF,JNPH,P) \
1550 NativePointerHolder__set(env, PREF, JNPH, P)
1551
1552 /*
1553 ** Fetches a native ptr value from NativePointerHolder object jNph,
1554 ** which must be of the native type described by pRef. This is a
1555 ** no-op if jNph is NULL.
1556 */
1557 static void * NativePointerHolder__get(JNIEnv * env, jobject jNph,
1558 S3JniNphOp const* pRef){
1559 void * rv = 0;
1560 if( jNph ){
1561 rv = S3JniCast_L2P(
1562 (*env)->GetLongField(env, jNph, s3jni_nphop_field(env, pRef))
1563 );
1564 S3JniExceptionIsFatal("Cannot fetch NativePointerHolder.nativePointer.");
1565 }
1566 return rv;
1567 }
1568
1569 #define NativePointerHolder_get(JOBJ,NPHREF) \
1570 NativePointerHolder__get(env, (JOBJ), (NPHREF))
1571
1572 /*
1573 ** Helpers for extracting pointers from jobjects, noting that we rely
1574 ** on the corresponding Java interfaces having already done the
1575 ** type-checking. OBJ must be a jobject referring to a
1576 ** NativePointerHolder<T>, where T matches PtrGet_T. Don't use these
1577 ** in contexts where that's not the case. Note that these aren't
1578 ** type-safe in the strictest sense:
1579 **
1580 ** sqlite3 * s = PtrGet_sqlite3_stmt(...)
1581 **
1582 ** will work, despite the incorrect macro name, so long as the
1583 ** argument is a Java sqlite3 object, as this operation only has void
1584 ** pointers to work with.
1585 */
1586 #define PtrGet_T(T,JOBJ) (T*)NativePointerHolder_get((JOBJ), S3JniNph(T))
1587 #define PtrGet_sqlite3(JOBJ) PtrGet_T(sqlite3, (JOBJ))
1588 #define PtrGet_sqlite3_backup(JOBJ) PtrGet_T(sqlite3_backup, (JOBJ))
1589 #define PtrGet_sqlite3_blob(JOBJ) PtrGet_T(sqlite3_blob, (JOBJ))
1590 #define PtrGet_sqlite3_context(JOBJ) PtrGet_T(sqlite3_context, (JOBJ))
1591 #define PtrGet_sqlite3_stmt(JOBJ) PtrGet_T(sqlite3_stmt, (JOBJ))
1592 #define PtrGet_sqlite3_value(JOBJ) PtrGet_T(sqlite3_value, (JOBJ))
1593 /*
1594 ** LongPtrGet_T(X,Y) expects X to be an unqualified sqlite3 struct
1595 ** type name and Y to be a native pointer to such an object in the
1596 ** form of a jlong value. The jlong is simply cast to (X*). This
1597 ** approach is, as of 2023-09-27, supplanting the former approach. We
1598 ** now do the native pointer extraction in the Java side, rather than
1599 ** the C side, because it's reportedly significantly faster. The
1600 ** intptr_t part here is necessary for compatibility with (at least)
1601 ** ARM32.
1602 **
1603 ** 2023-11-09: testing has not revealed any measurable performance
1604 ** difference between the approach of passing type T to C compared to
1605 ** passing pointer-to-T to C, and adding support for the latter
1606 ** everywhere requires sigificantly more code. As of this writing, the
1607 ** older/simpler approach is being applied except for (A) where the
1608 ** newer approach has already been applied and (B) hot-spot APIs where
1609 ** a difference of microseconds (i.e. below our testing measurement
1610 ** threshold) might add up.
1611 */
1612 #define LongPtrGet_T(T,JLongAsPtr) (T*)((intptr_t)((JLongAsPtr)))
1613 #define LongPtrGet_sqlite3(JLongAsPtr) LongPtrGet_T(sqlite3,(JLongAsPtr))
1614 #define LongPtrGet_sqlite3_backup(JLongAsPtr) LongPtrGet_T(sqlite3_backup,(JLongAsPtr))
1615 #define LongPtrGet_sqlite3_blob(JLongAsPtr) LongPtrGet_T(sqlite3_blob,(JLongAsPtr))
1616 #define LongPtrGet_sqlite3_stmt(JLongAsPtr) LongPtrGet_T(sqlite3_stmt,(JLongAsPtr))
1617 #define LongPtrGet_sqlite3_value(JLongAsPtr) LongPtrGet_T(sqlite3_value,(JLongAsPtr))
1618 /*
1619 ** Extracts the new S3JniDb instance from the free-list, or allocates
1620 ** one if needed, associates it with pDb, and returns. Returns NULL
1621 ** on OOM. The returned object MUST, on success of the calling
1622 ** operation, subsequently be associated with jDb via
1623 ** NativePointerHolder_set() or freed using S3JniDb_set_aside().
1624 */
1625 static S3JniDb * S3JniDb_alloc(JNIEnv * const env, jobject jDb){
1626 S3JniDb * rv = 0;
1627 S3JniDb_mutex_enter;
1628 if( SJG.perDb.aFree ){
1629 rv = SJG.perDb.aFree;
1630 SJG.perDb.aFree = rv->pNext;
1631 rv->pNext = 0;
1632 s3jni_incr( &SJG.metrics.nPdbRecycled );
1633 }
1634 S3JniDb_mutex_leave;
1635 if( 0==rv ){
1636 rv = s3jni_malloc(sizeof(S3JniDb));
1637 if( rv ){
1638 s3jni_incr( &SJG.metrics.nPdbAlloc );
1639 }
1640 }
1641 if( rv ){
1642 memset(rv, 0, sizeof(S3JniDb));
1643 rv->jDb = S3JniRefGlobal(jDb);
1644 }
1645 return rv;
1646 }
1647
1648 /*
1649 ** Returns the S3JniDb object for the given org.sqlite.jni.capi.sqlite3
1650 ** object, or NULL if jDb is NULL, no pointer can be extracted
1651 ** from it, or no matching entry can be found.
1652 */
1653 static S3JniDb * S3JniDb__from_java(JNIEnv * const env, jobject jDb){
1654 sqlite3 * const pDb = jDb ? PtrGet_sqlite3(jDb) : 0;
1655 return pDb ? S3JniDb_from_clientdata(pDb) : 0;
1656 }
1657 #define S3JniDb_from_java(jObject) S3JniDb__from_java(env,(jObject))
1658
1659 /*
1660 ** S3JniDb finalizer for use with sqlite3_set_clientdata().
1661 */
1662 static void S3JniDb_xDestroy(void *p){
1663 S3JniDeclLocal_env;
1664 S3JniDb * const ps = p;
1665 assert( !ps->pNext && "Else ps is already in the free-list.");
1666 S3JniDb_set_aside(ps);
1667 }
1668
1669 /*
1670 ** Evaluates to the S3JniDb object for the given sqlite3 object, or
1671 ** NULL if pDb is NULL or was not initialized via the JNI interfaces.
1672 */
1673 #define S3JniDb_from_c(sqlite3Ptr) \
1674 ((sqlite3Ptr) ? S3JniDb_from_clientdata(sqlite3Ptr) : 0)
1675 #define S3JniDb_from_jlong(sqlite3PtrAsLong) \
1676 S3JniDb_from_c(LongPtrGet_T(sqlite3,sqlite3PtrAsLong))
1677
1678 /*
1679 ** Unref any Java-side state in (S3JniAutoExtension*) AX and zero out
1680 ** AX.
1681 */
1682 #define S3JniAutoExtension_clear(AX) S3JniHook_unref(AX);
1683
1684 /*
1685 ** Initializes a pre-allocated S3JniAutoExtension object. Returns
1686 ** non-0 if there is an error collecting the required state from
1687 ** jAutoExt (which must be an AutoExtensionCallback object). On error,
1688 ** it passes ax to S3JniAutoExtension_clear().
1689 */
1690 static int S3JniAutoExtension_init(JNIEnv *const env,
1691 S3JniAutoExtension * const ax,
1692 jobject const jAutoExt){
1693 jclass const klazz = (*env)->GetObjectClass(env, jAutoExt);
1694
1695 S3JniAutoExt_mutex_assertLocker;
1696 *ax = S3JniHook_empty;
1697 ax->midCallback = (*env)->GetMethodID(env, klazz, "call",
1698 "(Lorg/sqlite/jni/capi/sqlite3;)I");
1699 S3JniUnrefLocal(klazz);
1700 S3JniExceptionWarnIgnore;
1701 if( !ax->midCallback ){
1702 S3JniAutoExtension_clear(ax);
1703 return SQLITE_ERROR;
1704 }
1705 ax->jObj = S3JniRefGlobal(jAutoExt);
1706 return 0;
1707 }
1708
1709 /*
1710 ** Sets the value property of the OutputPointer.Bool jOut object to
1711 ** v.
1712 */
1713 static void OutputPointer_set_Bool(JNIEnv * const env, jobject const jOut,
1714 int v){
1715 (*env)->SetBooleanField(env, jOut, s3jni_nphop_field(
1716 env, S3JniNph(OutputPointer_Bool)
1717 ), v ? JNI_TRUE : JNI_FALSE );
1718 S3JniExceptionIsFatal("Cannot set OutputPointer.Bool.value");
1719 }
1720
1721 /*
1722 ** Sets the value property of the OutputPointer.Int32 jOut object to
1723 ** v.
1724 */
1725 static void OutputPointer_set_Int32(JNIEnv * const env, jobject const jOut,
1726 int v){
1727 (*env)->SetIntField(env, jOut, s3jni_nphop_field(
1728 env, S3JniNph(OutputPointer_Int32)
1729 ), (jint)v);
1730 S3JniExceptionIsFatal("Cannot set OutputPointer.Int32.value");
1731 }
1732
1733 /*
1734 ** Sets the value property of the OutputPointer.Int64 jOut object to
1735 ** v.
1736 */
1737 static void OutputPointer_set_Int64(JNIEnv * const env, jobject const jOut,
1738 jlong v){
1739 (*env)->SetLongField(env, jOut, s3jni_nphop_field(
1740 env, S3JniNph(OutputPointer_Int64)
1741 ), v);
1742 S3JniExceptionIsFatal("Cannot set OutputPointer.Int64.value");
1743 }
1744
1745 /*
1746 ** Internal helper for OutputPointer_set_TYPE() where TYPE is an
1747 ** Object type.
1748 */
1749 static void OutputPointer_set_obj(JNIEnv * const env,
1750 S3JniNphOp const * const pRef,
1751 jobject const jOut,
1752 jobject v){
1753 (*env)->SetObjectField(env, jOut, s3jni_nphop_field(env, pRef), v);
1754 S3JniExceptionIsFatal("Cannot set OutputPointer.T.value");
1755 }
1756
1757 #ifdef SQLITE_ENABLE_FTS5
1758 #if 0
1759 /*
1760 ** Sets the value property of the OutputPointer.ByteArray jOut object
1761 ** to v.
1762 */
1763 static void OutputPointer_set_ByteArray(JNIEnv * const env, jobject const jOut,
1764 jbyteArray const v){
1765 OutputPointer_set_obj(env, S3JniNph(OutputPointer_ByteArray), jOut, v);
1766 }
1767 #endif
1768 #endif /* SQLITE_ENABLE_FTS5 */
1769
1770 /*
1771 ** Sets the value property of the OutputPointer.String jOut object to
1772 ** v.
1773 */
1774 static void OutputPointer_set_String(JNIEnv * const env, jobject const jOut,
1775 jstring const v){
1776 OutputPointer_set_obj(env, S3JniNph(OutputPointer_String), jOut, v);
1777 }
1778
1779 /*
1780 ** Returns true if eTextRep is a valid sqlite3 encoding constant, else
1781 ** returns false.
1782 */
1783 static int encodingTypeIsValid(int eTextRep){
1784 switch( eTextRep ){
1785 case SQLITE_UTF8: case SQLITE_UTF16:
1786 case SQLITE_UTF16LE: case SQLITE_UTF16BE:
1787 return 1;
1788 default:
1789 return 0;
1790 }
1791 }
1792
1793 /* For use with sqlite3_result_pointer(), sqlite3_value_pointer(),
1794 sqlite3_bind_java_object(), and sqlite3_column_java_object(). */
1795 static const char * const s3jni__value_jref_key = "org.sqlite.jni.capi.ResultJavaVal";
1796
1797 /*
1798 ** If v is not NULL, it must be a jobject global reference. Its
1799 ** reference is relinquished.
1800 */
1801 static void S3Jni_jobject_finalizer(void *v){
1802 if( v ){
1803 S3JniDeclLocal_env;
1804 S3JniUnrefGlobal((jobject)v);
1805 }
1806 }
1807
1808 /*
1809 ** Returns a new Java instance of the class referred to by pRef, which
1810 ** MUST be interface-compatible with NativePointerHolder and MUST have
1811 ** a no-arg constructor. The NativePointerHolder_set() method is
1812 ** passed the new Java object (which must not be NULL) and pNative
1813 ** (which may be NULL). Hypothetically returns NULL if Java fails to
1814 ** allocate, but the JNI docs are not entirely clear on that detail.
1815 **
1816 ** Always use a static pointer from the S3JniNphOps struct for the
1817 ** 2nd argument.
1818 */
1819 static jobject NativePointerHolder_new(JNIEnv * const env,
1820 S3JniNphOp const * pRef,
1821 const void * pNative){
1822 jobject rv = 0;
1823 S3JniNphOp * const pNC = s3jni_nphop(pRef);
1824 if( !pNC->midCtor ){
1825 S3JniNph_mutex_enter;
1826 if( !pNC->midCtor ){
1827 pNC->midCtor = (*env)->GetMethodID(env, pNC->klazz, "<init>", "()V");
1828 S3JniExceptionIsFatal("Cannot find constructor for class.");
1829 }
1830 S3JniNph_mutex_leave;
1831 }
1832 rv = (*env)->NewObject(env, pNC->klazz, pNC->midCtor);
1833 S3JniExceptionIsFatal("No-arg constructor threw.");
1834 s3jni_oom_check(rv);
1835 if( rv ) NativePointerHolder_set(pRef, rv, pNative);
1836 return rv;
1837 }
1838
1839 static inline jobject new_java_sqlite3(JNIEnv * const env, sqlite3 *sv){
1840 return NativePointerHolder_new(env, S3JniNph(sqlite3), sv);
1841 }
1842 static inline jobject new_java_sqlite3_backup(JNIEnv * const env, sqlite3_backup *sv){
1843 return NativePointerHolder_new(env, S3JniNph(sqlite3_backup), sv);
1844 }
1845 static inline jobject new_java_sqlite3_blob(JNIEnv * const env, sqlite3_blob *sv){
1846 return NativePointerHolder_new(env, S3JniNph(sqlite3_blob), sv);
1847 }
1848 static inline jobject new_java_sqlite3_context(JNIEnv * const env, sqlite3_context *sv){
1849 return NativePointerHolder_new(env, S3JniNph(sqlite3_context), sv);
1850 }
1851 static inline jobject new_java_sqlite3_stmt(JNIEnv * const env, sqlite3_stmt *sv){
1852 return NativePointerHolder_new(env, S3JniNph(sqlite3_stmt), sv);
1853 }
1854 static inline jobject new_java_sqlite3_value(JNIEnv * const env, sqlite3_value *sv){
1855 return NativePointerHolder_new(env, S3JniNph(sqlite3_value), sv);
1856 }
1857
1858 /* Helper typedefs for UDF callback types. */
1859 typedef void (*udf_xFunc_f)(sqlite3_context*,int,sqlite3_value**);
1860 typedef void (*udf_xStep_f)(sqlite3_context*,int,sqlite3_value**);
1861 typedef void (*udf_xFinal_f)(sqlite3_context*);
1862 /*typedef void (*udf_xValue_f)(sqlite3_context*);*/
1863 /*typedef void (*udf_xInverse_f)(sqlite3_context*,int,sqlite3_value**);*/
1864
1865 /*
1866 ** Allocate a new S3JniUdf (User-defined Function) and associate it
1867 ** with the SQLFunction-type jObj. Returns NULL on OOM. If the
1868 ** returned object's type==UDF_UNKNOWN_TYPE then the type of UDF was
1869 ** not unambiguously detected based on which callback members it has,
1870 ** which falls into the category of user error.
1871 **
1872 ** The caller must arrange for the returned object to eventually be
1873 ** passed to S3JniUdf_free().
1874 */
1875 static S3JniUdf * S3JniUdf_alloc(JNIEnv * const env, jobject jObj){
1876 S3JniUdf * s = 0;
1877
1878 S3JniGlobal_mutex_enter;
1879 s3jni_incr(&SJG.metrics.nMutexUdf);
1880 if( SJG.udf.aFree ){
1881 s = SJG.udf.aFree;
1882 SJG.udf.aFree = s->pNext;
1883 s->pNext = 0;
1884 s3jni_incr(&SJG.metrics.nUdfRecycled);
1885 }
1886 S3JniGlobal_mutex_leave;
1887 if( !s ){
1888 s = s3jni_malloc( sizeof(*s));
1889 s3jni_incr(&SJG.metrics.nUdfAlloc);
1890 }
1891 if( s ){
1892 const char * zFSI = /* signature for xFunc, xStep, xInverse */
1893 "(Lorg/sqlite/jni/capi/sqlite3_context;[Lorg/sqlite/jni/capi/sqlite3_value;)V";
1894 const char * zFV = /* signature for xFinal, xValue */
1895 "(Lorg/sqlite/jni/capi/sqlite3_context;)V";
1896 jclass const klazz = (*env)->GetObjectClass(env, jObj);
1897
1898 memset(s, 0, sizeof(*s));
1899 s->jObj = S3JniRefGlobal(jObj);
1900
1901 #define FGET(FuncName,FuncSig,Field) \
1902 s->Field = (*env)->GetMethodID(env, klazz, FuncName, FuncSig); \
1903 if( !s->Field ) (*env)->ExceptionClear(env)
1904
1905 FGET("xFunc", zFSI, jmidxFunc);
1906 FGET("xStep", zFSI, jmidxStep);
1907 FGET("xFinal", zFV, jmidxFinal);
1908 FGET("xValue", zFV, jmidxValue);
1909 FGET("xInverse", zFSI, jmidxInverse);
1910 #undef FGET
1911
1912 S3JniUnrefLocal(klazz);
1913 if( s->jmidxFunc ) s->type = UDF_SCALAR;
1914 else if( s->jmidxStep && s->jmidxFinal ){
1915 s->type = (s->jmidxValue && s->jmidxInverse)
1916 ? UDF_WINDOW : UDF_AGGREGATE;
1917 }else{
1918 s->type = UDF_UNKNOWN_TYPE;
1919 }
1920 }
1921 return s;
1922 }
1923
1924 /*
1925 ** Frees up all resources owned by s, clears its state, then either
1926 ** caches it for reuse (if cacheIt is true) or frees it. The former
1927 ** requires locking the global mutex, so it must not be held when this
1928 ** is called.
1929 */
1930 static void S3JniUdf_free(JNIEnv * const env, S3JniUdf * const s,
1931 int cacheIt){
1932 assert( !s->pNext );
1933 if( s->jObj ){
1934 s3jni_call_xDestroy(s->jObj);
1935 S3JniUnrefGlobal(s->jObj);
1936 sqlite3_free(s->zFuncName);
1937 assert( !s->pNext );
1938 memset(s, 0, sizeof(*s));
1939 }
1940 if( cacheIt ){
1941 S3JniGlobal_mutex_enter;
1942 s->pNext = S3JniGlobal.udf.aFree;
1943 S3JniGlobal.udf.aFree = s;
1944 S3JniGlobal_mutex_leave;
1945 }else{
1946 sqlite3_free( s );
1947 }
1948 }
1949
1950 /* Finalizer for sqlite3_create_function() and friends. */
1951 static void S3JniUdf_finalizer(void * s){
1952 S3JniUdf_free(s3jni_env(), (S3JniUdf*)s, 1);
1953 }
1954
1955 /*
1956 ** Helper for processing args to UDF handlers with signature
1957 ** (sqlite3_context*,int,sqlite3_value**).
1958 */
1959 typedef struct {
1960 jobject jcx /* sqlite3_context */;
1961 jobjectArray jargv /* sqlite3_value[] */;
1962 } udf_jargs;
1963
1964 /*
1965 ** Converts the given (cx, argc, argv) into arguments for the given
1966 ** UDF, writing the result (Java wrappers for cx and argv) in the
1967 ** final 2 arguments. Returns 0 on success, SQLITE_NOMEM on allocation
1968 ** error. On error *jCx and *jArgv will be set to 0. The output
1969 ** objects are of type org.sqlite.jni.capi.sqlite3_context and
1970 ** array-of-org.sqlite.jni.capi.sqlite3_value, respectively.
1971 */
1972 static int udf_args(JNIEnv *env,
1973 sqlite3_context * const cx,
1974 int argc, sqlite3_value**argv,
1975 jobject * jCx, jobjectArray *jArgv){
1976 jobjectArray ja = 0;
1977 jobject jcx = new_java_sqlite3_context(env, cx);
1978 jint i;
1979 *jCx = 0;
1980 *jArgv = 0;
1981 if( !jcx ) goto error_oom;
1982 ja = (*env)->NewObjectArray(
1983 env, argc, s3jni_nphop(S3JniNph(sqlite3_value))->klazz,
1984 NULL);
1985 s3jni_oom_check( ja );
1986 if( !ja ) goto error_oom;
1987 for(i = 0; i < argc; ++i){
1988 jobject jsv = new_java_sqlite3_value(env, argv[i]);
1989 if( !jsv ) goto error_oom;
1990 (*env)->SetObjectArrayElement(env, ja, i, jsv);
1991 S3JniUnrefLocal(jsv)/*ja has a ref*/;
1992 }
1993 *jCx = jcx;
1994 *jArgv = ja;
1995 return 0;
1996 error_oom:
1997 S3JniUnrefLocal(jcx);
1998 S3JniUnrefLocal(ja);
1999 return SQLITE_NOMEM;
2000 }
2001
2002 /*
2003 ** Requires that jCx and jArgv are sqlite3_context
2004 ** resp. array-of-sqlite3_value values initialized by udf_args(). The
2005 ** latter will be 0-and-NULL for UDF types with no arguments. This
2006 ** function zeroes out the nativePointer member of jCx and each entry
2007 ** in jArgv. This is a safety-net precaution to avoid undefined
2008 ** behavior if a Java-side UDF holds a reference to its context or one
2009 ** of its arguments. This MUST be called from any function which
2010 ** successfully calls udf_args(), after calling the corresponding UDF
2011 ** and checking its exception status, or which Java-wraps a
2012 ** sqlite3_context for use with a UDF(ish) call. It MUST NOT be called
2013 ** in any other case.
2014 */
2015 static void udf_unargs(JNIEnv *env, jobject jCx, int argc, jobjectArray jArgv){
2016 int i = 0;
2017 assert(jCx);
2018 NativePointerHolder_set(S3JniNph(sqlite3_context), jCx, 0);
2019 for( ; i < argc; ++i ){
2020 jobject jsv = (*env)->GetObjectArrayElement(env, jArgv, i);
2021 /*
2022 ** There is a potential Java-triggerable case of Undefined
2023 ** Behavior here, but it would require intentional misuse of the
2024 ** API:
2025 **
2026 ** If a Java UDF grabs an sqlite3_value from its argv and then
2027 ** assigns that element to null, it becomes unreachable to us so
2028 ** we cannot clear out its pointer. That Java-side object's
2029 ** getNativePointer() will then refer to a stale value, so passing
2030 ** it into (e.g.) sqlite3_value_SOMETHING() would invoke UB.
2031 **
2032 ** High-level wrappers can avoid that possibility if they do not
2033 ** expose sqlite3_value directly to clients (as is the case in
2034 ** org.sqlite.jni.wrapper1.SqlFunction).
2035 **
2036 ** One potential (but expensive) workaround for this would be to
2037 ** privately store a duplicate argv array in each sqlite3_context
2038 ** wrapper object, and clear the native pointers from that copy.
2039 */
2040 assert(jsv && "Someone illegally modified a UDF argument array.");
2041 if( jsv ){
2042 NativePointerHolder_set(S3JniNph(sqlite3_value), jsv, 0);
2043 }
2044 }
2045 }
2046
2047
2048 /*
2049 ** Must be called immediately after a Java-side UDF callback throws.
2050 ** If translateToErr is true then it sets the exception's message in
2051 ** the result error using sqlite3_result_error(). If translateToErr is
2052 ** false then it emits a warning that the function threw but should
2053 ** not do so. In either case, it clears the exception state.
2054 **
2055 ** Returns SQLITE_NOMEM if an allocation fails, else SQLITE_ERROR. In
2056 ** the former case it calls sqlite3_result_error_nomem().
2057 */
2058 static int udf_report_exception(JNIEnv * const env, int translateToErr,
2059 sqlite3_context * cx,
2060 const char *zFuncName, const char *zFuncType ){
2061 jthrowable const ex = (*env)->ExceptionOccurred(env);
2062 int rc = SQLITE_ERROR;
2063
2064 assert(ex && "This must only be called when a Java exception is pending.");
2065 if( translateToErr ){
2066 char * zMsg;
2067 char * z;
2068
2069 S3JniExceptionClear;
2070 zMsg = s3jni_exception_error_msg(env, ex);
2071 z = sqlite3_mprintf("Client-defined SQL function %s.%s() threw: %s",
2072 zFuncName ? zFuncName : "<unnamed>", zFuncType,
2073 zMsg ? zMsg : "Unknown exception" );
2074 sqlite3_free(zMsg);
2075 if( z ){
2076 sqlite3_result_error(cx, z, -1);
2077 sqlite3_free(z);
2078 }else{
2079 sqlite3_result_error_nomem(cx);
2080 rc = SQLITE_NOMEM;
2081 }
2082 }else{
2083 S3JniExceptionWarnCallbackThrew("client-defined SQL function");
2084 S3JniExceptionClear;
2085 }
2086 S3JniUnrefLocal(ex);
2087 return rc;
2088 }
2089
2090 /*
2091 ** Sets up the state for calling a Java-side xFunc/xStep/xInverse()
2092 ** UDF, calls it, and returns 0 on success.
2093 */
2094 static int udf_xFSI(sqlite3_context* const pCx, int argc,
2095 sqlite3_value** const argv, S3JniUdf * const s,
2096 jmethodID xMethodID, const char * const zFuncType){
2097 S3JniDeclLocal_env;
2098 udf_jargs args = {0,0};
2099 int rc = udf_args(env, pCx, argc, argv, &args.jcx, &args.jargv);
2100
2101 if( 0 == rc ){
2102 (*env)->CallVoidMethod(env, s->jObj, xMethodID, args.jcx, args.jargv);
2103 S3JniIfThrew{
2104 rc = udf_report_exception(env, 'F'==zFuncType[1]/*xFunc*/, pCx,
2105 s->zFuncName, zFuncType);
2106 }
2107 udf_unargs(env, args.jcx, argc, args.jargv);
2108 }
2109 S3JniUnrefLocal(args.jcx);
2110 S3JniUnrefLocal(args.jargv);
2111 return rc;
2112 }
2113
2114 /*
2115 ** Sets up the state for calling a Java-side xFinal/xValue() UDF,
2116 ** calls it, and returns 0 on success.
2117 */
2118 static int udf_xFV(sqlite3_context* cx, S3JniUdf * s,
2119 jmethodID xMethodID,
2120 const char *zFuncType){
2121 S3JniDeclLocal_env;
2122 jobject jcx = new_java_sqlite3_context(env, cx);
2123 int rc = 0;
2124 int const isFinal = 'F'==zFuncType[1]/*xFinal*/;
2125
2126 if( jcx ){
2127 (*env)->CallVoidMethod(env, s->jObj, xMethodID, jcx);
2128 S3JniIfThrew{
2129 rc = udf_report_exception(env, isFinal, cx, s->zFuncName,
2130 zFuncType);
2131 }
2132 udf_unargs(env, jcx, 0, 0);
2133 S3JniUnrefLocal(jcx);
2134 }else{
2135 if( isFinal ) sqlite3_result_error_nomem(cx);
2136 rc = SQLITE_NOMEM;
2137 }
2138 return rc;
2139 }
2140
2141 /* Proxy for C-to-Java xFunc. */
2142 static void udf_xFunc(sqlite3_context* cx, int argc,
2143 sqlite3_value** argv){
2144 S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx);
2145 s3jni_incr( &SJG.metrics.udf.nFunc );
2146 udf_xFSI(cx, argc, argv, s, s->jmidxFunc, "xFunc");
2147 }
2148 /* Proxy for C-to-Java xStep. */
2149 static void udf_xStep(sqlite3_context* cx, int argc,
2150 sqlite3_value** argv){
2151 S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx);
2152 s3jni_incr( &SJG.metrics.udf.nStep );
2153 udf_xFSI(cx, argc, argv, s, s->jmidxStep, "xStep");
2154 }
2155 /* Proxy for C-to-Java xFinal. */
2156 static void udf_xFinal(sqlite3_context* cx){
2157 S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx);
2158 s3jni_incr( &SJG.metrics.udf.nFinal );
2159 udf_xFV(cx, s, s->jmidxFinal, "xFinal");
2160 }
2161 /* Proxy for C-to-Java xValue. */
2162 static void udf_xValue(sqlite3_context* cx){
2163 S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx);
2164 s3jni_incr( &SJG.metrics.udf.nValue );
2165 udf_xFV(cx, s, s->jmidxValue, "xValue");
2166 }
2167 /* Proxy for C-to-Java xInverse. */
2168 static void udf_xInverse(sqlite3_context* cx, int argc,
2169 sqlite3_value** argv){
2170 S3JniUdf * const s = (S3JniUdf*)sqlite3_user_data(cx);
2171 s3jni_incr( &SJG.metrics.udf.nInverse );
2172 udf_xFSI(cx, argc, argv, s, s->jmidxInverse, "xInverse");
2173 }
2174
2175
2176 ////////////////////////////////////////////////////////////////////////
2177 // What follows is the JNI/C bindings. They are in alphabetical order
2178 // except for this macro-generated subset which are kept together
2179 // (alphabetized) here at the front...
2180 ////////////////////////////////////////////////////////////////////////
2181
2182 /** Create a trivial JNI wrapper for (int CName(void)). */
2183 #define WRAP_INT_VOID(JniNameSuffix,CName) \
2184 JniDecl(jint,JniNameSuffix)(JniArgsEnvClass){ \
2185 return (jint)CName(); \
2186 }
2187 /** Create a trivial JNI wrapper for (int CName(int)). */
2188 #define WRAP_INT_INT(JniNameSuffix,CName) \
2189 JniDecl(jint,JniNameSuffix)(JniArgsEnvClass, jint arg){ \
2190 return (jint)CName((int)arg); \
2191 }
2192 /*
2193 ** Create a trivial JNI wrapper for (const mutf8_string *
2194 ** CName(void)). This is only valid for functions which are known to
2195 ** return ASCII or text which is equivalent in UTF-8 and MUTF-8.
2196 */
2197 #define WRAP_MUTF8_VOID(JniNameSuffix,CName) \
2198 JniDecl(jstring,JniNameSuffix)(JniArgsEnvClass){ \
2199 jstring const rv = (*env)->NewStringUTF( env, CName() ); \
2200 s3jni_oom_check(rv); \
2201 return rv; \
2202 }
2203 /** Create a trivial JNI wrapper for (int CName(sqlite3_stmt*)). */
2204 #define WRAP_INT_STMT(JniNameSuffix,CName) \
2205 JniDecl(jint,JniNameSuffix)(JniArgsEnvClass, jlong jpStmt){ \
2206 return (jint)CName(LongPtrGet_sqlite3_stmt(jpStmt)); \
2207 }
2208 /** Create a trivial JNI wrapper for (int CName(sqlite3_stmt*,int)). */
2209 #define WRAP_INT_STMT_INT(JniNameSuffix,CName) \
2210 JniDecl(jint,JniNameSuffix)(JniArgsEnvClass, jlong jpStmt, jint n){ \
2211 return (jint)CName(LongPtrGet_sqlite3_stmt(jpStmt), (int)n); \
2212 }
2213 /** Create a trivial JNI wrapper for (boolean CName(sqlite3_stmt*)). */
2214 #define WRAP_BOOL_STMT(JniNameSuffix,CName) \
2215 JniDecl(jboolean,JniNameSuffix)(JniArgsEnvClass, jobject jStmt){ \
2216 return CName(PtrGet_sqlite3_stmt(jStmt)) ? JNI_TRUE : JNI_FALSE; \
2217 }
2218 /** Create a trivial JNI wrapper for (jstring CName(sqlite3_stmt*,int)). */
2219 #define WRAP_STR_STMT_INT(JniNameSuffix,CName) \
2220 JniDecl(jstring,JniNameSuffix)(JniArgsEnvClass, jlong jpStmt, jint ndx){ \
2221 return s3jni_utf8_to_jstring( \
2222 CName(LongPtrGet_sqlite3_stmt(jpStmt), (int)ndx), \
2223 -1); \
2224 }
2225 /** Create a trivial JNI wrapper for (boolean CName(sqlite3*)). */
2226 #define WRAP_BOOL_DB(JniNameSuffix,CName) \
2227 JniDecl(jboolean,JniNameSuffix)(JniArgsEnvClass, jlong jpDb){ \
2228 return CName(LongPtrGet_sqlite3(jpDb)) ? JNI_TRUE : JNI_FALSE; \
2229 }
2230 /** Create a trivial JNI wrapper for (int CName(sqlite3*)). */
2231 #define WRAP_INT_DB(JniNameSuffix,CName) \
2232 JniDecl(jint,JniNameSuffix)(JniArgsEnvClass, jlong jpDb){ \
2233 return (jint)CName(LongPtrGet_sqlite3(jpDb)); \
2234 }
2235 /** Create a trivial JNI wrapper for (int64 CName(sqlite3*)). */
2236 #define WRAP_INT64_DB(JniNameSuffix,CName) \
2237 JniDecl(jlong,JniNameSuffix)(JniArgsEnvClass, jlong jpDb){ \
2238 return (jlong)CName(LongPtrGet_sqlite3(jpDb)); \
2239 }
2240 /** Create a trivial JNI wrapper for (jstring CName(sqlite3*,int)). */
2241 #define WRAP_STR_DB_INT(JniNameSuffix,CName) \
2242 JniDecl(jstring,JniNameSuffix)(JniArgsEnvClass, jlong jpDb, jint ndx){ \
2243 return s3jni_utf8_to_jstring( \
2244 CName(LongPtrGet_sqlite3(jpDb), (int)ndx), \
2245 -1); \
2246 }
2247 /** Create a trivial JNI wrapper for (int CName(sqlite3_value*)). */
2248 #define WRAP_INT_SVALUE(JniNameSuffix,CName,DfltOnNull) \
2249 JniDecl(jint,JniNameSuffix)(JniArgsEnvClass, jlong jpSValue){ \
2250 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSValue); \
2251 return (jint)(sv ? CName(sv): DfltOnNull); \
2252 }
2253 /** Create a trivial JNI wrapper for (boolean CName(sqlite3_value*)). */
2254 #define WRAP_BOOL_SVALUE(JniNameSuffix,CName,DfltOnNull) \
2255 JniDecl(jboolean,JniNameSuffix)(JniArgsEnvClass, jlong jpSValue){ \
2256 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSValue); \
2257 return (jint)(sv ? CName(sv) : DfltOnNull) \
2258 ? JNI_TRUE : JNI_FALSE; \
2259 }
2260
2261 WRAP_INT_DB(1changes, sqlite3_changes)
2262 WRAP_INT64_DB(1changes64, sqlite3_changes64)
2263 WRAP_INT_STMT(1clear_1bindings, sqlite3_clear_bindings)
2264 WRAP_INT_STMT_INT(1column_1bytes, sqlite3_column_bytes)
2265 WRAP_INT_STMT_INT(1column_1bytes16, sqlite3_column_bytes16)
2266 WRAP_INT_STMT(1column_1count, sqlite3_column_count)
2267 WRAP_STR_STMT_INT(1column_1decltype, sqlite3_column_decltype)
2268 WRAP_STR_STMT_INT(1column_1name, sqlite3_column_name)
2269 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2270 WRAP_STR_STMT_INT(1column_1database_1name, sqlite3_column_database_name)
2271 WRAP_STR_STMT_INT(1column_1origin_1name, sqlite3_column_origin_name)
2272 WRAP_STR_STMT_INT(1column_1table_1name, sqlite3_column_table_name)
2273 #endif
2274 WRAP_INT_STMT_INT(1column_1type, sqlite3_column_type)
2275 WRAP_INT_STMT(1data_1count, sqlite3_data_count)
2276 WRAP_STR_DB_INT(1db_1name, sqlite3_db_name)
2277 WRAP_INT_DB(1error_1offset, sqlite3_error_offset)
2278 WRAP_INT_DB(1extended_1errcode, sqlite3_extended_errcode)
2279 WRAP_BOOL_DB(1get_1autocommit, sqlite3_get_autocommit)
2280 WRAP_MUTF8_VOID(1libversion, sqlite3_libversion)
2281 WRAP_INT_VOID(1libversion_1number, sqlite3_libversion_number)
2282 WRAP_INT_VOID(1keyword_1count, sqlite3_keyword_count)
2283 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
2284 WRAP_INT_DB(1preupdate_1blobwrite, sqlite3_preupdate_blobwrite)
2285 WRAP_INT_DB(1preupdate_1count, sqlite3_preupdate_count)
2286 WRAP_INT_DB(1preupdate_1depth, sqlite3_preupdate_depth)
2287 #endif
2288 WRAP_INT_INT(1release_1memory, sqlite3_release_memory)
2289 WRAP_INT_INT(1sleep, sqlite3_sleep)
2290 WRAP_MUTF8_VOID(1sourceid, sqlite3_sourceid)
2291 WRAP_BOOL_STMT(1stmt_1busy, sqlite3_stmt_busy)
2292 WRAP_INT_STMT_INT(1stmt_1explain, sqlite3_stmt_explain)
2293 WRAP_INT_STMT(1stmt_1isexplain, sqlite3_stmt_isexplain)
2294 WRAP_BOOL_STMT(1stmt_1readonly, sqlite3_stmt_readonly)
2295 WRAP_INT_DB(1system_1errno, sqlite3_system_errno)
2296 WRAP_INT_VOID(1threadsafe, sqlite3_threadsafe)
2297 WRAP_INT_DB(1total_1changes, sqlite3_total_changes)
2298 WRAP_INT64_DB(1total_1changes64, sqlite3_total_changes64)
2299 WRAP_INT_SVALUE(1value_1encoding, sqlite3_value_encoding,SQLITE_UTF8)
2300 WRAP_BOOL_SVALUE(1value_1frombind, sqlite3_value_frombind,0)
2301 WRAP_INT_SVALUE(1value_1nochange, sqlite3_value_nochange,0)
2302 WRAP_INT_SVALUE(1value_1numeric_1type, sqlite3_value_numeric_type,SQLITE_NULL)
2303 WRAP_INT_SVALUE(1value_1subtype, sqlite3_value_subtype,0)
2304 WRAP_INT_SVALUE(1value_1type, sqlite3_value_type,SQLITE_NULL)
2305
2306 #undef WRAP_BOOL_DB
2307 #undef WRAP_BOOL_STMT
2308 #undef WRAP_BOOL_SVALUE
2309 #undef WRAP_INT64_DB
2310 #undef WRAP_INT_DB
2311 #undef WRAP_INT_INT
2312 #undef WRAP_INT_STMT
2313 #undef WRAP_INT_STMT_INT
2314 #undef WRAP_INT_SVALUE
2315 #undef WRAP_INT_VOID
2316 #undef WRAP_MUTF8_VOID
2317 #undef WRAP_STR_STMT_INT
2318 #undef WRAP_STR_DB_INT
2319
2320 S3JniApi(sqlite3_aggregate_context(),jlong,1aggregate_1context)(
2321 JniArgsEnvClass, jobject jCx, jboolean initialize
2322 ){
2323 sqlite3_context * const pCx = PtrGet_sqlite3_context(jCx);
2324 void * const p = pCx
2325 ? sqlite3_aggregate_context(pCx, (int)(initialize
2326 ? (int)sizeof(void*)
2327 : 0))
2328 : 0;
2329 return S3JniCast_P2L(p);
2330 }
2331
2332 /*
2333 ** Central auto-extension runner for auto-extensions created in Java.
2334 */
2335 static int s3jni_run_java_auto_extensions(sqlite3 *pDb, const char **pzErr,
2336 const struct sqlite3_api_routines *ignored){
2337 int rc = 0;
2338 unsigned i, go = 1;
2339 JNIEnv * env = 0;
2340 S3JniDb * ps;
2341 S3JniEnv * jc;
2342
2343 if( 0==SJG.autoExt.nExt ) return 0;
2344 env = s3jni_env();
2345 jc = S3JniEnv_get();
2346 S3JniDb_mutex_enter;
2347 ps = jc->pdbOpening ? jc->pdbOpening : S3JniDb_from_c(pDb);
2348 if( !ps ){
2349 *pzErr = sqlite3_mprintf("Unexpected arrival of null S3JniDb in "
2350 "auto-extension runner.");
2351 S3JniDb_mutex_leave;
2352 return SQLITE_ERROR;
2353 }
2354 assert( ps->jDb );
2355 if( !ps->pDb ){
2356 assert( jc->pdbOpening == ps );
2357 rc = sqlite3_set_clientdata(pDb, S3JniDb_clientdata_key,
2358 ps, 0/* we'll re-set this after open()
2359 completes. */);
2360 if( rc ){
2361 S3JniDb_mutex_leave;
2362 return rc;
2363 }
2364 }
2365 else{
2366 assert( ps == jc->pdbOpening );
2367 jc->pdbOpening = 0;
2368 }
2369 S3JniDb_mutex_leave;
2370 NativePointerHolder_set(S3JniNph(sqlite3), ps->jDb, pDb)
2371 /* As of here, the Java/C connection is complete except for the
2372 (temporary) lack of finalizer for the ps object. */;
2373 ps->pDb = pDb;
2374 for( i = 0; go && 0==rc; ++i ){
2375 S3JniAutoExtension ax = S3JniHook_empty
2376 /* We need a copy of the auto-extension object, with our own
2377 ** local reference to it, to avoid a race condition with another
2378 ** thread manipulating the list during the call and invaliding
2379 ** what ax references. */;
2380 S3JniAutoExt_mutex_enter;
2381 if( i >= SJG.autoExt.nExt ){
2382 go = 0;
2383 }else{
2384 S3JniHook_localdup(&SJG.autoExt.aExt[i], &ax);
2385 }
2386 S3JniAutoExt_mutex_leave;
2387 if( ax.jObj ){
2388 rc = (*env)->CallIntMethod(env, ax.jObj, ax.midCallback, ps->jDb);
2389 S3JniHook_localundup(ax);
2390 S3JniIfThrew {
2391 jthrowable const ex = (*env)->ExceptionOccurred(env);
2392 char * zMsg;
2393 S3JniExceptionClear;
2394 zMsg = s3jni_exception_error_msg(env, ex);
2395 S3JniUnrefLocal(ex);
2396 *pzErr = sqlite3_mprintf("auto-extension threw: %s", zMsg);
2397 sqlite3_free(zMsg);
2398 rc = SQLITE_ERROR;
2399 }
2400 }
2401 }
2402 return rc;
2403 }
2404
2405 S3JniApi(sqlite3_auto_extension(),jint,1auto_1extension)(
2406 JniArgsEnvClass, jobject jAutoExt
2407 ){
2408 int i;
2409 S3JniAutoExtension * ax = 0;
2410 int rc = 0;
2411
2412 if( !jAutoExt ) return SQLITE_MISUSE;
2413 S3JniAutoExt_mutex_enter;
2414 for( i = 0; i < SJG.autoExt.nExt; ++i ){
2415 /* Look for a match. */
2416 ax = &SJG.autoExt.aExt[i];
2417 if( ax->jObj && (*env)->IsSameObject(env, ax->jObj, jAutoExt) ){
2418 /* same object, so this is a no-op. */
2419 S3JniAutoExt_mutex_leave;
2420 return 0;
2421 }
2422 }
2423 if( i == SJG.autoExt.nExt ){
2424 assert( SJG.autoExt.nExt <= SJG.autoExt.nAlloc );
2425 if( SJG.autoExt.nExt == SJG.autoExt.nAlloc ){
2426 /* Allocate another slot. */
2427 unsigned n = 1 + SJG.autoExt.nAlloc;
2428 S3JniAutoExtension * const aNew =
2429 s3jni_realloc( SJG.autoExt.aExt, n * sizeof(*ax) );
2430 if( !aNew ){
2431 rc = SQLITE_NOMEM;
2432 }else{
2433 SJG.autoExt.aExt = aNew;
2434 ++SJG.autoExt.nAlloc;
2435 }
2436 }
2437 if( 0==rc ){
2438 ax = &SJG.autoExt.aExt[SJG.autoExt.nExt];
2439 rc = S3JniAutoExtension_init(env, ax, jAutoExt);
2440 assert( rc ? (0==ax->jObj && 0==ax->midCallback)
2441 : (0!=ax->jObj && 0!=ax->midCallback) );
2442 }
2443 }
2444 if( 0==rc ){
2445 static int once = 0;
2446 if( 0==once && ++once ){
2447 rc = sqlite3_auto_extension(
2448 (void(*)(void))s3jni_run_java_auto_extensions
2449 /* Reminder: the JNI binding of sqlite3_reset_auto_extension()
2450 ** does not call the core-lib impl. It only clears Java-side
2451 ** auto-extensions. */
2452 );
2453 if( rc ){
2454 assert( ax );
2455 S3JniAutoExtension_clear(ax);
2456 }
2457 }
2458 if( 0==rc ){
2459 ++SJG.autoExt.nExt;
2460 }
2461 }
2462 S3JniAutoExt_mutex_leave;
2463 return rc;
2464 }
2465
2466 S3JniApi(sqlite3_backup_finish(),jint,1backup_1finish)(
2467 JniArgsEnvClass, jlong jpBack
2468 ){
2469 int rc = 0;
2470 if( jpBack!=0 ){
2471 rc = sqlite3_backup_finish( LongPtrGet_sqlite3_backup(jpBack) );
2472 }
2473 return rc;
2474 }
2475
2476 S3JniApi(sqlite3_backup_init(),jobject,1backup_1init)(
2477 JniArgsEnvClass, jlong jpDbDest, jstring jTDest,
2478 jlong jpDbSrc, jstring jTSrc
2479 ){
2480 sqlite3 * const pDest = LongPtrGet_sqlite3(jpDbDest);
2481 sqlite3 * const pSrc = LongPtrGet_sqlite3(jpDbSrc);
2482 char * const zDest = s3jni_jstring_to_utf8(jTDest, 0);
2483 char * const zSrc = s3jni_jstring_to_utf8(jTSrc, 0);
2484 jobject rv = 0;
2485
2486 if( pDest && pSrc && zDest && zSrc ){
2487 sqlite3_backup * const pB =
2488 sqlite3_backup_init(pDest, zDest, pSrc, zSrc);
2489 if( pB ){
2490 rv = new_java_sqlite3_backup(env, pB);
2491 if( !rv ){
2492 sqlite3_backup_finish( pB );
2493 }
2494 }
2495 }
2496 sqlite3_free(zDest);
2497 sqlite3_free(zSrc);
2498 return rv;
2499 }
2500
2501 S3JniApi(sqlite3_backup_pagecount(),jint,1backup_1pagecount)(
2502 JniArgsEnvClass, jlong jpBack
2503 ){
2504 return sqlite3_backup_pagecount(LongPtrGet_sqlite3_backup(jpBack));
2505 }
2506
2507 S3JniApi(sqlite3_backup_remaining(),jint,1backup_1remaining)(
2508 JniArgsEnvClass, jlong jpBack
2509 ){
2510 return sqlite3_backup_remaining(LongPtrGet_sqlite3_backup(jpBack));
2511 }
2512
2513 S3JniApi(sqlite3_backup_step(),jint,1backup_1step)(
2514 JniArgsEnvClass, jlong jpBack, jint nPage
2515 ){
2516 return sqlite3_backup_step(LongPtrGet_sqlite3_backup(jpBack), (int)nPage);
2517 }
2518
2519 S3JniApi(sqlite3_bind_blob(),jint,1bind_1blob)(
2520 JniArgsEnvClass, jlong jpStmt, jint ndx, jbyteArray baData, jint nMax
2521 ){
2522 jsize nBA = 0;
2523 jbyte * const pBuf = baData ? s3jni_jbyteArray_bytes2(baData, &nBA) : 0;
2524 int rc;
2525 if( pBuf ){
2526 if( nMax>nBA ){
2527 nMax = nBA;
2528 }
2529 rc = sqlite3_bind_blob(LongPtrGet_sqlite3_stmt(jpStmt), (int)ndx,
2530 pBuf, (int)nMax, SQLITE_TRANSIENT);
2531 s3jni_jbyteArray_release(baData, pBuf);
2532 }else{
2533 rc = baData
2534 ? SQLITE_NOMEM
2535 : sqlite3_bind_null( LongPtrGet_sqlite3_stmt(jpStmt), ndx );
2536 }
2537 return (jint)rc;
2538 }
2539
2540 /**
2541 Helper for use with s3jni_setup_nio_args().
2542 */
2543 struct S3JniNioArgs {
2544 jobject jBuf; /* input - ByteBuffer */
2545 jint iOffset; /* input - byte offset */
2546 jint iHowMany; /* input - byte count to bind/read/write */
2547 jint nBuf; /* output - jBuf's buffer size */
2548 void * p; /* output - jBuf's buffer memory */
2549 void * pStart; /* output - offset of p to bind/read/write */
2550 int nOut; /* output - number of bytes from pStart to bind/read/write */
2551 };
2552 typedef struct S3JniNioArgs S3JniNioArgs;
2553 static const S3JniNioArgs S3JniNioArgs_empty = {
2554 0,0,0,0,0,0,0
2555 };
2556
2557 /*
2558 ** Internal helper for sqlite3_bind_nio_buffer(),
2559 ** sqlite3_result_nio_buffer(), and similar methods which take a
2560 ** ByteBuffer object as either input or output. Populates pArgs and
2561 ** returns 0 on success, non-0 if the operation should fail. The
2562 ** caller is required to check for SJG.g.byteBuffer.klazz!=0 before calling
2563 ** this and reporting it in a way appropriate for that routine. This
2564 ** function may assert() that SJG.g.byteBuffer.klazz is not 0.
2565 **
2566 ** The (jBuffer, iOffset, iHowMany) arguments are the (ByteBuffer, offset,
2567 ** length) arguments to the bind/result method.
2568 **
2569 ** If iHowMany is negative then it's treated as "until the end" and
2570 ** the calculated slice is trimmed to fit if needed. If iHowMany is
2571 ** positive and extends past the end of jBuffer then SQLITE_ERROR is
2572 ** returned.
2573 **
2574 ** Returns 0 if everything looks to be in order, else some SQLITE_...
2575 ** result code
2576 */
2577 static int s3jni_setup_nio_args(
2578 JNIEnv *env, S3JniNioArgs * pArgs,
2579 jobject jBuffer, jint iOffset, jint iHowMany
2580 ){
2581 jlong iEnd = 0;
2582 const int bAllowTruncate = iHowMany<0;
2583 *pArgs = S3JniNioArgs_empty;
2584 pArgs->jBuf = jBuffer;
2585 pArgs->iOffset = iOffset;
2586 pArgs->iHowMany = iHowMany;
2587 assert( SJG.g.byteBuffer.klazz );
2588 if( pArgs->iOffset<0 ){
2589 return SQLITE_ERROR
2590 /* SQLITE_MISUSE or SQLITE_RANGE would fit better but we use
2591 SQLITE_ERROR for consistency with the code documented for a
2592 negative target blob offset in sqlite3_blob_read/write(). */;
2593 }
2594 s3jni_get_nio_buffer(pArgs->jBuf, &pArgs->p, &pArgs->nBuf);
2595 if( !pArgs->p ){
2596 return SQLITE_MISUSE;
2597 }else if( pArgs->iOffset>=pArgs->nBuf ){
2598 pArgs->pStart = 0;
2599 pArgs->nOut = 0;
2600 return 0;
2601 }
2602 assert( pArgs->nBuf > 0 );
2603 assert( pArgs->iOffset < pArgs->nBuf );
2604 iEnd = pArgs->iHowMany<0
2605 ? pArgs->nBuf - pArgs->iOffset
2606 : pArgs->iOffset + pArgs->iHowMany;
2607 if( iEnd>(jlong)pArgs->nBuf ){
2608 if( bAllowTruncate ){
2609 iEnd = pArgs->nBuf - pArgs->iOffset;
2610 }else{
2611 return SQLITE_ERROR
2612 /* again: for consistency with blob_read/write(), though
2613 SQLITE_MISUSE or SQLITE_RANGE would be a better fit. */;
2614 }
2615 }
2616 if( iEnd - pArgs->iOffset > (jlong)SQLITE_MAX_LENGTH ){
2617 return SQLITE_TOOBIG;
2618 }
2619 assert( pArgs->iOffset >= 0 );
2620 assert( iEnd > pArgs->iOffset );
2621 pArgs->pStart = pArgs->p + pArgs->iOffset;
2622 pArgs->nOut = (int)(iEnd - pArgs->iOffset);
2623 assert( pArgs->nOut > 0 );
2624 assert( (pArgs->pStart + pArgs->nOut) <= (pArgs->p + pArgs->nBuf) );
2625 return 0;
2626 }
2627
2628 S3JniApi(sqlite3_bind_nio_buffer(),jint,1bind_1nio_1buffer)(
2629 JniArgsEnvClass, jobject jpStmt, jint ndx, jobject jBuffer,
2630 jint iOffset, jint iN
2631 ){
2632 sqlite3_stmt * pStmt = PtrGet_sqlite3_stmt(jpStmt);
2633 S3JniNioArgs args;
2634 int rc;
2635 if( !pStmt || !SJG.g.byteBuffer.klazz ) return SQLITE_MISUSE;
2636 rc = s3jni_setup_nio_args(env, &args, jBuffer, iOffset, iN);
2637 if(rc){
2638 return rc;
2639 }else if( !args.pStart || !args.nOut ){
2640 return sqlite3_bind_null(pStmt, ndx);
2641 }
2642 return sqlite3_bind_blob( pStmt, (int)ndx, args.pStart,
2643 args.nOut, SQLITE_TRANSIENT );
2644 }
2645
2646 S3JniApi(sqlite3_bind_double(),jint,1bind_1double)(
2647 JniArgsEnvClass, jlong jpStmt, jint ndx, jdouble val
2648 ){
2649 return (jint)sqlite3_bind_double(LongPtrGet_sqlite3_stmt(jpStmt),
2650 (int)ndx, (double)val);
2651 }
2652
2653 S3JniApi(sqlite3_bind_int(),jint,1bind_1int)(
2654 JniArgsEnvClass, jlong jpStmt, jint ndx, jint val
2655 ){
2656 return (jint)sqlite3_bind_int(LongPtrGet_sqlite3_stmt(jpStmt), (int)ndx, (int)val);
2657 }
2658
2659 S3JniApi(sqlite3_bind_int64(),jint,1bind_1int64)(
2660 JniArgsEnvClass, jlong jpStmt, jint ndx, jlong val
2661 ){
2662 return (jint)sqlite3_bind_int64(LongPtrGet_sqlite3_stmt(jpStmt), (int)ndx, (sqlite3_int64)val);
2663 }
2664
2665 /*
2666 ** Bind a new global ref to Object `val` using sqlite3_bind_pointer().
2667 */
2668 S3JniApi(sqlite3_bind_java_object(),jint,1bind_1java_1object)(
2669 JniArgsEnvClass, jlong jpStmt, jint ndx, jobject val
2670 ){
2671 sqlite3_stmt * const pStmt = LongPtrGet_sqlite3_stmt(jpStmt);
2672 int rc = SQLITE_MISUSE;
2673
2674 if(pStmt){
2675 jobject const rv = S3JniRefGlobal(val);
2676 if( rv ){
2677 rc = sqlite3_bind_pointer(pStmt, ndx, rv, s3jni__value_jref_key,
2678 S3Jni_jobject_finalizer);
2679 }else if(val){
2680 rc = SQLITE_NOMEM;
2681 }else{
2682 rc = sqlite3_bind_null(pStmt, ndx);
2683 }
2684 }
2685 return rc;
2686 }
2687
2688 S3JniApi(sqlite3_bind_null(),jint,1bind_1null)(
2689 JniArgsEnvClass, jlong jpStmt, jint ndx
2690 ){
2691 return (jint)sqlite3_bind_null(LongPtrGet_sqlite3_stmt(jpStmt), (int)ndx);
2692 }
2693
2694 S3JniApi(sqlite3_bind_parameter_count(),jint,1bind_1parameter_1count)(
2695 JniArgsEnvClass, jlong jpStmt
2696 ){
2697 return (jint)sqlite3_bind_parameter_count(LongPtrGet_sqlite3_stmt(jpStmt));
2698 }
2699
2700 S3JniApi(sqlite3_bind_parameter_index(),jint,1bind_1parameter_1index)(
2701 JniArgsEnvClass, jlong jpStmt, jbyteArray jName
2702 ){
2703 int rc = 0;
2704 jbyte * const pBuf = s3jni_jbyteArray_bytes(jName);
2705 if( pBuf ){
2706 rc = sqlite3_bind_parameter_index(LongPtrGet_sqlite3_stmt(jpStmt),
2707 (const char *)pBuf);
2708 s3jni_jbyteArray_release(jName, pBuf);
2709 }
2710 return rc;
2711 }
2712
2713 S3JniApi(sqlite3_bind_parameter_name(),jstring,1bind_1parameter_1name)(
2714 JniArgsEnvClass, jlong jpStmt, jint ndx
2715 ){
2716 const char *z =
2717 sqlite3_bind_parameter_name(LongPtrGet_sqlite3_stmt(jpStmt), (int)ndx);
2718 return z ? s3jni_utf8_to_jstring(z, -1) : 0;
2719 }
2720
2721 /*
2722 ** Impl of sqlite3_bind_text/text16().
2723 */
2724 static int s3jni__bind_text(int is16, JNIEnv *env, jlong jpStmt, jint ndx,
2725 jbyteArray baData, jint nMax){
2726 jsize nBA = 0;
2727 jbyte * const pBuf =
2728 baData ? s3jni_jbyteArray_bytes2(baData, &nBA) : 0;
2729 int rc;
2730 if( pBuf ){
2731 if( nMax>nBA ){
2732 nMax = nBA;
2733 }
2734 /* Note that we rely on the Java layer having assured that baData
2735 is NUL-terminated if nMax is negative. In order to avoid UB for
2736 such cases, we do not expose the byte-limit arguments in the
2737 public API. */
2738 rc = is16
2739 ? sqlite3_bind_text16(LongPtrGet_sqlite3_stmt(jpStmt), (int)ndx,
2740 pBuf, (int)nMax, SQLITE_TRANSIENT)
2741 : sqlite3_bind_text(LongPtrGet_sqlite3_stmt(jpStmt), (int)ndx,
2742 (const char *)pBuf,
2743 (int)nMax, SQLITE_TRANSIENT);
2744 }else{
2745 rc = baData
2746 ? sqlite3_bind_null(LongPtrGet_sqlite3_stmt(jpStmt), (int)ndx)
2747 : SQLITE_NOMEM;
2748 }
2749 s3jni_jbyteArray_release(baData, pBuf);
2750 return (jint)rc;
2751
2752 }
2753
2754 S3JniApi(sqlite3_bind_text(),jint,1bind_1text)(
2755 JniArgsEnvClass, jlong jpStmt, jint ndx, jbyteArray baData, jint nMax
2756 ){
2757 return s3jni__bind_text(0, env, jpStmt, ndx, baData, nMax);
2758 }
2759
2760 S3JniApi(sqlite3_bind_text16(),jint,1bind_1text16)(
2761 JniArgsEnvClass, jlong jpStmt, jint ndx, jbyteArray baData, jint nMax
2762 ){
2763 return s3jni__bind_text(1, env, jpStmt, ndx, baData, nMax);
2764 }
2765
2766 S3JniApi(sqlite3_bind_value(),jint,1bind_1value)(
2767 JniArgsEnvClass, jlong jpStmt, jint ndx, jlong jpValue
2768 ){
2769 int rc = 0;
2770 sqlite3_stmt * pStmt = LongPtrGet_sqlite3_stmt(jpStmt);
2771 if( pStmt ){
2772 sqlite3_value *v = LongPtrGet_sqlite3_value(jpValue);
2773 if( v ){
2774 rc = sqlite3_bind_value(pStmt, (int)ndx, v);
2775 }else{
2776 rc = sqlite3_bind_null(pStmt, (int)ndx);
2777 }
2778 }else{
2779 rc = SQLITE_MISUSE;
2780 }
2781 return (jint)rc;
2782 }
2783
2784 S3JniApi(sqlite3_bind_zeroblob(),jint,1bind_1zeroblob)(
2785 JniArgsEnvClass, jlong jpStmt, jint ndx, jint n
2786 ){
2787 return (jint)sqlite3_bind_zeroblob(LongPtrGet_sqlite3_stmt(jpStmt),
2788 (int)ndx, (int)n);
2789 }
2790
2791 S3JniApi(sqlite3_bind_zeroblob64(),jint,1bind_1zeroblob64)(
2792 JniArgsEnvClass, jlong jpStmt, jint ndx, jlong n
2793 ){
2794 return (jint)sqlite3_bind_zeroblob64(LongPtrGet_sqlite3_stmt(jpStmt),
2795 (int)ndx, (sqlite3_uint64)n);
2796 }
2797
2798 S3JniApi(sqlite3_blob_bytes(),jint,1blob_1bytes)(
2799 JniArgsEnvClass, jlong jpBlob
2800 ){
2801 return sqlite3_blob_bytes(LongPtrGet_sqlite3_blob(jpBlob));
2802 }
2803
2804 S3JniApi(sqlite3_blob_close(),jint,1blob_1close)(
2805 JniArgsEnvClass, jlong jpBlob
2806 ){
2807 sqlite3_blob * const b = LongPtrGet_sqlite3_blob(jpBlob);
2808 return b ? (jint)sqlite3_blob_close(b) : SQLITE_MISUSE;
2809 }
2810
2811 S3JniApi(sqlite3_blob_open(),jint,1blob_1open)(
2812 JniArgsEnvClass, jlong jpDb, jstring jDbName, jstring jTbl, jstring jCol,
2813 jlong jRowId, jint flags, jobject jOut
2814 ){
2815 sqlite3 * const db = LongPtrGet_sqlite3(jpDb);
2816 sqlite3_blob * pBlob = 0;
2817 char * zDbName = 0, * zTableName = 0, * zColumnName = 0;
2818 int rc;
2819
2820 if( !db || !jDbName || !jTbl || !jCol ) return SQLITE_MISUSE;
2821 zDbName = s3jni_jstring_to_utf8(jDbName,0);
2822 zTableName = zDbName ? s3jni_jstring_to_utf8(jTbl,0) : 0;
2823 zColumnName = zTableName ? s3jni_jstring_to_utf8(jCol,0) : 0;
2824 rc = zColumnName
2825 ? sqlite3_blob_open(db, zDbName, zTableName, zColumnName,
2826 (sqlite3_int64)jRowId, (int)flags, &pBlob)
2827 : SQLITE_NOMEM;
2828 if( 0==rc ){
2829 jobject rv = new_java_sqlite3_blob(env, pBlob);
2830 if( !rv ){
2831 sqlite3_blob_close(pBlob);
2832 rc = SQLITE_NOMEM;
2833 }
2834 OutputPointer_set_obj(env, S3JniNph(OutputPointer_sqlite3_blob), jOut, rv);
2835 }
2836 sqlite3_free(zDbName);
2837 sqlite3_free(zTableName);
2838 sqlite3_free(zColumnName);
2839 return rc;
2840 }
2841
2842 S3JniApi(sqlite3_blob_read(),jint,1blob_1read)(
2843 JniArgsEnvClass, jlong jpBlob, jbyteArray jTgt, jint iOffset
2844 ){
2845 jbyte * const pBa = s3jni_jbyteArray_bytes(jTgt);
2846 int rc = jTgt ? (pBa ? SQLITE_MISUSE : SQLITE_NOMEM) : SQLITE_MISUSE;
2847 if( pBa ){
2848 jsize const nTgt = (*env)->GetArrayLength(env, jTgt);
2849 rc = sqlite3_blob_read(LongPtrGet_sqlite3_blob(jpBlob), pBa,
2850 (int)nTgt, (int)iOffset);
2851 if( 0==rc ){
2852 s3jni_jbyteArray_commit(jTgt, pBa);
2853 }else{
2854 s3jni_jbyteArray_release(jTgt, pBa);
2855 }
2856 }
2857 return rc;
2858 }
2859
2860 S3JniApi(sqlite3_blob_read_nio_buffer(),jint,1blob_1read_1nio_1buffer)(
2861 JniArgsEnvClass, jlong jpBlob, jint iSrcOff, jobject jBB, jint iTgtOff, jint iHowMany
2862 ){
2863 sqlite3_blob * const b = LongPtrGet_sqlite3_blob(jpBlob);
2864 S3JniNioArgs args;
2865 int rc;
2866 if( !b || !SJG.g.byteBuffer.klazz || iHowMany<0 ){
2867 return SQLITE_MISUSE;
2868 }else if( iTgtOff<0 || iSrcOff<0 ){
2869 return SQLITE_ERROR
2870 /* for consistency with underlying sqlite3_blob_read() */;
2871 }else if( 0==iHowMany ){
2872 return 0;
2873 }
2874 rc = s3jni_setup_nio_args(env, &args, jBB, iTgtOff, iHowMany);
2875 if(rc){
2876 return rc;
2877 }else if( !args.pStart || !args.nOut ){
2878 return 0;
2879 }
2880 assert( args.iHowMany>0 );
2881 return sqlite3_blob_read( b, args.pStart, (int)args.nOut, (int)iSrcOff );
2882 }
2883
2884 S3JniApi(sqlite3_blob_reopen(),jint,1blob_1reopen)(
2885 JniArgsEnvClass, jlong jpBlob, jlong iNewRowId
2886 ){
2887 return (jint)sqlite3_blob_reopen(LongPtrGet_sqlite3_blob(jpBlob),
2888 (sqlite3_int64)iNewRowId);
2889 }
2890
2891 S3JniApi(sqlite3_blob_write(),jint,1blob_1write)(
2892 JniArgsEnvClass, jlong jpBlob, jbyteArray jBa, jint iOffset
2893 ){
2894 sqlite3_blob * const b = LongPtrGet_sqlite3_blob(jpBlob);
2895 jbyte * const pBuf = b ? s3jni_jbyteArray_bytes(jBa) : 0;
2896 const jsize nBA = pBuf ? (*env)->GetArrayLength(env, jBa) : 0;
2897 int rc = SQLITE_MISUSE;
2898 if(b && pBuf){
2899 rc = sqlite3_blob_write( b, pBuf, (int)nBA, (int)iOffset );
2900 }
2901 s3jni_jbyteArray_release(jBa, pBuf);
2902 return (jint)rc;
2903 }
2904
2905 S3JniApi(sqlite3_blob_write_nio_buffer(),jint,1blob_1write_1nio_1buffer)(
2906 JniArgsEnvClass, jlong jpBlob, jint iTgtOff, jobject jBB, jint iSrcOff, jint iHowMany
2907 ){
2908 sqlite3_blob * const b = LongPtrGet_sqlite3_blob(jpBlob);
2909 S3JniNioArgs args;
2910 int rc;
2911 if( !b || !SJG.g.byteBuffer.klazz ){
2912 return SQLITE_MISUSE;
2913 }else if( iTgtOff<0 || iSrcOff<0 ){
2914 return SQLITE_ERROR
2915 /* for consistency with underlying sqlite3_blob_write() */;
2916 }else if( 0==iHowMany ){
2917 return 0;
2918 }
2919 rc = s3jni_setup_nio_args(env, &args, jBB, iSrcOff, iHowMany);
2920 if(rc){
2921 return rc;
2922 }else if( !args.pStart || !args.nOut ){
2923 return 0;
2924 }
2925 return sqlite3_blob_write( b, args.pStart, (int)args.nOut, (int)iTgtOff );
2926 }
2927
2928 /* Central C-to-Java busy handler proxy. */
2929 static int s3jni_busy_handler(void* pState, int n){
2930 S3JniDb * const ps = (S3JniDb *)pState;
2931 int rc = 0;
2932 S3JniDeclLocal_env;
2933 S3JniHook hook;
2934
2935 S3JniHook_localdup(&ps->hooks.busyHandler, &hook);
2936 if( hook.jObj ){
2937 rc = (*env)->CallIntMethod(env, hook.jObj,
2938 hook.midCallback, (jint)n);
2939 S3JniIfThrew{
2940 S3JniExceptionWarnCallbackThrew("sqlite3_busy_handler() callback");
2941 rc = s3jni_db_exception(ps->pDb, SQLITE_ERROR,
2942 "sqlite3_busy_handler() callback threw.");
2943 }
2944 S3JniHook_localundup(hook);
2945 }
2946 return rc;
2947 }
2948
2949 S3JniApi(sqlite3_busy_handler(),jint,1busy_1handler)(
2950 JniArgsEnvClass, jlong jpDb, jobject jBusy
2951 ){
2952 S3JniDb * const ps = S3JniDb_from_jlong(jpDb);
2953 S3JniHook * const pHook = ps ? &ps->hooks.busyHandler : 0;
2954 S3JniHook hook = S3JniHook_empty;
2955 int rc = 0;
2956
2957 if( !ps ) return (jint)SQLITE_MISUSE;
2958 S3JniDb_mutex_enter;
2959 if( jBusy ){
2960 if( pHook->jObj && (*env)->IsSameObject(env, pHook->jObj, jBusy) ){
2961 /* Same object - this is a no-op. */
2962 }else{
2963 jclass const klazz = (*env)->GetObjectClass(env, jBusy);
2964 hook.jObj = S3JniRefGlobal(jBusy);
2965 hook.midCallback = (*env)->GetMethodID(env, klazz, "call", "(I)I");
2966 S3JniUnrefLocal(klazz);
2967 S3JniIfThrew {
2968 rc = SQLITE_ERROR;
2969 }
2970 }
2971 }
2972 if( 0==rc ){
2973 if( jBusy ){
2974 if( hook.jObj ){ /* Replace handler */
2975 rc = sqlite3_busy_handler(ps->pDb, s3jni_busy_handler, ps);
2976 if( 0==rc ){
2977 S3JniHook_unref(pHook);
2978 *pHook = hook /* transfer Java ref ownership */;
2979 hook = S3JniHook_empty;
2980 }
2981 }/* else no-op */
2982 }else{ /* Clear handler */
2983 rc = sqlite3_busy_handler(ps->pDb, 0, 0);
2984 if( 0==rc ){
2985 S3JniHook_unref(pHook);
2986 }
2987 }
2988 }
2989 S3JniHook_unref(&hook);
2990 S3JniDb_mutex_leave;
2991 return rc;
2992 }
2993
2994 S3JniApi(sqlite3_busy_timeout(),jint,1busy_1timeout)(
2995 JniArgsEnvClass, jlong jpDb, jint ms
2996 ){
2997 S3JniDb * const ps = S3JniDb_from_jlong(jpDb);
2998 int rc = SQLITE_MISUSE;
2999 if( ps ){
3000 S3JniDb_mutex_enter;
3001 S3JniHook_unref(&ps->hooks.busyHandler);
3002 rc = sqlite3_busy_timeout(ps->pDb, (int)ms);
3003 S3JniDb_mutex_leave;
3004 }
3005 return rc;
3006 }
3007
3008 S3JniApi(sqlite3_cancel_auto_extension(),jboolean,1cancel_1auto_1extension)(
3009 JniArgsEnvClass, jobject jAutoExt
3010 ){
3011 S3JniAutoExtension * ax;
3012 jboolean rc = JNI_FALSE;
3013 int i;
3014
3015 if( !jAutoExt ){
3016 return rc;
3017 }
3018 S3JniAutoExt_mutex_enter;
3019 /* This algo corresponds to the one in the core. */
3020 for( i = SJG.autoExt.nExt-1; i >= 0; --i ){
3021 ax = &SJG.autoExt.aExt[i];
3022 if( ax->jObj && (*env)->IsSameObject(env, ax->jObj, jAutoExt) ){
3023 S3JniAutoExtension_clear(ax);
3024 /* Move final entry into this slot. */
3025 --SJG.autoExt.nExt;
3026 *ax = SJG.autoExt.aExt[SJG.autoExt.nExt];
3027 SJG.autoExt.aExt[SJG.autoExt.nExt] = S3JniHook_empty;
3028 assert( !SJG.autoExt.aExt[SJG.autoExt.nExt].jObj );
3029 rc = JNI_TRUE;
3030 break;
3031 }
3032 }
3033 S3JniAutoExt_mutex_leave;
3034 return rc;
3035 }
3036
3037 /* Wrapper for sqlite3_close(_v2)(). */
3038 static jint s3jni_close_db(JNIEnv * const env, jlong jpDb, int version){
3039 int rc = 0;
3040 S3JniDb * const ps = S3JniDb_from_jlong(jpDb);
3041
3042 assert(version == 1 || version == 2);
3043 if( ps ){
3044 rc = 1==version
3045 ? (jint)sqlite3_close(ps->pDb)
3046 : (jint)sqlite3_close_v2(ps->pDb);
3047 }
3048 return (jint)rc;
3049 }
3050
3051 S3JniApi(sqlite3_close(),jint,1close)(JniArgsEnvClass, jlong pDb){
3052 return s3jni_close_db(env, pDb, 1);
3053 }
3054
3055 S3JniApi(sqlite3_close_v2(),jint,1close_1v2)(JniArgsEnvClass, jlong pDb){
3056 return s3jni_close_db(env, pDb, 2);
3057 }
3058
3059 /*
3060 ** Assumes z is an array of unsigned short and returns the index in
3061 ** that array of the first element with the value 0.
3062 */
3063 static unsigned int s3jni_utf16_strlen(void const * z){
3064 unsigned int i = 0;
3065 const unsigned short * p = z;
3066 while( p[i] ) ++i;
3067 return i;
3068 }
3069
3070 /* Descriptive alias for use with sqlite3_collation_needed(). */
3071 typedef S3JniHook S3JniCollationNeeded;
3072
3073 /* Central C-to-Java sqlite3_collation_needed16() hook impl. */
3074 static void s3jni_collation_needed_impl16(void *pState, sqlite3 *pDb,
3075 int eTextRep, const void * z16Name){
3076 S3JniCollationNeeded * const pHook = pState;
3077 S3JniDeclLocal_env;
3078 S3JniHook hook;
3079
3080 S3JniHook_localdup(pHook, &hook);
3081 if( hook.jObj ){
3082 unsigned int const nName = s3jni_utf16_strlen(z16Name);
3083 jstring jName = (*env)->NewString(env, (jchar const *)z16Name, nName);
3084
3085 s3jni_oom_check( jName );
3086 assert( hook.jExtra );
3087 S3JniIfThrew{
3088 S3JniExceptionClear;
3089 }else if( hook.jExtra ){
3090 (*env)->CallVoidMethod(env, hook.jObj, hook.midCallback,
3091 hook.jExtra, (jint)eTextRep, jName);
3092 S3JniIfThrew{
3093 S3JniExceptionWarnCallbackThrew("sqlite3_collation_needed() callback");
3094 }
3095 }
3096 S3JniUnrefLocal(jName);
3097 S3JniHook_localundup(hook);
3098 }
3099 }
3100
3101 S3JniApi(sqlite3_collation_needed(),jint,1collation_1needed)(
3102 JniArgsEnvClass, jlong jpDb, jobject jHook
3103 ){
3104 S3JniDb * ps;
3105 S3JniCollationNeeded * pHook;
3106 int rc = 0;
3107
3108 S3JniDb_mutex_enter;
3109 ps = S3JniDb_from_jlong(jpDb);
3110 if( !ps ){
3111 S3JniDb_mutex_leave;
3112 return SQLITE_MISUSE;
3113 }
3114 pHook = &ps->hooks.collationNeeded;
3115 if( pHook->jObj && jHook &&
3116 (*env)->IsSameObject(env, pHook->jObj, jHook) ){
3117 /* no-op */
3118 }else if( !jHook ){
3119 rc = sqlite3_collation_needed(ps->pDb, 0, 0);
3120 if( 0==rc ){
3121 S3JniHook_unref(pHook);
3122 }
3123 }else{
3124 jclass const klazz = (*env)->GetObjectClass(env, jHook);
3125 jmethodID const xCallback = (*env)->GetMethodID(
3126 env, klazz, "call", "(Lorg/sqlite/jni/capi/sqlite3;ILjava/lang/String;)V"
3127 );
3128 S3JniUnrefLocal(klazz);
3129 S3JniIfThrew {
3130 rc = s3jni_db_exception(ps->pDb, SQLITE_MISUSE,
3131 "Cannot not find matching call() in "
3132 "CollationNeededCallback object.");
3133 }else{
3134 rc = sqlite3_collation_needed16(ps->pDb, pHook,
3135 s3jni_collation_needed_impl16);
3136 if( 0==rc ){
3137 S3JniHook_unref(pHook);
3138 pHook->midCallback = xCallback;
3139 pHook->jObj = S3JniRefGlobal(jHook);
3140 pHook->jExtra = S3JniRefGlobal(ps->jDb);
3141 }
3142 }
3143 }
3144 S3JniDb_mutex_leave;
3145 return rc;
3146 }
3147
3148 S3JniApi(sqlite3_column_blob(),jbyteArray,1column_1blob)(
3149 JniArgsEnvClass, jobject jpStmt, jint ndx
3150 ){
3151 sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt);
3152 void const * const p = sqlite3_column_blob(pStmt, (int)ndx);
3153 int const n = p ? sqlite3_column_bytes(pStmt, (int)ndx) : 0;
3154
3155 return p ? s3jni_new_jbyteArray(p, n) : 0;
3156 }
3157
3158 S3JniApi(sqlite3_column_double(),jdouble,1column_1double)(
3159 JniArgsEnvClass, jobject jpStmt, jint ndx
3160 ){
3161 return (jdouble)sqlite3_column_double(PtrGet_sqlite3_stmt(jpStmt), (int)ndx);
3162 }
3163
3164 S3JniApi(sqlite3_column_int(),jint,1column_1int)(
3165 JniArgsEnvClass, jobject jpStmt, jint ndx
3166 ){
3167 return (jint)sqlite3_column_int(PtrGet_sqlite3_stmt(jpStmt), (int)ndx);
3168 }
3169
3170 S3JniApi(sqlite3_column_int64(),jlong,1column_1int64)(
3171 JniArgsEnvClass, jobject jpStmt, jint ndx
3172 ){
3173 return (jlong)sqlite3_column_int64(PtrGet_sqlite3_stmt(jpStmt), (int)ndx);
3174 }
3175
3176 S3JniApi(sqlite3_column_java_object(),jobject,1column_1java_1object)(
3177 JniArgsEnvClass, jlong jpStmt, jint ndx
3178 ){
3179 sqlite3_stmt * const stmt = LongPtrGet_sqlite3_stmt(jpStmt);
3180 jobject rv = 0;
3181 if( stmt ){
3182 sqlite3 * const db = sqlite3_db_handle(stmt);
3183 sqlite3_value * sv;
3184 sqlite3_mutex_enter(sqlite3_db_mutex(db));
3185 sv = sqlite3_column_value(stmt, (int)ndx);
3186 if( sv ){
3187 rv = S3JniRefLocal(
3188 sqlite3_value_pointer(sv, s3jni__value_jref_key)
3189 );
3190 }
3191 sqlite3_mutex_leave(sqlite3_db_mutex(db));
3192 }
3193 return rv;
3194 }
3195
3196 S3JniApi(sqlite3_column_nio_buffer(),jobject,1column_1nio_1buffer)(
3197 JniArgsEnvClass, jobject jStmt, jint ndx
3198 ){
3199 sqlite3_stmt * const stmt = PtrGet_sqlite3_stmt(jStmt);
3200 jobject rv = 0;
3201 if( stmt ){
3202 const void * const p = sqlite3_column_blob(stmt, (int)ndx);
3203 if( p ){
3204 const int n = sqlite3_column_bytes(stmt, (int)ndx);
3205 rv = s3jni__blob_to_ByteBuffer(env, p, n);
3206 }
3207 }
3208 return rv;
3209 }
3210
3211 S3JniApi(sqlite3_column_text(),jbyteArray,1column_1text)(
3212 JniArgsEnvClass, jobject jpStmt, jint ndx
3213 ){
3214 sqlite3_stmt * const stmt = PtrGet_sqlite3_stmt(jpStmt);
3215 const unsigned char * const p = stmt ? sqlite3_column_text(stmt, (int)ndx) : 0;
3216 const int n = p ? sqlite3_column_bytes(stmt, (int)ndx) : 0;
3217 return p ? s3jni_new_jbyteArray(p, n) : NULL;
3218 }
3219
3220 #if 0
3221 // this impl might prove useful.
3222 S3JniApi(sqlite3_column_text(),jstring,1column_1text)(
3223 JniArgsEnvClass, jobject jpStmt, jint ndx
3224 ){
3225 sqlite3_stmt * const stmt = PtrGet_sqlite3_stmt(jpStmt);
3226 const unsigned char * const p = stmt ? sqlite3_column_text(stmt, (int)ndx) : 0;
3227 const int n = p ? sqlite3_column_bytes(stmt, (int)ndx) : 0;
3228 return p ? s3jni_utf8_to_jstring( (const char *)p, n) : 0;
3229 }
3230 #endif
3231
3232 S3JniApi(sqlite3_column_text16(),jstring,1column_1text16)(
3233 JniArgsEnvClass, jobject jpStmt, jint ndx
3234 ){
3235 sqlite3_stmt * const stmt = PtrGet_sqlite3_stmt(jpStmt);
3236 const void * const p = stmt ? sqlite3_column_text16(stmt, (int)ndx) : 0;
3237 const int n = p ? sqlite3_column_bytes16(stmt, (int)ndx) : 0;
3238 return s3jni_text16_to_jstring(env, p, n);
3239 }
3240
3241 S3JniApi(sqlite3_column_value(),jobject,1column_1value)(
3242 JniArgsEnvClass, jobject jpStmt, jint ndx
3243 ){
3244 sqlite3_value * const sv =
3245 sqlite3_column_value(PtrGet_sqlite3_stmt(jpStmt), (int)ndx)
3246 /* reminder: returns an SQL NULL if jpStmt==NULL */;
3247 return new_java_sqlite3_value(env, sv);
3248 }
3249
3250 /*
3251 ** Impl for commit hooks (if isCommit is true) or rollback hooks.
3252 */
3253 static int s3jni_commit_rollback_hook_impl(int isCommit, S3JniDb * const ps){
3254 S3JniDeclLocal_env;
3255 int rc = 0;
3256 S3JniHook hook;
3257
3258 S3JniHook_localdup(isCommit
3259 ? &ps->hooks.commit : &ps->hooks.rollback,
3260 &hook);
3261 if( hook.jObj ){
3262 rc = isCommit
3263 ? (int)(*env)->CallIntMethod(env, hook.jObj, hook.midCallback)
3264 : (int)((*env)->CallVoidMethod(env, hook.jObj, hook.midCallback), 0);
3265 S3JniIfThrew{
3266 rc = s3jni_db_exception(ps->pDb, SQLITE_ERROR,
3267 isCommit
3268 ? "Commit hook callback threw"
3269 : "Rollback hook callback threw");
3270 }
3271 S3JniHook_localundup(hook);
3272 }
3273 return rc;
3274 }
3275
3276 /* C-to-Java commit hook wrapper. */
3277 static int s3jni_commit_hook_impl(void *pP){
3278 return s3jni_commit_rollback_hook_impl(1, pP);
3279 }
3280
3281 /* C-to-Java rollback hook wrapper. */
3282 static void s3jni_rollback_hook_impl(void *pP){
3283 (void)s3jni_commit_rollback_hook_impl(0, pP);
3284 }
3285
3286 /*
3287 ** Proxy for sqlite3_commit_hook() (if isCommit is true) or
3288 ** sqlite3_rollback_hook().
3289 */
3290 static jobject s3jni_commit_rollback_hook(int isCommit, JNIEnv * const env,
3291 jlong jpDb, jobject jHook){
3292 S3JniDb * ps;
3293 jobject pOld = 0; /* previous hoook */
3294 S3JniHook * pHook; /* ps->hooks.commit|rollback */
3295
3296 S3JniDb_mutex_enter;
3297 ps = S3JniDb_from_jlong(jpDb);
3298 if( !ps ){
3299 s3jni_db_error(ps->pDb, SQLITE_MISUSE, 0);
3300 S3JniDb_mutex_leave;
3301 return 0;
3302 }
3303 pHook = isCommit ? &ps->hooks.commit : &ps->hooks.rollback;
3304 pOld = pHook->jObj;
3305 if( pOld && jHook &&
3306 (*env)->IsSameObject(env, pOld, jHook) ){
3307 /* No-op. */
3308 }else if( !jHook ){
3309 if( pOld ){
3310 jobject tmp = S3JniRefLocal(pOld);
3311 S3JniUnrefGlobal(pOld);
3312 pOld = tmp;
3313 }
3314 *pHook = S3JniHook_empty;
3315 if( isCommit ) sqlite3_commit_hook(ps->pDb, 0, 0);
3316 else sqlite3_rollback_hook(ps->pDb, 0, 0);
3317 }else{
3318 jclass const klazz = (*env)->GetObjectClass(env, jHook);
3319 jmethodID const xCallback = (*env)->GetMethodID(env, klazz, "call",
3320 isCommit ? "()I" : "()V");
3321 S3JniUnrefLocal(klazz);
3322 S3JniIfThrew {
3323 S3JniExceptionReport;
3324 S3JniExceptionClear;
3325 s3jni_db_error(ps->pDb, SQLITE_ERROR,
3326 "Cannot not find matching call() method in"
3327 "hook object.");
3328 }else{
3329 pHook->midCallback = xCallback;
3330 pHook->jObj = S3JniRefGlobal(jHook);
3331 if( isCommit ) sqlite3_commit_hook(ps->pDb, s3jni_commit_hook_impl, ps);
3332 else sqlite3_rollback_hook(ps->pDb, s3jni_rollback_hook_impl, ps);
3333 if( pOld ){
3334 jobject tmp = S3JniRefLocal(pOld);
3335 S3JniUnrefGlobal(pOld);
3336 pOld = tmp;
3337 }
3338 }
3339 }
3340 S3JniDb_mutex_leave;
3341 return pOld;
3342 }
3343
3344 S3JniApi(sqlite3_commit_hook(),jobject,1commit_1hook)(
3345 JniArgsEnvClass, jlong jpDb, jobject jHook
3346 ){
3347 return s3jni_commit_rollback_hook(1, env, jpDb, jHook);
3348 }
3349
3350 S3JniApi(sqlite3_compileoption_get(),jstring,1compileoption_1get)(
3351 JniArgsEnvClass, jint n
3352 ){
3353 const char * z = sqlite3_compileoption_get(n);
3354 jstring const rv = z ? (*env)->NewStringUTF( env, z ) : 0;
3355 /* We know these to be ASCII, so MUTF-8 is fine. */;
3356 s3jni_oom_check(z ? !!rv : 1);
3357 return rv;
3358 }
3359
3360 S3JniApi(sqlite3_compileoption_used(),jboolean,1compileoption_1used)(
3361 JniArgsEnvClass, jstring name
3362 ){
3363 const char *zUtf8 = s3jni_jstring_to_mutf8(name)
3364 /* We know these to be ASCII, so MUTF-8 is fine (and
3365 hypothetically faster to convert). */;
3366 const jboolean rc =
3367 0==sqlite3_compileoption_used(zUtf8) ? JNI_FALSE : JNI_TRUE;
3368 s3jni_mutf8_release(name, zUtf8);
3369 return rc;
3370 }
3371
3372 S3JniApi(sqlite3_complete(),jint,1complete)(
3373 JniArgsEnvClass, jbyteArray jSql
3374 ){
3375 jbyte * const pBuf = s3jni_jbyteArray_bytes(jSql);
3376 const jsize nBA = pBuf ? (*env)->GetArrayLength(env, jSql) : 0;
3377 int rc;
3378
3379 assert( (nBA>0 ? 0==pBuf[nBA-1] : (pBuf ? 0==*pBuf : 1))
3380 && "Byte array is not NUL-terminated." );
3381 rc = (pBuf && 0==pBuf[(nBA ? nBA-1 : 0)])
3382 ? sqlite3_complete( (const char *)pBuf )
3383 : (jSql ? SQLITE_NOMEM : SQLITE_MISUSE);
3384 s3jni_jbyteArray_release(jSql, pBuf);
3385 return rc;
3386 }
3387
3388 S3JniApi(sqlite3_config() /*for a small subset of options.*/
3389 sqlite3_config__enable()/* internal name to avoid name-mangling issues*/,
3390 jint,1config_1_1enable)(JniArgsEnvClass, jint n){
3391 switch( n ){
3392 case SQLITE_CONFIG_SINGLETHREAD:
3393 case SQLITE_CONFIG_MULTITHREAD:
3394 case SQLITE_CONFIG_SERIALIZED:
3395 return sqlite3_config( n );
3396 default:
3397 return SQLITE_MISUSE;
3398 }
3399 }
3400 /* C-to-Java SQLITE_CONFIG_LOG wrapper. */
3401 static void s3jni_config_log(void *ignored, int errCode, const char *z){
3402 S3JniDeclLocal_env;
3403 S3JniHook hook = S3JniHook_empty;
3404
3405 S3JniHook_localdup(&SJG.hook.configlog, &hook);
3406 if( hook.jObj ){
3407 jstring const jArg1 = z ? s3jni_utf8_to_jstring(z, -1) : 0;
3408 if( z ? !!jArg1 : 1 ){
3409 (*env)->CallVoidMethod(env, hook.jObj, hook.midCallback, errCode, jArg1);
3410 }
3411 S3JniIfThrew{
3412 S3JniExceptionWarnCallbackThrew("SQLITE_CONFIG_LOG callback");
3413 S3JniExceptionClear;
3414 }
3415 S3JniHook_localundup(hook);
3416 S3JniUnrefLocal(jArg1);
3417 }
3418 }
3419
3420 S3JniApi(sqlite3_config() /* for SQLITE_CONFIG_LOG */
3421 sqlite3_config__config_log() /* internal name */,
3422 jint, 1config_1_1CONFIG_1LOG
3423 )(JniArgsEnvClass, jobject jLog){
3424 S3JniHook * const pHook = &SJG.hook.configlog;
3425 int rc = 0;
3426
3427 S3JniGlobal_mutex_enter;
3428 if( !jLog ){
3429 rc = sqlite3_config( SQLITE_CONFIG_LOG, NULL, NULL );
3430 if( 0==rc ){
3431 S3JniHook_unref(pHook);
3432 }
3433 }else if( pHook->jObj && (*env)->IsSameObject(env, jLog, pHook->jObj) ){
3434 /* No-op */
3435 }else {
3436 jclass const klazz = (*env)->GetObjectClass(env, jLog);
3437 jmethodID const midCallback = (*env)->GetMethodID(env, klazz, "call",
3438 "(ILjava/lang/String;)V");
3439 S3JniUnrefLocal(klazz);
3440 if( midCallback ){
3441 rc = sqlite3_config( SQLITE_CONFIG_LOG, s3jni_config_log, NULL );
3442 if( 0==rc ){
3443 S3JniHook_unref(pHook);
3444 pHook->midCallback = midCallback;
3445 pHook->jObj = S3JniRefGlobal(jLog);
3446 }
3447 }else{
3448 S3JniExceptionWarnIgnore;
3449 rc = SQLITE_ERROR;
3450 }
3451 }
3452 S3JniGlobal_mutex_leave;
3453 return rc;
3454 }
3455
3456 #ifdef SQLITE_ENABLE_SQLLOG
3457 /* C-to-Java SQLITE_CONFIG_SQLLOG wrapper. */
3458 static void s3jni_config_sqllog(void *ignored, sqlite3 *pDb, const char *z, int op){
3459 jobject jArg0 = 0;
3460 jstring jArg1 = 0;
3461 S3JniDeclLocal_env;
3462 S3JniDb * const ps = S3JniDb_from_c(pDb);
3463 S3JniHook hook = S3JniHook_empty;
3464
3465 if( ps ){
3466 S3JniHook_localdup(&SJG.hook.sqllog, &hook);
3467 }
3468 if( !hook.jObj ) return;
3469 jArg0 = S3JniRefLocal(ps->jDb);
3470 switch( op ){
3471 case 0: /* db opened */
3472 case 1: /* SQL executed */
3473 jArg1 = s3jni_utf8_to_jstring( z, -1);
3474 break;
3475 case 2: /* db closed */
3476 break;
3477 default:
3478 (*env)->FatalError(env, "Unhandled 4th arg to SQLITE_CONFIG_SQLLOG.");
3479 break;
3480 }
3481 (*env)->CallVoidMethod(env, hook.jObj, hook.midCallback, jArg0, jArg1, op);
3482 S3JniIfThrew{
3483 S3JniExceptionWarnCallbackThrew("SQLITE_CONFIG_SQLLOG callback");
3484 S3JniExceptionClear;
3485 }
3486 S3JniHook_localundup(hook);
3487 S3JniUnrefLocal(jArg0);
3488 S3JniUnrefLocal(jArg1);
3489 }
3490 //! Requirement of SQLITE_CONFIG_SQLLOG.
3491 void sqlite3_init_sqllog(void){
3492 sqlite3_config( SQLITE_CONFIG_SQLLOG, s3jni_config_sqllog, 0 );
3493 }
3494 #endif
3495
3496 S3JniApi(sqlite3_config() /* for SQLITE_CONFIG_SQLLOG */
3497 sqlite3_config__SQLLOG() /*internal name*/,
3498 jint, 1config_1_1SQLLOG
3499 )(JniArgsEnvClass, jobject jLog){
3500 #ifndef SQLITE_ENABLE_SQLLOG
3501 return SQLITE_MISUSE;
3502 #else
3503 S3JniHook * const pHook = &SJG.hook.sqllog;
3504 int rc = 0;
3505
3506 S3JniGlobal_mutex_enter;
3507 if( !jLog ){
3508 rc = sqlite3_config( SQLITE_CONFIG_SQLLOG, NULL );
3509 if( 0==rc ){
3510 S3JniHook_unref(pHook);
3511 }
3512 }else if( pHook->jObj && (*env)->IsSameObject(env, jLog, pHook->jObj) ){
3513 /* No-op */
3514 }else {
3515 jclass const klazz = (*env)->GetObjectClass(env, jLog);
3516 jmethodID const midCallback = (*env)->GetMethodID(env, klazz, "call",
3517 "(Lorg/sqlite/jni/capi/sqlite3;"
3518 "Ljava/lang/String;"
3519 "I)V");
3520 S3JniUnrefLocal(klazz);
3521 if( midCallback ){
3522 rc = sqlite3_config( SQLITE_CONFIG_SQLLOG, s3jni_config_sqllog, NULL );
3523 if( 0==rc ){
3524 S3JniHook_unref(pHook);
3525 pHook->midCallback = midCallback;
3526 pHook->jObj = S3JniRefGlobal(jLog);
3527 }
3528 }else{
3529 S3JniExceptionWarnIgnore;
3530 rc = SQLITE_ERROR;
3531 }
3532 }
3533 S3JniGlobal_mutex_leave;
3534 return rc;
3535 #endif
3536 }
3537
3538 S3JniApi(sqlite3_context_db_handle(),jobject,1context_1db_1handle)(
3539 JniArgsEnvClass, jobject jpCx
3540 ){
3541 sqlite3_context * const pCx = PtrGet_sqlite3_context(jpCx);
3542 sqlite3 * const pDb = pCx ? sqlite3_context_db_handle(pCx) : 0;
3543 S3JniDb * const ps = pDb ? S3JniDb_from_c(pDb) : 0;
3544 return ps ? ps->jDb : 0;
3545 }
3546
3547 /*
3548 ** State for CollationCallbacks. This used to be its own separate
3549 ** type, but has since been consolidated with S3JniHook. It retains
3550 ** its own typedef for code legibility and searchability reasons.
3551 */
3552 typedef S3JniHook S3JniCollationCallback;
3553
3554 /*
3555 ** Proxy for Java-side CollationCallback.xCompare() callbacks.
3556 */
3557 static int CollationCallback_xCompare(void *pArg, int nLhs, const void *lhs,
3558 int nRhs, const void *rhs){
3559 S3JniCollationCallback * const pCC = pArg;
3560 S3JniDeclLocal_env;
3561 jint rc = 0;
3562 if( pCC->jObj ){
3563 jbyteArray jbaLhs = s3jni_new_jbyteArray(lhs, (jint)nLhs);
3564 jbyteArray jbaRhs = jbaLhs
3565 ? s3jni_new_jbyteArray(rhs, (jint)nRhs) : 0;
3566 if( !jbaRhs ){
3567 S3JniUnrefLocal(jbaLhs);
3568 /* We have no recovery strategy here. */
3569 s3jni_oom_check( jbaRhs );
3570 return 0;
3571 }
3572 rc = (*env)->CallIntMethod(env, pCC->jObj, pCC->midCallback,
3573 jbaLhs, jbaRhs);
3574 S3JniExceptionIgnore;
3575 S3JniUnrefLocal(jbaLhs);
3576 S3JniUnrefLocal(jbaRhs);
3577 }
3578 return (int)rc;
3579 }
3580
3581 /* CollationCallback finalizer for use by the sqlite3 internals. */
3582 static void CollationCallback_xDestroy(void *pArg){
3583 S3JniCollationCallback * const pCC = pArg;
3584 S3JniDeclLocal_env;
3585 S3JniHook_free(pCC);
3586 }
3587
3588 S3JniApi(sqlite3_create_collation() sqlite3_create_collation_v2(),
3589 jint,1create_1collation
3590 )(JniArgsEnvClass, jobject jDb, jstring name, jint eTextRep,
3591 jobject oCollation){
3592 int rc;
3593 S3JniDb * ps;
3594
3595 if( !jDb || !name || !encodingTypeIsValid(eTextRep) ){
3596 return (jint)SQLITE_MISUSE;
3597 }
3598 S3JniDb_mutex_enter;
3599 ps = S3JniDb_from_java(jDb);
3600 jclass const klazz = (*env)->GetObjectClass(env, oCollation);
3601 jmethodID const midCallback =
3602 (*env)->GetMethodID(env, klazz, "call", "([B[B)I");
3603 S3JniUnrefLocal(klazz);
3604 S3JniIfThrew{
3605 rc = s3jni_db_error(ps->pDb, SQLITE_ERROR,
3606 "Could not get call() method from "
3607 "CollationCallback object.");
3608 }else{
3609 char * const zName = s3jni_jstring_to_utf8(name, 0);
3610 S3JniCollationCallback * const pCC =
3611 zName ? S3JniHook_alloc() : 0;
3612 if( pCC ){
3613 rc = sqlite3_create_collation_v2(ps->pDb, zName, (int)eTextRep,
3614 pCC, CollationCallback_xCompare,
3615 CollationCallback_xDestroy);
3616 if( 0==rc ){
3617 pCC->midCallback = midCallback;
3618 pCC->jObj = S3JniRefGlobal(oCollation);
3619 pCC->doXDestroy = 1;
3620 }else{
3621 CollationCallback_xDestroy(pCC);
3622 }
3623 }else{
3624 rc = SQLITE_NOMEM;
3625 }
3626 sqlite3_free(zName);
3627 }
3628 S3JniDb_mutex_leave;
3629 return (jint)rc;
3630 }
3631
3632 S3JniApi(sqlite3_create_function() sqlite3_create_function_v2()
3633 sqlite3_create_window_function(),
3634 jint,1create_1function
3635 )(JniArgsEnvClass, jobject jDb, jstring jFuncName, jint nArg,
3636 jint eTextRep, jobject jFunctor){
3637 S3JniUdf * s = 0;
3638 int rc;
3639 sqlite3 * const pDb = PtrGet_sqlite3(jDb);
3640 char * zFuncName = 0;
3641
3642 if( !pDb || !jFuncName ){
3643 return SQLITE_MISUSE;
3644 }else if( !encodingTypeIsValid(eTextRep) ){
3645 return s3jni_db_error(pDb, SQLITE_FORMAT,
3646 "Invalid function encoding option.");
3647 }
3648 s = S3JniUdf_alloc(env, jFunctor);
3649 if( !s ) return SQLITE_NOMEM;
3650
3651 if( UDF_UNKNOWN_TYPE==s->type ){
3652 rc = s3jni_db_error(pDb, SQLITE_MISUSE,
3653 "Cannot unambiguously determine function type.");
3654 S3JniUdf_free(env, s, 1);
3655 goto error_cleanup;
3656 }
3657 zFuncName = s3jni_jstring_to_utf8(jFuncName,0);
3658 if( !zFuncName ){
3659 rc = SQLITE_NOMEM;
3660 S3JniUdf_free(env, s, 1);
3661 goto error_cleanup;
3662 }
3663 s->zFuncName = zFuncName /* pass on ownership */;
3664 if( UDF_WINDOW == s->type ){
3665 rc = sqlite3_create_window_function(pDb, zFuncName, nArg, eTextRep, s,
3666 udf_xStep, udf_xFinal, udf_xValue,
3667 udf_xInverse, S3JniUdf_finalizer);
3668 }else{
3669 udf_xFunc_f xFunc = 0;
3670 udf_xStep_f xStep = 0;
3671 udf_xFinal_f xFinal = 0;
3672 if( UDF_SCALAR == s->type ){
3673 xFunc = udf_xFunc;
3674 }else{
3675 assert( UDF_AGGREGATE == s->type );
3676 xStep = udf_xStep;
3677 xFinal = udf_xFinal;
3678 }
3679 rc = sqlite3_create_function_v2(pDb, zFuncName, nArg, eTextRep, s,
3680 xFunc, xStep, xFinal, S3JniUdf_finalizer);
3681 }
3682 error_cleanup:
3683 /* Reminder: on sqlite3_create_function() error, s will be
3684 ** destroyed via create_function(). */
3685 return (jint)rc;
3686 }
3687
3688
3689 S3JniApi(sqlite3_db_config() /*for MAINDBNAME*/,
3690 jint,1db_1config__Lorg_sqlite_jni_capi_sqlite3_2ILjava_lang_String_2
3691 )(JniArgsEnvClass, jobject jDb, jint op, jstring jStr){
3692 S3JniDb * const ps = S3JniDb_from_java(jDb);
3693 int rc;
3694 char *zStr;
3695
3696 switch( (ps && jStr) ? op : 0 ){
3697 case SQLITE_DBCONFIG_MAINDBNAME:
3698 S3JniDb_mutex_enter
3699 /* Protect against a race in modifying/freeing
3700 ps->zMainDbName. */;
3701 zStr = s3jni_jstring_to_utf8( jStr, 0);
3702 if( zStr ){
3703 rc = sqlite3_db_config(ps->pDb, (int)op, zStr);
3704 if( rc ){
3705 sqlite3_free( zStr );
3706 }else{
3707 sqlite3_free( ps->zMainDbName );
3708 ps->zMainDbName = zStr;
3709 }
3710 }else{
3711 rc = SQLITE_NOMEM;
3712 }
3713 S3JniDb_mutex_leave;
3714 break;
3715 case 0:
3716 default:
3717 rc = SQLITE_MISUSE;
3718 }
3719 return rc;
3720 }
3721
3722 S3JniApi(
3723 sqlite3_db_config(),
3724 /* WARNING: openjdk v19 creates a different mangled name for this
3725 ** function than openjdk v8 does. We account for that by exporting
3726 ** both versions of the name. */
3727 jint,1db_1config__Lorg_sqlite_jni_capi_sqlite3_2IILorg_sqlite_jni_capi_OutputPointer_Int32_2
3728 )(
3729 JniArgsEnvClass, jobject jDb, jint op, jint onOff, jobject jOut
3730 ){
3731 S3JniDb * const ps = S3JniDb_from_java(jDb);
3732 int rc;
3733 switch( ps ? op : 0 ){
3734 case SQLITE_DBCONFIG_ENABLE_FKEY:
3735 case SQLITE_DBCONFIG_ENABLE_TRIGGER:
3736 case SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:
3737 case SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:
3738 case SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:
3739 case SQLITE_DBCONFIG_ENABLE_QPSG:
3740 case SQLITE_DBCONFIG_TRIGGER_EQP:
3741 case SQLITE_DBCONFIG_RESET_DATABASE:
3742 case SQLITE_DBCONFIG_DEFENSIVE:
3743 case SQLITE_DBCONFIG_WRITABLE_SCHEMA:
3744 case SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:
3745 case SQLITE_DBCONFIG_DQS_DML:
3746 case SQLITE_DBCONFIG_DQS_DDL:
3747 case SQLITE_DBCONFIG_ENABLE_VIEW:
3748 case SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:
3749 case SQLITE_DBCONFIG_TRUSTED_SCHEMA:
3750 case SQLITE_DBCONFIG_STMT_SCANSTATUS:
3751 case SQLITE_DBCONFIG_REVERSE_SCANORDER: {
3752 int pOut = 0;
3753 rc = sqlite3_db_config( ps->pDb, (int)op, onOff, &pOut );
3754 if( 0==rc && jOut ){
3755 OutputPointer_set_Int32(env, jOut, pOut);
3756 }
3757 break;
3758 }
3759 default:
3760 rc = SQLITE_MISUSE;
3761 }
3762 return (jint)rc;
3763 }
3764
3765 /*
3766 ** This is a workaround for openjdk v19 (and possibly others) encoding
3767 ** this function's name differently than JDK v8 does. If we do not
3768 ** install both names for this function then Java will not be able to
3769 ** find the function in both environments.
3770 */
3771 JniDecl(jint,1db_1config__Lorg_sqlite_jni_capi_sqlite3_2IILorg_sqlite_jni_capi_OutputPointer_00024Int32_2)(
3772 JniArgsEnvClass, jobject jDb, jint op, jint onOff, jobject jOut
3773 ){
3774 return JniFuncName(1db_1config__Lorg_sqlite_jni_capi_sqlite3_2IILorg_sqlite_jni_capi_OutputPointer_Int32_2)(
3775 env, jKlazz, jDb, op, onOff, jOut
3776 );
3777 }
3778
3779 S3JniApi(sqlite3_db_filename(),jstring,1db_1filename)(
3780 JniArgsEnvClass, jobject jDb, jstring jDbName
3781 ){
3782 S3JniDb * const ps = S3JniDb_from_java(jDb);
3783 char *zDbName;
3784 jstring jRv = 0;
3785 int nStr = 0;
3786
3787 if( !ps || !jDbName ){
3788 return 0;
3789 }
3790 zDbName = s3jni_jstring_to_utf8( jDbName, &nStr);
3791 if( zDbName ){
3792 char const * zRv = sqlite3_db_filename(ps->pDb, zDbName);
3793 sqlite3_free(zDbName);
3794 if( zRv ){
3795 jRv = s3jni_utf8_to_jstring( zRv, -1);
3796 }
3797 }
3798 return jRv;
3799 }
3800
3801 S3JniApi(sqlite3_db_handle(),jobject,1db_1handle)(
3802 JniArgsEnvClass, jobject jpStmt
3803 ){
3804 sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt);
3805 sqlite3 * const pDb = pStmt ? sqlite3_db_handle(pStmt) : 0;
3806 S3JniDb * const ps = pDb ? S3JniDb_from_c(pDb) : 0;
3807 return ps ? ps->jDb : 0;
3808 }
3809
3810 S3JniApi(sqlite3_db_readonly(),jint,1db_1readonly)(
3811 JniArgsEnvClass, jobject jDb, jstring jDbName
3812 ){
3813 int rc = 0;
3814 S3JniDb * const ps = S3JniDb_from_java(jDb);
3815 char *zDbName = jDbName ? s3jni_jstring_to_utf8( jDbName, 0 ) : 0;
3816 rc = sqlite3_db_readonly(ps ? ps->pDb : 0, zDbName);
3817 sqlite3_free(zDbName);
3818 return (jint)rc;
3819 }
3820
3821 S3JniApi(sqlite3_db_release_memory(),jint,1db_1release_1memory)(
3822 JniArgsEnvClass, jobject jDb
3823 ){
3824 sqlite3 * const pDb = PtrGet_sqlite3(jDb);
3825 return pDb ? sqlite3_db_release_memory(pDb) : SQLITE_MISUSE;
3826 }
3827
3828 S3JniApi(sqlite3_db_status(),jint,1db_1status)(
3829 JniArgsEnvClass, jobject jDb, jint op, jobject jOutCurrent,
3830 jobject jOutHigh, jboolean reset
3831 ){
3832 int iCur = 0, iHigh = 0;
3833 sqlite3 * const pDb = PtrGet_sqlite3(jDb);
3834 int rc = sqlite3_db_status( pDb, op, &iCur, &iHigh, reset );
3835 if( 0==rc ){
3836 OutputPointer_set_Int32(env, jOutCurrent, iCur);
3837 OutputPointer_set_Int32(env, jOutHigh, iHigh);
3838 }
3839 return (jint)rc;
3840 }
3841
3842 S3JniApi(sqlite3_errcode(),jint,1errcode)(
3843 JniArgsEnvClass, jobject jpDb
3844 ){
3845 sqlite3 * const pDb = PtrGet_sqlite3(jpDb);
3846 return pDb ? sqlite3_errcode(pDb) : SQLITE_MISUSE;
3847 }
3848
3849 S3JniApi(sqlite3_errmsg(),jstring,1errmsg)(
3850 JniArgsEnvClass, jobject jpDb
3851 ){
3852 sqlite3 * const pDb = PtrGet_sqlite3(jpDb);
3853 return pDb ? s3jni_utf8_to_jstring( sqlite3_errmsg(pDb), -1) : 0
3854 /* We don't use errmsg16() directly only because it would cause an
3855 additional level of internal encoding in sqlite3. The end
3856 effect should be identical to using errmsg16(), however. */;
3857 }
3858
3859 S3JniApi(sqlite3_errstr(),jstring,1errstr)(
3860 JniArgsEnvClass, jint rcCode
3861 ){
3862 jstring rv;
3863 const char * z = sqlite3_errstr((int)rcCode);
3864 if( !z ){
3865 /* This hypothetically cannot happen, but we'll behave like the
3866 low-level library would in such a case... */
3867 z = "unknown error";
3868 }
3869 rv = (*env)->NewStringUTF(env, z)
3870 /* We know these values to be plain ASCII, so pose no MUTF-8
3871 ** incompatibility */;
3872 s3jni_oom_check( rv );
3873 return rv;
3874 }
3875
3876 #ifndef SQLITE_ENABLE_NORMALIZE
3877 /* Dummy stub for sqlite3_normalized_sql(). Never called. */
3878 static const char * sqlite3_normalized_sql(sqlite3_stmt *s){
3879 S3JniDeclLocal_env;
3880 (*env)->FatalError(env, "dummy sqlite3_normalized_sql() was "
3881 "impossibly called.") /* does not return */;
3882 return 0;
3883 }
3884 #endif
3885
3886 /*
3887 ** Impl for sqlite3_expanded_sql() (if isExpanded is true) and
3888 ** sqlite3_normalized_sql().
3889 */
3890 static jstring s3jni_xn_sql(int isExpanded, JNIEnv *env, jobject jpStmt){
3891 jstring rv = 0;
3892 sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt);
3893
3894 if( pStmt ){
3895 char * zSql = isExpanded
3896 ? sqlite3_expanded_sql(pStmt)
3897 : (char*)sqlite3_normalized_sql(pStmt);
3898 s3jni_oom_fatal(zSql);
3899 if( zSql ){
3900 rv = s3jni_utf8_to_jstring(zSql, -1);
3901 if( isExpanded ) sqlite3_free(zSql);
3902 }
3903 }
3904 return rv;
3905 }
3906
3907 S3JniApi(sqlite3_expanded_sql(),jstring,1expanded_1sql)(
3908 JniArgsEnvClass, jobject jpStmt
3909 ){
3910 return s3jni_xn_sql(1, env, jpStmt);
3911 }
3912
3913 S3JniApi(sqlite3_normalized_sql(),jstring,1normalized_1sql)(
3914 JniArgsEnvClass, jobject jpStmt
3915 ){
3916 #ifdef SQLITE_ENABLE_NORMALIZE
3917 return s3jni_xn_sql(0, env, jpStmt);
3918 #else
3919 return 0;
3920 #endif
3921 }
3922
3923 S3JniApi(sqlite3_extended_result_codes(),jint,1extended_1result_1codes)(
3924 JniArgsEnvClass, jobject jpDb, jboolean onoff
3925 ){
3926 sqlite3 * const pDb = PtrGet_sqlite3(jpDb);
3927 int const rc = pDb
3928 ? sqlite3_extended_result_codes(pDb, onoff ? 1 : 0)
3929 : SQLITE_MISUSE;
3930 return rc;
3931 }
3932
3933 S3JniApi(sqlite3_finalize(),jint,1finalize)(
3934 JniArgsEnvClass, jlong jpStmt
3935 ){
3936 return jpStmt
3937 ? sqlite3_finalize(LongPtrGet_sqlite3_stmt(jpStmt))
3938 : 0;
3939 }
3940
3941 S3JniApi(sqlite3_get_auxdata(),jobject,1get_1auxdata)(
3942 JniArgsEnvClass, jobject jCx, jint n
3943 ){
3944 return sqlite3_get_auxdata(PtrGet_sqlite3_context(jCx), (int)n);
3945 }
3946
3947 S3JniApi(sqlite3_initialize(),jint,1initialize)(
3948 JniArgsEnvClass
3949 ){
3950 return sqlite3_initialize();
3951 }
3952
3953 S3JniApi(sqlite3_interrupt(),void,1interrupt)(
3954 JniArgsEnvClass, jobject jpDb
3955 ){
3956 sqlite3 * const pDb = PtrGet_sqlite3(jpDb);
3957 if( pDb ){
3958 sqlite3_interrupt(pDb);
3959 }
3960 }
3961
3962 S3JniApi(sqlite3_is_interrupted(),jboolean,1is_1interrupted)(
3963 JniArgsEnvClass, jobject jpDb
3964 ){
3965 int rc = 0;
3966 sqlite3 * const pDb = PtrGet_sqlite3(jpDb);
3967 if( pDb ){
3968 rc = sqlite3_is_interrupted(pDb);
3969 }
3970 return rc ? JNI_TRUE : JNI_FALSE;
3971 }
3972
3973 /*
3974 ** Uncaches the current JNIEnv from the S3JniGlobal state, clearing
3975 ** any resources owned by that cache entry and making that slot
3976 ** available for re-use.
3977 */
3978 S3JniApi(sqlite3_java_uncache_thread(), jboolean, 1java_1uncache_1thread)(
3979 JniArgsEnvClass
3980 ){
3981 int rc;
3982 S3JniEnv_mutex_enter;
3983 rc = S3JniEnv_uncache(env);
3984 S3JniEnv_mutex_leave;
3985 return rc ? JNI_TRUE : JNI_FALSE;
3986 }
3987
3988 S3JniApi(sqlite3_jni_db_error(), jint, 1jni_1db_1error)(
3989 JniArgsEnvClass, jobject jDb, jint jRc, jstring jStr
3990 ){
3991 S3JniDb * const ps = S3JniDb_from_java(jDb);
3992 int rc = SQLITE_MISUSE;
3993 if( ps ){
3994 char *zStr;
3995 zStr = jStr
3996 ? s3jni_jstring_to_utf8( jStr, 0)
3997 : NULL;
3998 rc = s3jni_db_error( ps->pDb, (int)jRc, zStr );
3999 sqlite3_free(zStr);
4000 }
4001 return rc;
4002 }
4003
4004 S3JniApi(sqlite3_jni_supports_nio(), jboolean,1jni_1supports_1nio)(
4005 JniArgsEnvClass
4006 ){
4007 return SJG.g.byteBuffer.klazz ? JNI_TRUE : JNI_FALSE;
4008 }
4009
4010
4011 S3JniApi(sqlite3_keyword_check(),jboolean,1keyword_1check)(
4012 JniArgsEnvClass, jstring jWord
4013 ){
4014 int nWord = 0;
4015 char * zWord = s3jni_jstring_to_utf8(jWord, &nWord);
4016 int rc = 0;
4017
4018 s3jni_oom_check(jWord ? !!zWord : 1);
4019 if( zWord && nWord ){
4020 rc = sqlite3_keyword_check(zWord, nWord);
4021 }
4022 sqlite3_free(zWord);
4023 return rc ? JNI_TRUE : JNI_FALSE;
4024 }
4025
4026 S3JniApi(sqlite3_keyword_name(),jstring,1keyword_1name)(
4027 JniArgsEnvClass, jint ndx
4028 ){
4029 const char * zWord = 0;
4030 int n = 0;
4031 jstring rv = 0;
4032
4033 if( 0==sqlite3_keyword_name(ndx, &zWord, &n) ){
4034 rv = s3jni_utf8_to_jstring(zWord, n);
4035 }
4036 return rv;
4037 }
4038
4039
4040 S3JniApi(sqlite3_last_insert_rowid(),jlong,1last_1insert_1rowid)(
4041 JniArgsEnvClass, jobject jpDb
4042 ){
4043 return (jlong)sqlite3_last_insert_rowid(PtrGet_sqlite3(jpDb));
4044 }
4045
4046 S3JniApi(sqlite3_limit(),jint,1limit)(
4047 JniArgsEnvClass, jobject jpDb, jint id, jint newVal
4048 ){
4049 jint rc = 0;
4050 sqlite3 * const pDb = PtrGet_sqlite3(jpDb);
4051 if( pDb ){
4052 rc = sqlite3_limit( pDb, (int)id, (int)newVal );
4053 }
4054 return rc;
4055 }
4056
4057 /* Pre-open() code common to sqlite3_open[_v2](). */
4058 static int s3jni_open_pre(JNIEnv * const env, S3JniEnv **jc,
4059 jstring jDbName, char **zDbName,
4060 S3JniDb ** ps){
4061 int rc = 0;
4062 jobject jDb = 0;
4063
4064 *jc = S3JniEnv_get();
4065 if( !*jc ){
4066 rc = SQLITE_NOMEM;
4067 goto end;
4068 }
4069 *zDbName = jDbName ? s3jni_jstring_to_utf8( jDbName, 0) : 0;
4070 if( jDbName && !*zDbName ){
4071 rc = SQLITE_NOMEM;
4072 goto end;
4073 }
4074 jDb = new_java_sqlite3(env, 0);
4075 if( !jDb ){
4076 sqlite3_free(*zDbName);
4077 *zDbName = 0;
4078 rc = SQLITE_NOMEM;
4079 goto end;
4080 }
4081 *ps = S3JniDb_alloc(env, jDb);
4082 if( *ps ){
4083 (*jc)->pdbOpening = *ps;
4084 }else{
4085 S3JniUnrefLocal(jDb);
4086 rc = SQLITE_NOMEM;
4087 }
4088 end:
4089 return rc;
4090 }
4091
4092 /*
4093 ** Post-open() code common to both the sqlite3_open() and
4094 ** sqlite3_open_v2() bindings. ps->jDb must be the
4095 ** org.sqlite.jni.capi.sqlite3 object which will hold the db's native
4096 ** pointer. theRc must be the result code of the open() op. If
4097 ** *ppDb is NULL then ps is set aside and its state cleared,
4098 ** else ps is associated with *ppDb. If *ppDb is not NULL then
4099 ** ps->jDb is stored in jOut (an OutputPointer.sqlite3 instance).
4100 **
4101 ** Must be called if s3jni_open_pre() succeeds and must not be called
4102 ** if it doesn't.
4103 **
4104 ** Returns theRc.
4105 */
4106 static int s3jni_open_post(JNIEnv * const env, S3JniEnv * const jc,
4107 S3JniDb * ps, sqlite3 **ppDb,
4108 jobject jOut, int theRc){
4109 int rc = 0;
4110 jc->pdbOpening = 0;
4111 if( *ppDb ){
4112 assert(ps->jDb);
4113 if( 0==ps->pDb ){
4114 ps->pDb = *ppDb;
4115 NativePointerHolder_set(S3JniNph(sqlite3), ps->jDb, *ppDb);
4116 }else{
4117 assert( ps->pDb==*ppDb
4118 && "Set up via s3jni_run_java_auto_extensions()" );
4119 }
4120 rc = sqlite3_set_clientdata(ps->pDb, S3JniDb_clientdata_key,
4121 ps, S3JniDb_xDestroy)
4122 /* As of here, the Java/C connection is complete */;
4123 }else{
4124 S3JniDb_set_aside(ps);
4125 ps = 0;
4126 }
4127 OutputPointer_set_obj(env, S3JniNph(OutputPointer_sqlite3),
4128 jOut, ps ? ps->jDb : 0);
4129 return theRc ? theRc : rc;
4130 }
4131
4132 S3JniApi(sqlite3_open(),jint,1open)(
4133 JniArgsEnvClass, jstring strName, jobject jOut
4134 ){
4135 sqlite3 * pOut = 0;
4136 char *zName = 0;
4137 S3JniDb * ps = 0;
4138 S3JniEnv * jc = 0;
4139 int rc;
4140
4141 if( 0==jOut ) return SQLITE_MISUSE;
4142 rc = s3jni_open_pre(env, &jc, strName, &zName, &ps);
4143 if( 0==rc ){
4144 rc = s3jni_open_post(env, jc, ps, &pOut, jOut,
4145 sqlite3_open(zName, &pOut));
4146 assert(rc==0 ? pOut!=0 : 1);
4147 sqlite3_free(zName);
4148 }
4149 return (jint)rc;
4150 }
4151
4152 S3JniApi(sqlite3_open_v2(),jint,1open_1v2)(
4153 JniArgsEnvClass, jstring strName,
4154 jobject jOut, jint flags, jstring strVfs
4155 ){
4156 sqlite3 * pOut = 0;
4157 char *zName = 0;
4158 S3JniDb * ps = 0;
4159 S3JniEnv * jc = 0;
4160 char *zVfs = 0;
4161 int rc;
4162
4163 if( 0==jOut ) return SQLITE_MISUSE;
4164 rc = s3jni_open_pre(env, &jc, strName, &zName, &ps);
4165 if( 0==rc ){
4166 if( strVfs ){
4167 zVfs = s3jni_jstring_to_utf8( strVfs, 0);
4168 if( !zVfs ){
4169 rc = SQLITE_NOMEM;
4170 }
4171 }
4172 if( 0==rc ){
4173 rc = sqlite3_open_v2(zName, &pOut, (int)flags, zVfs);
4174 }
4175 rc = s3jni_open_post(env, jc, ps, &pOut, jOut, rc);
4176 }
4177 assert(rc==0 ? pOut!=0 : 1);
4178 sqlite3_free(zName);
4179 sqlite3_free(zVfs);
4180 return (jint)rc;
4181 }
4182
4183 /* Proxy for the sqlite3_prepare[_v2/3]() family. */
4184 static jint sqlite3_jni_prepare_v123( int prepVersion, JNIEnv * const env,
4185 jclass self,
4186 jlong jpDb, jbyteArray baSql,
4187 jint nMax, jint prepFlags,
4188 jobject jOutStmt, jobject outTail){
4189 sqlite3_stmt * pStmt = 0;
4190 jobject jStmt = 0;
4191 const char * zTail = 0;
4192 sqlite3 * const pDb = LongPtrGet_sqlite3(jpDb);
4193 jbyte * const pBuf = pDb ? s3jni_jbyteArray_bytes(baSql) : 0;
4194 int rc = SQLITE_ERROR;
4195
4196 assert(prepVersion==1 || prepVersion==2 || prepVersion==3);
4197 if( !pDb || !jOutStmt ){
4198 rc = SQLITE_MISUSE;
4199 goto end;
4200 }else if( !pBuf ){
4201 rc = baSql ? SQLITE_NOMEM : SQLITE_MISUSE;
4202 goto end;
4203 }
4204 jStmt = new_java_sqlite3_stmt(env, 0);
4205 if( !jStmt ){
4206 rc = SQLITE_NOMEM;
4207 goto end;
4208 }
4209 switch( prepVersion ){
4210 case 1: rc = sqlite3_prepare(pDb, (const char *)pBuf,
4211 (int)nMax, &pStmt, &zTail);
4212 break;
4213 case 2: rc = sqlite3_prepare_v2(pDb, (const char *)pBuf,
4214 (int)nMax, &pStmt, &zTail);
4215 break;
4216 case 3: rc = sqlite3_prepare_v3(pDb, (const char *)pBuf,
4217 (int)nMax, (unsigned int)prepFlags,
4218 &pStmt, &zTail);
4219 break;
4220 default:
4221 assert(!"Invalid prepare() version");
4222 }
4223 end:
4224 s3jni_jbyteArray_release(baSql,pBuf);
4225 if( 0==rc ){
4226 if( 0!=outTail ){
4227 /* Noting that pBuf is deallocated now but its address is all we need for
4228 ** what follows... */
4229 assert(zTail ? ((void*)zTail>=(void*)pBuf) : 1);
4230 assert(zTail ? (((int)((void*)zTail - (void*)pBuf)) >= 0) : 1);
4231 OutputPointer_set_Int32(
4232 env, outTail, (int)(zTail ? (zTail - (const char *)pBuf) : 0)
4233 );
4234 }
4235 if( pStmt ){
4236 NativePointerHolder_set(S3JniNph(sqlite3_stmt), jStmt, pStmt);
4237 }else{
4238 /* Happens for comments and whitespace. */
4239 S3JniUnrefLocal(jStmt);
4240 jStmt = 0;
4241 }
4242 }else{
4243 S3JniUnrefLocal(jStmt);
4244 jStmt = 0;
4245 }
4246 if( jOutStmt ){
4247 OutputPointer_set_obj(env, S3JniNph(OutputPointer_sqlite3_stmt),
4248 jOutStmt, jStmt);
4249 }
4250 return (jint)rc;
4251 }
4252 S3JniApi(sqlite3_prepare(),jint,1prepare)(
4253 JNIEnv * const env, jclass self, jlong jpDb, jbyteArray baSql,
4254 jint nMax, jobject jOutStmt, jobject outTail
4255 ){
4256 return sqlite3_jni_prepare_v123(1, env, self, jpDb, baSql, nMax, 0,
4257 jOutStmt, outTail);
4258 }
4259 S3JniApi(sqlite3_prepare_v2(),jint,1prepare_1v2)(
4260 JNIEnv * const env, jclass self, jlong jpDb, jbyteArray baSql,
4261 jint nMax, jobject jOutStmt, jobject outTail
4262 ){
4263 return sqlite3_jni_prepare_v123(2, env, self, jpDb, baSql, nMax, 0,
4264 jOutStmt, outTail);
4265 }
4266 S3JniApi(sqlite3_prepare_v3(),jint,1prepare_1v3)(
4267 JNIEnv * const env, jclass self, jlong jpDb, jbyteArray baSql,
4268 jint nMax, jint prepFlags, jobject jOutStmt, jobject outTail
4269 ){
4270 return sqlite3_jni_prepare_v123(3, env, self, jpDb, baSql, nMax,
4271 prepFlags, jOutStmt, outTail);
4272 }
4273
4274 /*
4275 ** Impl for C-to-Java of the callbacks for both sqlite3_update_hook()
4276 ** and sqlite3_preupdate_hook(). The differences are that for
4277 ** update_hook():
4278 **
4279 ** - pDb is NULL
4280 ** - iKey1 is the row ID
4281 ** - iKey2 is unused
4282 */
4283 static void s3jni_updatepre_hook_impl(void * pState, sqlite3 *pDb, int opId,
4284 const char *zDb, const char *zTable,
4285 sqlite3_int64 iKey1, sqlite3_int64 iKey2){
4286 S3JniDb * const ps = pState;
4287 S3JniDeclLocal_env;
4288 jstring jDbName;
4289 jstring jTable;
4290 const int isPre = 0!=pDb;
4291 S3JniHook hook;
4292
4293 S3JniHook_localdup(isPre ?
4294 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4295 &ps->hooks.preUpdate
4296 #else
4297 &S3JniHook_empty
4298 #endif
4299 : &ps->hooks.update, &hook);
4300 if( !hook.jObj ){
4301 return;
4302 }
4303 jDbName = s3jni_utf8_to_jstring( zDb, -1);
4304 jTable = jDbName ? s3jni_utf8_to_jstring( zTable, -1) : 0;
4305 S3JniIfThrew {
4306 S3JniExceptionClear;
4307 s3jni_db_error(ps->pDb, SQLITE_NOMEM, 0);
4308 }else{
4309 assert( hook.jObj );
4310 assert( hook.midCallback );
4311 assert( ps->jDb );
4312 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4313 if( isPre ) (*env)->CallVoidMethod(env, hook.jObj, hook.midCallback,
4314 ps->jDb, (jint)opId, jDbName, jTable,
4315 (jlong)iKey1, (jlong)iKey2);
4316 else
4317 #endif
4318 (*env)->CallVoidMethod(env, hook.jObj, hook.midCallback,
4319 (jint)opId, jDbName, jTable, (jlong)iKey1);
4320 S3JniIfThrew{
4321 S3JniExceptionWarnCallbackThrew("sqlite3_(pre)update_hook() callback");
4322 s3jni_db_exception(ps->pDb, 0,
4323 "sqlite3_(pre)update_hook() callback threw");
4324 }
4325 }
4326 S3JniUnrefLocal(jDbName);
4327 S3JniUnrefLocal(jTable);
4328 S3JniHook_localundup(hook);
4329 }
4330
4331 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4332 static void s3jni_preupdate_hook_impl(void * pState, sqlite3 *pDb, int opId,
4333 const char *zDb, const char *zTable,
4334 sqlite3_int64 iKey1, sqlite3_int64 iKey2){
4335 return s3jni_updatepre_hook_impl(pState, pDb, opId, zDb, zTable,
4336 iKey1, iKey2);
4337 }
4338 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
4339
4340 static void s3jni_update_hook_impl(void * pState, int opId, const char *zDb,
4341 const char *zTable, sqlite3_int64 nRowid){
4342 return s3jni_updatepre_hook_impl(pState, NULL, opId, zDb, zTable, nRowid, 0);
4343 }
4344
4345 #if !defined(SQLITE_ENABLE_PREUPDATE_HOOK)
4346 /* We need no-op impls for preupdate_{count,depth,blobwrite}() */
4347 S3JniApi(sqlite3_preupdate_blobwrite(),jint,1preupdate_1blobwrite)(
4348 JniArgsEnvClass, jlong jDb){ return SQLITE_MISUSE; }
4349 S3JniApi(sqlite3_preupdate_count(),jint,1preupdate_1count)(
4350 JniArgsEnvClass, jlong jDb){ return SQLITE_MISUSE; }
4351 S3JniApi(sqlite3_preupdate_depth(),jint,1preupdate_1depth)(
4352 JniArgsEnvClass, jlong jDb){ return SQLITE_MISUSE; }
4353 #endif /* !SQLITE_ENABLE_PREUPDATE_HOOK */
4354
4355 /*
4356 ** JNI wrapper for both sqlite3_update_hook() and
4357 ** sqlite3_preupdate_hook() (if isPre is true).
4358 */
4359 static jobject s3jni_updatepre_hook(JNIEnv * env, int isPre, jlong jpDb, jobject jHook){
4360 S3JniDb * const ps = S3JniDb_from_jlong(jpDb);
4361 jclass klazz;
4362 jobject pOld = 0;
4363 jmethodID xCallback;
4364 S3JniHook * pHook;
4365
4366 if( !ps ) return 0;
4367 S3JniDb_mutex_enter;
4368 pHook = isPre ?
4369 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4370 &ps->hooks.preUpdate
4371 #else
4372 0
4373 #endif
4374 : &ps->hooks.update;
4375 if( !pHook ){
4376 goto end;
4377 }
4378 pOld = pHook->jObj;
4379 if( pOld && jHook && (*env)->IsSameObject(env, pOld, jHook) ){
4380 goto end;
4381 }
4382 if( !jHook ){
4383 if( pOld ){
4384 jobject tmp = S3JniRefLocal(pOld);
4385 S3JniUnrefGlobal(pOld);
4386 pOld = tmp;
4387 }
4388 *pHook = S3JniHook_empty;
4389 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4390 if( isPre ) sqlite3_preupdate_hook(ps->pDb, 0, 0);
4391 else
4392 #endif
4393 sqlite3_update_hook(ps->pDb, 0, 0);
4394 goto end;
4395 }
4396 klazz = (*env)->GetObjectClass(env, jHook);
4397 xCallback = isPre
4398 ? (*env)->GetMethodID(env, klazz, "call",
4399 "(Lorg/sqlite/jni/capi/sqlite3;"
4400 "I"
4401 "Ljava/lang/String;"
4402 "Ljava/lang/String;"
4403 "JJ)V")
4404 : (*env)->GetMethodID(env, klazz, "call",
4405 "(ILjava/lang/String;Ljava/lang/String;J)V");
4406 S3JniUnrefLocal(klazz);
4407 S3JniIfThrew {
4408 S3JniExceptionClear;
4409 s3jni_db_error(ps->pDb, SQLITE_ERROR,
4410 "Cannot not find matching callback on "
4411 "(pre)update hook object.");
4412 }else{
4413 pHook->midCallback = xCallback;
4414 pHook->jObj = S3JniRefGlobal(jHook);
4415 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4416 if( isPre ) sqlite3_preupdate_hook(ps->pDb, s3jni_preupdate_hook_impl, ps);
4417 else
4418 #endif
4419 sqlite3_update_hook(ps->pDb, s3jni_update_hook_impl, ps);
4420 if( pOld ){
4421 jobject tmp = S3JniRefLocal(pOld);
4422 S3JniUnrefGlobal(pOld);
4423 pOld = tmp;
4424 }
4425 }
4426 end:
4427 S3JniDb_mutex_leave;
4428 return pOld;
4429 }
4430
4431
4432 S3JniApi(sqlite3_preupdate_hook(),jobject,1preupdate_1hook)(
4433 JniArgsEnvClass, jlong jpDb, jobject jHook
4434 ){
4435 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4436 return s3jni_updatepre_hook(env, 1, jpDb, jHook);
4437 #else
4438 return NULL;
4439 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
4440 }
4441
4442 /* Impl for sqlite3_preupdate_{new,old}(). */
4443 static int s3jni_preupdate_newold(JNIEnv * const env, int isNew, jlong jpDb,
4444 jint iCol, jobject jOut){
4445 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
4446 sqlite3 * const pDb = LongPtrGet_sqlite3(jpDb);
4447 int rc = SQLITE_MISUSE;
4448 if( pDb ){
4449 sqlite3_value * pOut = 0;
4450 int (*fOrig)(sqlite3*,int,sqlite3_value**) =
4451 isNew ? sqlite3_preupdate_new : sqlite3_preupdate_old;
4452 rc = fOrig(pDb, (int)iCol, &pOut);
4453 if( 0==rc ){
4454 jobject pWrap = new_java_sqlite3_value(env, pOut);
4455 if( !pWrap ){
4456 rc = SQLITE_NOMEM;
4457 }
4458 OutputPointer_set_obj(env, S3JniNph(OutputPointer_sqlite3_value),
4459 jOut, pWrap);
4460 S3JniUnrefLocal(pWrap);
4461 }
4462 }
4463 return rc;
4464 #else
4465 return SQLITE_MISUSE;
4466 #endif
4467 }
4468
4469 S3JniApi(sqlite3_preupdate_new(),jint,1preupdate_1new)(
4470 JniArgsEnvClass, jlong jpDb, jint iCol, jobject jOut
4471 ){
4472 return s3jni_preupdate_newold(env, 1, jpDb, iCol, jOut);
4473 }
4474
4475 S3JniApi(sqlite3_preupdate_old(),jint,1preupdate_1old)(
4476 JniArgsEnvClass, jlong jpDb, jint iCol, jobject jOut
4477 ){
4478 return s3jni_preupdate_newold(env, 0, jpDb, iCol, jOut);
4479 }
4480
4481
4482 /* Central C-to-Java sqlite3_progress_handler() proxy. */
4483 static int s3jni_progress_handler_impl(void *pP){
4484 S3JniDb * const ps = (S3JniDb *)pP;
4485 int rc = 0;
4486 S3JniDeclLocal_env;
4487 S3JniHook hook;
4488
4489 S3JniHook_localdup(&ps->hooks.progress, &hook);
4490 if( hook.jObj ){
4491 rc = (int)(*env)->CallIntMethod(env, hook.jObj, hook.midCallback);
4492 S3JniIfThrew{
4493 rc = s3jni_db_exception(ps->pDb, rc,
4494 "sqlite3_progress_handler() callback threw");
4495 }
4496 S3JniHook_localundup(hook);
4497 }
4498 return rc;
4499 }
4500
4501 S3JniApi(sqlite3_progress_handler(),void,1progress_1handler)(
4502 JniArgsEnvClass,jobject jDb, jint n, jobject jProgress
4503 ){
4504 S3JniDb * const ps = S3JniDb_from_java(jDb);
4505 S3JniHook * const pHook = ps ? &ps->hooks.progress : 0;
4506
4507 if( !ps ) return;
4508 S3JniDb_mutex_enter;
4509 if( n<1 || !jProgress ){
4510 S3JniHook_unref(pHook);
4511 sqlite3_progress_handler(ps->pDb, 0, 0, 0);
4512 }else{
4513 jclass const klazz = (*env)->GetObjectClass(env, jProgress);
4514 jmethodID const xCallback = (*env)->GetMethodID(env, klazz, "call", "()I");
4515 S3JniUnrefLocal(klazz);
4516 S3JniIfThrew {
4517 S3JniExceptionClear;
4518 s3jni_db_error(ps->pDb, SQLITE_ERROR,
4519 "Cannot not find matching xCallback() on "
4520 "ProgressHandler object.");
4521 }else{
4522 S3JniUnrefGlobal(pHook->jObj);
4523 pHook->midCallback = xCallback;
4524 pHook->jObj = S3JniRefGlobal(jProgress);
4525 sqlite3_progress_handler(ps->pDb, (int)n, s3jni_progress_handler_impl, ps);
4526 }
4527 }
4528 S3JniDb_mutex_leave;
4529 }
4530
4531 S3JniApi(sqlite3_randomness(),void,1randomness)(
4532 JniArgsEnvClass, jbyteArray jTgt
4533 ){
4534 jbyte * const jba = s3jni_jbyteArray_bytes(jTgt);
4535 if( jba ){
4536 jsize const nTgt = (*env)->GetArrayLength(env, jTgt);
4537 sqlite3_randomness( (int)nTgt, jba );
4538 s3jni_jbyteArray_commit(jTgt, jba);
4539 }
4540 }
4541
4542
4543 S3JniApi(sqlite3_reset(),jint,1reset)(
4544 JniArgsEnvClass, jobject jpStmt
4545 ){
4546 sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt);
4547 return pStmt ? sqlite3_reset(pStmt) : SQLITE_MISUSE;
4548 }
4549
4550 /* Clears all entries from S3JniGlobal.autoExt. */
4551 static void s3jni_reset_auto_extension(JNIEnv *env){
4552 int i;
4553 S3JniAutoExt_mutex_enter;
4554 for( i = 0; i < SJG.autoExt.nExt; ++i ){
4555 S3JniAutoExtension_clear( &SJG.autoExt.aExt[i] );
4556 }
4557 SJG.autoExt.nExt = 0;
4558 S3JniAutoExt_mutex_leave;
4559 }
4560
4561 S3JniApi(sqlite3_reset_auto_extension(),void,1reset_1auto_1extension)(
4562 JniArgsEnvClass
4563 ){
4564 s3jni_reset_auto_extension(env);
4565 }
4566
4567 /* Impl for sqlite3_result_text/blob() and friends. */
4568 static void result_blob_text(int as64 /* true for text64/blob64() mode */,
4569 int eTextRep /* 0 for blobs, else SQLITE_UTF... */,
4570 JNIEnv * const env, sqlite3_context *pCx,
4571 jbyteArray jBa, jlong nMax){
4572 int const asBlob = 0==eTextRep;
4573 if( !pCx ){
4574 /* We should arguably emit a warning here. But where to log it? */
4575 return;
4576 }else if( jBa ){
4577 jbyte * const pBuf = s3jni_jbyteArray_bytes(jBa);
4578 jsize nBA = (*env)->GetArrayLength(env, jBa);
4579 if( nMax>=0 && nBA>(jsize)nMax ){
4580 nBA = (jsize)nMax;
4581 /**
4582 From the sqlite docs:
4583
4584 > If the 3rd parameter to any of the sqlite3_result_text*
4585 interfaces other than sqlite3_result_text64() is negative,
4586 then SQLite computes the string length itself by searching
4587 the 2nd parameter for the first zero character.
4588
4589 Note that the text64() interfaces take an unsigned value for
4590 the length, which Java does not support. This binding takes
4591 the approach of passing on negative values to the C API,
4592 which will in turn fail with SQLITE_TOOBIG at some later
4593 point (recall that the sqlite3_result_xyz() family do not
4594 have result values).
4595 */
4596 }
4597 if( as64 ){ /* 64-bit... */
4598 static const jsize nLimit64 =
4599 SQLITE_MAX_ALLOCATION_SIZE/*only _kinda_ arbitrary*/;
4600 if( nBA > nLimit64 ){
4601 sqlite3_result_error_toobig(pCx);
4602 }else if( asBlob ){
4603 sqlite3_result_blob64(pCx, pBuf, (sqlite3_uint64)nBA,
4604 SQLITE_TRANSIENT);
4605 }else{ /* text64... */
4606 if( encodingTypeIsValid(eTextRep) ){
4607 sqlite3_result_text64(pCx, (const char *)pBuf,
4608 (sqlite3_uint64)nBA,
4609 SQLITE_TRANSIENT, eTextRep);
4610 }else{
4611 sqlite3_result_error_code(pCx, SQLITE_FORMAT);
4612 }
4613 }
4614 }else{ /* 32-bit... */
4615 static const jsize nLimit = SQLITE_MAX_ALLOCATION_SIZE;
4616 if( nBA > nLimit ){
4617 sqlite3_result_error_toobig(pCx);
4618 }else if( asBlob ){
4619 sqlite3_result_blob(pCx, pBuf, (int)nBA,
4620 SQLITE_TRANSIENT);
4621 }else{
4622 switch( eTextRep ){
4623 case SQLITE_UTF8:
4624 sqlite3_result_text(pCx, (const char *)pBuf, (int)nBA,
4625 SQLITE_TRANSIENT);
4626 break;
4627 case SQLITE_UTF16:
4628 sqlite3_result_text16(pCx, (const char *)pBuf, (int)nBA,
4629 SQLITE_TRANSIENT);
4630 break;
4631 case SQLITE_UTF16LE:
4632 sqlite3_result_text16le(pCx, (const char *)pBuf, (int)nBA,
4633 SQLITE_TRANSIENT);
4634 break;
4635 case SQLITE_UTF16BE:
4636 sqlite3_result_text16be(pCx, (const char *)pBuf, (int)nBA,
4637 SQLITE_TRANSIENT);
4638 break;
4639 }
4640 }
4641 s3jni_jbyteArray_release(jBa, pBuf);
4642 }
4643 }else{
4644 sqlite3_result_null(pCx);
4645 }
4646 }
4647
4648 S3JniApi(sqlite3_result_blob(),void,1result_1blob)(
4649 JniArgsEnvClass, jobject jpCx, jbyteArray jBa, jint nMax
4650 ){
4651 return result_blob_text(0, 0, env, PtrGet_sqlite3_context(jpCx), jBa, nMax);
4652 }
4653
4654 S3JniApi(sqlite3_result_blob64(),void,1result_1blob64)(
4655 JniArgsEnvClass, jobject jpCx, jbyteArray jBa, jlong nMax
4656 ){
4657 return result_blob_text(1, 0, env, PtrGet_sqlite3_context(jpCx), jBa, nMax);
4658 }
4659
4660 S3JniApi(sqlite3_result_double(),void,1result_1double)(
4661 JniArgsEnvClass, jobject jpCx, jdouble v
4662 ){
4663 sqlite3_result_double(PtrGet_sqlite3_context(jpCx), v);
4664 }
4665
4666 S3JniApi(sqlite3_result_error(),void,1result_1error)(
4667 JniArgsEnvClass, jobject jpCx, jbyteArray baMsg, jint eTextRep
4668 ){
4669 const char * zUnspecified = "Unspecified error.";
4670 jsize const baLen = (*env)->GetArrayLength(env, baMsg);
4671 jbyte * const pjBuf = baMsg ? s3jni_jbyteArray_bytes(baMsg) : NULL;
4672 switch( pjBuf ? eTextRep : SQLITE_UTF8 ){
4673 case SQLITE_UTF8: {
4674 const char *zMsg = pjBuf ? (const char *)pjBuf : zUnspecified;
4675 int const n = pjBuf ? (int)baLen : (int)sqlite3Strlen30(zMsg);
4676 sqlite3_result_error(PtrGet_sqlite3_context(jpCx), zMsg, n);
4677 break;
4678 }
4679 case SQLITE_UTF16: {
4680 const void *zMsg = pjBuf;
4681 sqlite3_result_error16(PtrGet_sqlite3_context(jpCx), zMsg, (int)baLen);
4682 break;
4683 }
4684 default:
4685 sqlite3_result_error(PtrGet_sqlite3_context(jpCx),
4686 "Invalid encoding argument passed "
4687 "to sqlite3_result_error().", -1);
4688 break;
4689 }
4690 s3jni_jbyteArray_release(baMsg,pjBuf);
4691 }
4692
4693 S3JniApi(sqlite3_result_error_code(),void,1result_1error_1code)(
4694 JniArgsEnvClass, jobject jpCx, jint v
4695 ){
4696 sqlite3_result_error_code(PtrGet_sqlite3_context(jpCx), (int)v);
4697 }
4698
4699 S3JniApi(sqlite3_result_error_nomem(),void,1result_1error_1nomem)(
4700 JniArgsEnvClass, jobject jpCx
4701 ){
4702 sqlite3_result_error_nomem(PtrGet_sqlite3_context(jpCx));
4703 }
4704
4705 S3JniApi(sqlite3_result_error_toobig(),void,1result_1error_1toobig)(
4706 JniArgsEnvClass, jobject jpCx
4707 ){
4708 sqlite3_result_error_toobig(PtrGet_sqlite3_context(jpCx));
4709 }
4710
4711 S3JniApi(sqlite3_result_int(),void,1result_1int)(
4712 JniArgsEnvClass, jobject jpCx, jint v
4713 ){
4714 sqlite3_result_int(PtrGet_sqlite3_context(jpCx), (int)v);
4715 }
4716
4717 S3JniApi(sqlite3_result_int64(),void,1result_1int64)(
4718 JniArgsEnvClass, jobject jpCx, jlong v
4719 ){
4720 sqlite3_result_int64(PtrGet_sqlite3_context(jpCx), (sqlite3_int64)v);
4721 }
4722
4723 S3JniApi(sqlite3_result_java_object(),void,1result_1java_1object)(
4724 JniArgsEnvClass, jobject jpCx, jobject v
4725 ){
4726 sqlite3_context * pCx = PtrGet_sqlite3_context(jpCx);
4727 if( !pCx ) return;
4728 else if( v ){
4729 jobject const rjv = S3JniRefGlobal(v);
4730 if( rjv ){
4731 sqlite3_result_pointer(pCx, rjv,
4732 s3jni__value_jref_key, S3Jni_jobject_finalizer);
4733 }else{
4734 sqlite3_result_error_nomem(PtrGet_sqlite3_context(jpCx));
4735 }
4736 }else{
4737 sqlite3_result_null(PtrGet_sqlite3_context(jpCx));
4738 }
4739 }
4740
4741 S3JniApi(sqlite3_result_nio_buffer(),void,1result_1nio_1buffer)(
4742 JniArgsEnvClass, jobject jpCtx, jobject jBuffer,
4743 jint iOffset, jint iN
4744 ){
4745 sqlite3_context * pCx = PtrGet_sqlite3_context(jpCtx);
4746 int rc;
4747 S3JniNioArgs args;
4748 if( !pCx ){
4749 return;
4750 }else if( !SJG.g.byteBuffer.klazz ){
4751 sqlite3_result_error(
4752 pCx, "This JVM does not support JNI access to ByteBuffers.", -1
4753 );
4754 return;
4755 }
4756 rc = s3jni_setup_nio_args(env, &args, jBuffer, iOffset, iN);
4757 if(rc){
4758 if( iOffset<0 ){
4759 sqlite3_result_error(pCx, "Start index may not be negative.", -1);
4760 }else if( SQLITE_TOOBIG==rc ){
4761 sqlite3_result_error_toobig(pCx);
4762 }else{
4763 sqlite3_result_error(
4764 pCx, "Invalid arguments to sqlite3_result_nio_buffer().", -1
4765 );
4766 }
4767 }else if( !args.pStart || !args.nOut ){
4768 sqlite3_result_null(pCx);
4769 }else{
4770 sqlite3_result_blob(pCx, args.pStart, args.nOut, SQLITE_TRANSIENT);
4771 }
4772 }
4773
4774
4775 S3JniApi(sqlite3_result_null(),void,1result_1null)(
4776 JniArgsEnvClass, jobject jpCx
4777 ){
4778 sqlite3_result_null(PtrGet_sqlite3_context(jpCx));
4779 }
4780
4781 S3JniApi(sqlite3_result_subtype(),void,1result_1subtype)(
4782 JniArgsEnvClass, jobject jpCx, jint v
4783 ){
4784 sqlite3_result_subtype(PtrGet_sqlite3_context(jpCx), (unsigned int)v);
4785 }
4786
4787
4788 S3JniApi(sqlite3_result_text(),void,1result_1text)(
4789 JniArgsEnvClass, jobject jpCx, jbyteArray jBa, jint nMax
4790 ){
4791 return result_blob_text(0, SQLITE_UTF8, env,
4792 PtrGet_sqlite3_context(jpCx), jBa, nMax);
4793 }
4794
4795 S3JniApi(sqlite3_result_text64(),void,1result_1text64)(
4796 JniArgsEnvClass, jobject jpCx, jbyteArray jBa, jlong nMax,
4797 jint eTextRep
4798 ){
4799 return result_blob_text(1, eTextRep, env,
4800 PtrGet_sqlite3_context(jpCx), jBa, nMax);
4801 }
4802
4803 S3JniApi(sqlite3_result_value(),void,1result_1value)(
4804 JniArgsEnvClass, jobject jpCx, jobject jpSVal
4805 ){
4806 sqlite3_result_value(PtrGet_sqlite3_context(jpCx),
4807 PtrGet_sqlite3_value(jpSVal));
4808 }
4809
4810 S3JniApi(sqlite3_result_zeroblob(),void,1result_1zeroblob)(
4811 JniArgsEnvClass, jobject jpCx, jint v
4812 ){
4813 sqlite3_result_zeroblob(PtrGet_sqlite3_context(jpCx), (int)v);
4814 }
4815
4816 S3JniApi(sqlite3_result_zeroblob64(),jint,1result_1zeroblob64)(
4817 JniArgsEnvClass, jobject jpCx, jlong v
4818 ){
4819 return (jint)sqlite3_result_zeroblob64(PtrGet_sqlite3_context(jpCx),
4820 (sqlite3_int64)v);
4821 }
4822
4823 S3JniApi(sqlite3_rollback_hook(),jobject,1rollback_1hook)(
4824 JniArgsEnvClass, jlong jpDb, jobject jHook
4825 ){
4826 return s3jni_commit_rollback_hook(0, env, jpDb, jHook);
4827 }
4828
4829 /* Callback for sqlite3_set_authorizer(). */
4830 int s3jni_xAuth(void* pState, int op,const char*z0, const char*z1,
4831 const char*z2,const char*z3){
4832 S3JniDb * const ps = pState;
4833 S3JniDeclLocal_env;
4834 S3JniHook hook;
4835 int rc = 0;
4836
4837 S3JniHook_localdup(&ps->hooks.auth, &hook );
4838 if( hook.jObj ){
4839 jstring const s0 = z0 ? s3jni_utf8_to_jstring( z0, -1) : 0;
4840 jstring const s1 = z1 ? s3jni_utf8_to_jstring( z1, -1) : 0;
4841 jstring const s2 = z2 ? s3jni_utf8_to_jstring( z2, -1) : 0;
4842 jstring const s3 = z3 ? s3jni_utf8_to_jstring( z3, -1) : 0;
4843
4844 rc = (*env)->CallIntMethod(env, hook.jObj, hook.midCallback, (jint)op,
4845 s0, s1, s3, s3);
4846 S3JniIfThrew{
4847 rc = s3jni_db_exception(ps->pDb, rc, "sqlite3_set_authorizer() callback");
4848 }
4849 S3JniUnrefLocal(s0);
4850 S3JniUnrefLocal(s1);
4851 S3JniUnrefLocal(s2);
4852 S3JniUnrefLocal(s3);
4853 S3JniHook_localundup(hook);
4854 }
4855 return rc;
4856 }
4857
4858 S3JniApi(sqlite3_set_authorizer(),jint,1set_1authorizer)(
4859 JniArgsEnvClass,jobject jDb, jobject jHook
4860 ){
4861 S3JniDb * const ps = S3JniDb_from_java(jDb);
4862 S3JniHook * const pHook = ps ? &ps->hooks.auth : 0;
4863 int rc = 0;
4864
4865 if( !ps ) return SQLITE_MISUSE;
4866 S3JniDb_mutex_enter;
4867 if( !jHook ){
4868 S3JniHook_unref(pHook);
4869 rc = sqlite3_set_authorizer( ps->pDb, 0, 0 );
4870 }else{
4871 jclass klazz;
4872 if( pHook->jObj ){
4873 if( (*env)->IsSameObject(env, pHook->jObj, jHook) ){
4874 /* Same object - this is a no-op. */
4875 S3JniDb_mutex_leave;
4876 return 0;
4877 }
4878 S3JniHook_unref(pHook);
4879 }
4880 pHook->jObj = S3JniRefGlobal(jHook);
4881 klazz = (*env)->GetObjectClass(env, jHook);
4882 pHook->midCallback = (*env)->GetMethodID(env, klazz,
4883 "call",
4884 "(I"
4885 "Ljava/lang/String;"
4886 "Ljava/lang/String;"
4887 "Ljava/lang/String;"
4888 "Ljava/lang/String;"
4889 ")I");
4890 S3JniUnrefLocal(klazz);
4891 S3JniIfThrew {
4892 rc = s3jni_db_error(ps->pDb, SQLITE_ERROR,
4893 "Error setting up Java parts of authorizer hook.");
4894 }else{
4895 rc = sqlite3_set_authorizer(ps->pDb, s3jni_xAuth, ps);
4896 }
4897 if( rc ) S3JniHook_unref(pHook);
4898 }
4899 S3JniDb_mutex_leave;
4900 return rc;
4901 }
4902
4903 S3JniApi(sqlite3_set_auxdata(),void,1set_1auxdata)(
4904 JniArgsEnvClass, jobject jCx, jint n, jobject jAux
4905 ){
4906 sqlite3_set_auxdata(PtrGet_sqlite3_context(jCx), (int)n,
4907 S3JniRefGlobal(jAux), S3Jni_jobject_finalizer);
4908 }
4909
4910 S3JniApi(sqlite3_set_last_insert_rowid(),void,1set_1last_1insert_1rowid)(
4911 JniArgsEnvClass, jobject jpDb, jlong rowId
4912 ){
4913 sqlite3_set_last_insert_rowid(PtrGet_sqlite3(jpDb),
4914 (sqlite3_int64)rowId);
4915 }
4916
4917 S3JniApi(sqlite3_shutdown(),jint,1shutdown)(
4918 JniArgsEnvClass
4919 ){
4920 s3jni_reset_auto_extension(env);
4921 #ifdef SQLITE_ENABLE_SQLLOG
4922 S3JniHook_unref(&SJG.hook.sqllog);
4923 #endif
4924 S3JniHook_unref(&SJG.hook.configlog);
4925 /* Free up S3JniDb recycling bin. */
4926 S3JniDb_mutex_enter; {
4927 while( S3JniGlobal.perDb.aFree ){
4928 S3JniDb * const d = S3JniGlobal.perDb.aFree;
4929 S3JniGlobal.perDb.aFree = d->pNext;
4930 S3JniDb_clear(env, d);
4931 sqlite3_free(d);
4932 }
4933 } S3JniDb_mutex_leave;
4934 S3JniGlobal_mutex_enter; {
4935 /* Free up S3JniUdf recycling bin. */
4936 while( S3JniGlobal.udf.aFree ){
4937 S3JniUdf * const u = S3JniGlobal.udf.aFree;
4938 S3JniGlobal.udf.aFree = u->pNext;
4939 u->pNext = 0;
4940 S3JniUdf_free(env, u, 0);
4941 }
4942 } S3JniGlobal_mutex_leave;
4943 S3JniHook_mutex_enter; {
4944 /* Free up S3JniHook recycling bin. */
4945 while( S3JniGlobal.hook.aFree ){
4946 S3JniHook * const u = S3JniGlobal.hook.aFree;
4947 S3JniGlobal.hook.aFree = u->pNext;
4948 u->pNext = 0;
4949 assert( !u->doXDestroy );
4950 assert( !u->jObj );
4951 assert( !u->jExtra );
4952 sqlite3_free( u );
4953 }
4954 } S3JniHook_mutex_leave;
4955 /* Free up env cache. */
4956 S3JniEnv_mutex_enter; {
4957 while( SJG.envCache.aHead ){
4958 S3JniEnv_uncache( SJG.envCache.aHead->env );
4959 }
4960 } S3JniEnv_mutex_leave;
4961 /* Do not clear S3JniGlobal.jvm or S3JniGlobal.g: it's legal to
4962 ** restart the lib. */
4963 return sqlite3_shutdown();
4964 }
4965
4966 S3JniApi(sqlite3_status(),jint,1status)(
4967 JniArgsEnvClass, jint op, jobject jOutCurrent, jobject jOutHigh,
4968 jboolean reset
4969 ){
4970 int iCur = 0, iHigh = 0;
4971 int rc = sqlite3_status( op, &iCur, &iHigh, reset );
4972 if( 0==rc ){
4973 OutputPointer_set_Int32(env, jOutCurrent, iCur);
4974 OutputPointer_set_Int32(env, jOutHigh, iHigh);
4975 }
4976 return (jint)rc;
4977 }
4978
4979 S3JniApi(sqlite3_status64(),jint,1status64)(
4980 JniArgsEnvClass, jint op, jobject jOutCurrent, jobject jOutHigh,
4981 jboolean reset
4982 ){
4983 sqlite3_int64 iCur = 0, iHigh = 0;
4984 int rc = sqlite3_status64( op, &iCur, &iHigh, reset );
4985 if( 0==rc ){
4986 OutputPointer_set_Int64(env, jOutCurrent, iCur);
4987 OutputPointer_set_Int64(env, jOutHigh, iHigh);
4988 }
4989 return (jint)rc;
4990 }
4991
4992 S3JniApi(sqlite3_stmt_status(),jint,1stmt_1status)(
4993 JniArgsEnvClass, jobject jStmt, jint op, jboolean reset
4994 ){
4995 return sqlite3_stmt_status(PtrGet_sqlite3_stmt(jStmt),
4996 (int)op, reset ? 1 : 0);
4997 }
4998
4999
5000 static int s3jni_strlike_glob(int isLike, JNIEnv *const env,
5001 jbyteArray baG, jbyteArray baT, jint escLike){
5002 int rc = 0;
5003 jbyte * const pG = s3jni_jbyteArray_bytes(baG);
5004 jbyte * const pT = s3jni_jbyteArray_bytes(baT);
5005
5006 /* Note that we're relying on the byte arrays having been
5007 NUL-terminated on the Java side. */
5008 rc = isLike
5009 ? sqlite3_strlike((const char *)pG, (const char *)pT,
5010 (unsigned int)escLike)
5011 : sqlite3_strglob((const char *)pG, (const char *)pT);
5012 s3jni_jbyteArray_release(baG, pG);
5013 s3jni_jbyteArray_release(baT, pT);
5014 return rc;
5015 }
5016
5017 S3JniApi(sqlite3_strglob(),jint,1strglob)(
5018 JniArgsEnvClass, jbyteArray baG, jbyteArray baT
5019 ){
5020 return s3jni_strlike_glob(0, env, baG, baT, 0);
5021 }
5022
5023 S3JniApi(sqlite3_strlike(),jint,1strlike)(
5024 JniArgsEnvClass, jbyteArray baG, jbyteArray baT, jint escChar
5025 ){
5026 return s3jni_strlike_glob(1, env, baG, baT, escChar);
5027 }
5028
5029 S3JniApi(sqlite3_sql(),jstring,1sql)(
5030 JniArgsEnvClass, jobject jpStmt
5031 ){
5032 sqlite3_stmt * const pStmt = PtrGet_sqlite3_stmt(jpStmt);
5033 jstring rv = 0;
5034 if( pStmt ){
5035 const char * zSql = 0;
5036 zSql = sqlite3_sql(pStmt);
5037 rv = s3jni_utf8_to_jstring( zSql, -1);
5038 }
5039 return rv;
5040 }
5041
5042 S3JniApi(sqlite3_step(),jint,1step)(
5043 JniArgsEnvClass, jlong jpStmt
5044 ){
5045 sqlite3_stmt * const pStmt = LongPtrGet_sqlite3_stmt(jpStmt);
5046 return pStmt ? (jint)sqlite3_step(pStmt) : (jint)SQLITE_MISUSE;
5047 }
5048
5049 S3JniApi(sqlite3_table_column_metadata(),jint,1table_1column_1metadata)(
5050 JniArgsEnvClass, jobject jDb, jstring jDbName, jstring jTableName,
5051 jstring jColumnName, jobject jDataType, jobject jCollSeq, jobject jNotNull,
5052 jobject jPrimaryKey, jobject jAutoinc
5053 ){
5054 sqlite3 * const db = PtrGet_sqlite3(jDb);
5055 char * zDbName = 0, * zTableName = 0, * zColumnName = 0;
5056 const char * pzCollSeq = 0;
5057 const char * pzDataType = 0;
5058 int pNotNull = 0, pPrimaryKey = 0, pAutoinc = 0;
5059 int rc;
5060
5061 if( !db || !jDbName || !jTableName ) return SQLITE_MISUSE;
5062 zDbName = s3jni_jstring_to_utf8(jDbName,0);
5063 zTableName = zDbName ? s3jni_jstring_to_utf8(jTableName,0) : 0;
5064 zColumnName = (zTableName && jColumnName)
5065 ? s3jni_jstring_to_utf8(jColumnName,0) : 0;
5066 rc = zTableName
5067 ? sqlite3_table_column_metadata(db, zDbName, zTableName,
5068 zColumnName, &pzDataType, &pzCollSeq,
5069 &pNotNull, &pPrimaryKey, &pAutoinc)
5070 : SQLITE_NOMEM;
5071 if( 0==rc ){
5072 jstring jseq = jCollSeq
5073 ? (pzCollSeq ? s3jni_utf8_to_jstring(pzCollSeq, -1) : 0)
5074 : 0;
5075 jstring jdtype = jDataType
5076 ? (pzDataType ? s3jni_utf8_to_jstring(pzDataType, -1) : 0)
5077 : 0;
5078 if( (jCollSeq && pzCollSeq && !jseq)
5079 || (jDataType && pzDataType && !jdtype) ){
5080 rc = SQLITE_NOMEM;
5081 }else{
5082 if( jNotNull ) OutputPointer_set_Bool(env, jNotNull, pNotNull);
5083 if( jPrimaryKey ) OutputPointer_set_Bool(env, jPrimaryKey, pPrimaryKey);
5084 if( jAutoinc ) OutputPointer_set_Bool(env, jAutoinc, pAutoinc);
5085 if( jCollSeq ) OutputPointer_set_String(env, jCollSeq, jseq);
5086 if( jDataType ) OutputPointer_set_String(env, jDataType, jdtype);
5087 }
5088 S3JniUnrefLocal(jseq);
5089 S3JniUnrefLocal(jdtype);
5090 }
5091 sqlite3_free(zDbName);
5092 sqlite3_free(zTableName);
5093 sqlite3_free(zColumnName);
5094 return rc;
5095 }
5096
5097 static int s3jni_trace_impl(unsigned traceflag, void *pC, void *pP, void *pX){
5098 S3JniDb * const ps = (S3JniDb *)pC;
5099 S3JniDeclLocal_env;
5100 jobject jX = NULL /* the tracer's X arg */;
5101 jobject jP = NULL /* the tracer's P arg */;
5102 jobject jPUnref = NULL /* potentially a local ref to jP */;
5103 int rc = 0;
5104 S3JniHook hook;
5105
5106 S3JniHook_localdup(&ps->hooks.trace, &hook );
5107 if( !hook.jObj ){
5108 return 0;
5109 }
5110 switch( traceflag ){
5111 case SQLITE_TRACE_STMT:
5112 jX = s3jni_utf8_to_jstring( (const char *)pX, -1);
5113 if( !jX ) rc = SQLITE_NOMEM;
5114 break;
5115 case SQLITE_TRACE_PROFILE:
5116 jX = (*env)->NewObject(env, SJG.g.cLong, SJG.g.ctorLong1,
5117 (jlong)*((sqlite3_int64*)pX));
5118 // hmm. ^^^ (*pX) really is zero.
5119 // MARKER(("profile time = %llu\n", *((sqlite3_int64*)pX)));
5120 s3jni_oom_check( jX );
5121 if( !jX ) rc = SQLITE_NOMEM;
5122 break;
5123 case SQLITE_TRACE_ROW:
5124 break;
5125 case SQLITE_TRACE_CLOSE:
5126 jP = jPUnref = S3JniRefLocal(ps->jDb);
5127 break;
5128 default:
5129 assert(!"cannot happen - unknown trace flag");
5130 rc = SQLITE_ERROR;
5131 }
5132 if( 0==rc ){
5133 if( !jP ){
5134 /* Create a new temporary sqlite3_stmt wrapper */
5135 jP = jPUnref = new_java_sqlite3_stmt(env, pP);
5136 if( !jP ){
5137 rc = SQLITE_NOMEM;
5138 }
5139 }
5140 if( 0==rc ){
5141 assert(jP);
5142 rc = (int)(*env)->CallIntMethod(env, hook.jObj, hook.midCallback,
5143 (jint)traceflag, jP, jX);
5144 S3JniIfThrew{
5145 rc = s3jni_db_exception(ps->pDb, SQLITE_ERROR,
5146 "sqlite3_trace_v2() callback threw.");
5147 }
5148 }
5149 }
5150 S3JniUnrefLocal(jPUnref);
5151 S3JniUnrefLocal(jX);
5152 S3JniHook_localundup(hook);
5153 return rc;
5154 }
5155
5156 S3JniApi(sqlite3_trace_v2(),jint,1trace_1v2)(
5157 JniArgsEnvClass,jobject jDb, jint traceMask, jobject jTracer
5158 ){
5159 S3JniDb * const ps = S3JniDb_from_java(jDb);
5160 int rc;
5161
5162 if( !ps ) return SQLITE_MISUSE;
5163 if( !traceMask || !jTracer ){
5164 S3JniDb_mutex_enter;
5165 rc = (jint)sqlite3_trace_v2(ps->pDb, 0, 0, 0);
5166 S3JniHook_unref(&ps->hooks.trace);
5167 S3JniDb_mutex_leave;
5168 }else{
5169 jclass const klazz = (*env)->GetObjectClass(env, jTracer);
5170 S3JniHook hook = S3JniHook_empty;
5171 hook.midCallback = (*env)->GetMethodID(
5172 env, klazz, "call", "(ILjava/lang/Object;Ljava/lang/Object;)I"
5173 );
5174 S3JniUnrefLocal(klazz);
5175 S3JniIfThrew {
5176 S3JniExceptionClear;
5177 rc = s3jni_db_error(ps->pDb, SQLITE_ERROR,
5178 "Cannot not find matching call() on "
5179 "TracerCallback object.");
5180 }else{
5181 hook.jObj = S3JniRefGlobal(jTracer);
5182 S3JniDb_mutex_enter;
5183 rc = sqlite3_trace_v2(ps->pDb, (unsigned)traceMask, s3jni_trace_impl, ps);
5184 if( 0==rc ){
5185 S3JniHook_unref(&ps->hooks.trace);
5186 ps->hooks.trace = hook /* transfer ownership of reference */;
5187 }else{
5188 S3JniHook_unref(&hook);
5189 }
5190 S3JniDb_mutex_leave;
5191 }
5192 }
5193 return rc;
5194 }
5195
5196 S3JniApi(sqlite3_txn_state(),jint,1txn_1state)(
5197 JniArgsEnvClass,jobject jDb, jstring jSchema
5198 ){
5199 sqlite3 * const pDb = PtrGet_sqlite3(jDb);
5200 int rc = SQLITE_MISUSE;
5201 if( pDb ){
5202 char * zSchema = jSchema
5203 ? s3jni_jstring_to_utf8(jSchema, 0)
5204 : 0;
5205 if( !jSchema || (zSchema && jSchema) ){
5206 rc = sqlite3_txn_state(pDb, zSchema);
5207 sqlite3_free(zSchema);
5208 }else{
5209 rc = SQLITE_NOMEM;
5210 }
5211 }
5212 return rc;
5213 }
5214
5215 S3JniApi(sqlite3_update_hook(),jobject,1update_1hook)(
5216 JniArgsEnvClass, jlong jpDb, jobject jHook
5217 ){
5218 return s3jni_updatepre_hook(env, 0, jpDb, jHook);
5219 }
5220
5221
5222 S3JniApi(sqlite3_value_blob(),jbyteArray,1value_1blob)(
5223 JniArgsEnvClass, jlong jpSVal
5224 ){
5225 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5226 const jbyte * pBytes = sv ? sqlite3_value_blob(sv) : 0;
5227 int const nLen = pBytes ? sqlite3_value_bytes(sv) : 0;
5228
5229 s3jni_oom_check( nLen ? !!pBytes : 1 );
5230 return pBytes
5231 ? s3jni_new_jbyteArray(pBytes, nLen)
5232 : NULL;
5233 }
5234
5235 S3JniApi(sqlite3_value_bytes(),jint,1value_1bytes)(
5236 JniArgsEnvClass, jlong jpSVal
5237 ){
5238 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5239 return sv ? sqlite3_value_bytes(sv) : 0;
5240 }
5241
5242 S3JniApi(sqlite3_value_bytes16(),jint,1value_1bytes16)(
5243 JniArgsEnvClass, jlong jpSVal
5244 ){
5245 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5246 return sv ? sqlite3_value_bytes16(sv) : 0;
5247 }
5248
5249
5250 S3JniApi(sqlite3_value_double(),jdouble,1value_1double)(
5251 JniArgsEnvClass, jlong jpSVal
5252 ){
5253 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5254 return (jdouble) (sv ? sqlite3_value_double(sv) : 0.0);
5255 }
5256
5257
5258 S3JniApi(sqlite3_value_dup(),jobject,1value_1dup)(
5259 JniArgsEnvClass, jlong jpSVal
5260 ){
5261 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5262 sqlite3_value * const sd = sv ? sqlite3_value_dup(sv) : 0;
5263 jobject rv = sd ? new_java_sqlite3_value(env, sd) : 0;
5264 if( sd && !rv ) {
5265 /* OOM */
5266 sqlite3_value_free(sd);
5267 }
5268 return rv;
5269 }
5270
5271 S3JniApi(sqlite3_value_free(),void,1value_1free)(
5272 JniArgsEnvClass, jlong jpSVal
5273 ){
5274 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5275 if( sv ){
5276 sqlite3_value_free(sv);
5277 }
5278 }
5279
5280 S3JniApi(sqlite3_value_int(),jint,1value_1int)(
5281 JniArgsEnvClass, jlong jpSVal
5282 ){
5283 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5284 return (jint) (sv ? sqlite3_value_int(sv) : 0);
5285 }
5286
5287 S3JniApi(sqlite3_value_int64(),jlong,1value_1int64)(
5288 JniArgsEnvClass, jlong jpSVal
5289 ){
5290 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5291 return (jlong) (sv ? sqlite3_value_int64(sv) : 0LL);
5292 }
5293
5294 S3JniApi(sqlite3_value_java_object(),jobject,1value_1java_1object)(
5295 JniArgsEnvClass, jlong jpSVal
5296 ){
5297 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5298 return sv
5299 ? sqlite3_value_pointer(sv, s3jni__value_jref_key)
5300 : 0;
5301 }
5302
5303 S3JniApi(sqlite3_value_nio_buffer(),jobject,1value_1nio_1buffer)(
5304 JniArgsEnvClass, jobject jVal
5305 ){
5306 sqlite3_value * const sv = PtrGet_sqlite3_value(jVal);
5307 jobject rv = 0;
5308 if( sv ){
5309 const void * const p = sqlite3_value_blob(sv);
5310 if( p ){
5311 const int n = sqlite3_value_bytes(sv);
5312 rv = s3jni__blob_to_ByteBuffer(env, p, n);
5313 }
5314 }
5315 return rv;
5316 }
5317
5318 S3JniApi(sqlite3_value_text(),jbyteArray,1value_1text)(
5319 JniArgsEnvClass, jlong jpSVal
5320 ){
5321 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5322 const unsigned char * const p = sv ? sqlite3_value_text(sv) : 0;
5323 int const n = p ? sqlite3_value_bytes(sv) : 0;
5324 return p ? s3jni_new_jbyteArray(p, n) : 0;
5325 }
5326
5327 #if 0
5328 // this impl might prove useful.
5329 S3JniApi(sqlite3_value_text(),jstring,1value_1text)(
5330 JniArgsEnvClass, jlong jpSVal
5331 ){
5332 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5333 const unsigned char * const p = sv ? sqlite3_value_text(sv) : 0;
5334 int const n = p ? sqlite3_value_bytes(sv) : 0;
5335 return p ? s3jni_utf8_to_jstring( (const char *)p, n) : 0;
5336 }
5337 #endif
5338
5339 S3JniApi(sqlite3_value_text16(),jstring,1value_1text16)(
5340 JniArgsEnvClass, jlong jpSVal
5341 ){
5342 sqlite3_value * const sv = LongPtrGet_sqlite3_value(jpSVal);
5343 const int n = sv ? sqlite3_value_bytes16(sv) : 0;
5344 const void * const p = sv ? sqlite3_value_text16(sv) : 0;
5345 return p ? s3jni_text16_to_jstring(env, p, n) : 0;
5346 }
5347
5348 JniDecl(void,1jni_1internal_1details)(JniArgsEnvClass){
5349 MARKER(("\nVarious bits of internal info:\n"));
5350 puts("FTS5 is "
5351 #ifdef SQLITE_ENABLE_FTS5
5352 "available"
5353 #else
5354 "unavailable"
5355 #endif
5356 "."
5357 );
5358 puts("sizeofs:");
5359 #define SO(T) printf("\tsizeof(" #T ") = %u\n", (unsigned)sizeof(T))
5360 SO(void*);
5361 SO(jmethodID);
5362 SO(jfieldID);
5363 SO(S3JniEnv);
5364 SO(S3JniHook);
5365 SO(S3JniDb);
5366 SO(S3JniNphOps);
5367 printf("\t(^^^ %u NativePointerHolder/OutputPointer.T types)\n",
5368 (unsigned)S3Jni_NphCache_size);
5369 SO(S3JniGlobal);
5370 SO(S3JniGlobal.nph);
5371 SO(S3JniGlobal.metrics);
5372 SO(S3JniAutoExtension);
5373 SO(S3JniUdf);
5374 #undef SO
5375 #ifdef SQLITE_JNI_ENABLE_METRICS
5376 printf("Cache info:\n");
5377 printf("\tJNIEnv cache: %u allocs, %u misses, %u hits\n",
5378 SJG.metrics.nEnvAlloc, SJG.metrics.nEnvMiss,
5379 SJG.metrics.nEnvHit);
5380 printf("Mutex entry:"
5381 "\n\tglobal = %u"
5382 "\n\tenv = %u"
5383 "\n\tnph = %u for S3JniNphOp init"
5384 "\n\thook = %u"
5385 "\n\tperDb = %u"
5386 "\n\tautoExt list = %u"
5387 "\n\tS3JniUdf = %u (free-list)"
5388 "\n\tmetrics = %u\n",
5389 SJG.metrics.nMutexGlobal, SJG.metrics.nMutexEnv,
5390 SJG.metrics.nMutexNph, SJG.metrics.nMutexHook,
5391 SJG.metrics.nMutexPerDb, SJG.metrics.nMutexAutoExt,
5392 SJG.metrics.nMutexUdf, SJG.metrics.nMetrics);
5393 puts("Allocs:");
5394 printf("\tS3JniDb: %u alloced (*%u = %u bytes), %u recycled\n",
5395 SJG.metrics.nPdbAlloc, (unsigned) sizeof(S3JniDb),
5396 (unsigned)(SJG.metrics.nPdbAlloc * sizeof(S3JniDb)),
5397 SJG.metrics.nPdbRecycled);
5398 printf("\tS3JniUdf: %u alloced (*%u = %u bytes), %u recycled\n",
5399 SJG.metrics.nUdfAlloc, (unsigned) sizeof(S3JniUdf),
5400 (unsigned)(SJG.metrics.nUdfAlloc * sizeof(S3JniUdf)),
5401 SJG.metrics.nUdfRecycled);
5402 printf("\tS3JniHook: %u alloced (*%u = %u bytes), %u recycled\n",
5403 SJG.metrics.nHookAlloc, (unsigned) sizeof(S3JniHook),
5404 (unsigned)(SJG.metrics.nHookAlloc * sizeof(S3JniHook)),
5405 SJG.metrics.nHookRecycled);
5406 printf("\tS3JniEnv: %u alloced (*%u = %u bytes)\n",
5407 SJG.metrics.nEnvAlloc, (unsigned) sizeof(S3JniEnv),
5408 (unsigned)(SJG.metrics.nEnvAlloc * sizeof(S3JniEnv)));
5409 puts("Java-side UDF calls:");
5410 #define UDF(T) printf("\t%-8s = %u\n", "x" #T, SJG.metrics.udf.n##T)
5411 UDF(Func); UDF(Step); UDF(Final); UDF(Value); UDF(Inverse);
5412 #undef UDF
5413 printf("xDestroy calls across all callback types: %u\n",
5414 SJG.metrics.nDestroy);
5415 #else
5416 puts("Built without SQLITE_JNI_ENABLE_METRICS.");
5417 #endif
5418 }
5419
5420 ////////////////////////////////////////////////////////////////////////
5421 // End of the sqlite3_... API bindings. Next up, FTS5...
5422 ////////////////////////////////////////////////////////////////////////
5423 #ifdef SQLITE_ENABLE_FTS5
5424
5425 /* Creates a verbose JNI Fts5 function name. */
5426 #define JniFuncNameFtsXA(Suffix) \
5427 Java_org_sqlite_jni_fts5_Fts5ExtensionApi_ ## Suffix
5428 #define JniFuncNameFtsApi(Suffix) \
5429 Java_org_sqlite_jni_fts5_fts5_1api_ ## Suffix
5430 #define JniFuncNameFtsTok(Suffix) \
5431 Java_org_sqlite_jni_fts5_fts5_tokenizer_ ## Suffix
5432
5433 #define JniDeclFtsXA(ReturnType,Suffix) \
5434 JNIEXPORT ReturnType JNICALL \
5435 JniFuncNameFtsXA(Suffix)
5436 #define JniDeclFtsApi(ReturnType,Suffix) \
5437 JNIEXPORT ReturnType JNICALL \
5438 JniFuncNameFtsApi(Suffix)
5439 #define JniDeclFtsTok(ReturnType,Suffix) \
5440 JNIEXPORT ReturnType JNICALL \
5441 JniFuncNameFtsTok(Suffix)
5442
5443 #define PtrGet_fts5_api(OBJ) NativePointerHolder_get(OBJ,S3JniNph(fts5_api))
5444 #define PtrGet_fts5_tokenizer(OBJ) NativePointerHolder_get(OBJ,S3JniNph(fts5_tokenizer))
5445 #define PtrGet_Fts5Context(OBJ) NativePointerHolder_get(OBJ,S3JniNph(Fts5Context))
5446 #define PtrGet_Fts5Tokenizer(OBJ) NativePointerHolder_get(OBJ,S3JniNph(Fts5Tokenizer))
5447 #define s3jni_ftsext() &sFts5Api/*singleton from sqlite3.c*/
5448 #define Fts5ExtDecl Fts5ExtensionApi const * const ext = s3jni_ftsext()
5449
5450 /**
5451 State for binding Java-side FTS5 auxiliary functions.
5452 */
5453 typedef struct {
5454 jobject jObj /* functor instance */;
5455 jobject jUserData /* 2nd arg to JNI binding of
5456 xCreateFunction(), ostensibly the 3rd arg
5457 to the lib-level xCreateFunction(), except
5458 that we necessarily use that slot for a
5459 Fts5JniAux instance. */;
5460 char * zFuncName /* Only for error reporting and debug logging */;
5461 jmethodID jmid /* callback member's method ID */;
5462 } Fts5JniAux;
5463
5464 static void Fts5JniAux_free(Fts5JniAux * const s){
5465 S3JniDeclLocal_env;
5466 if( env ){
5467 /*MARKER(("FTS5 aux function cleanup: %s\n", s->zFuncName));*/
5468 s3jni_call_xDestroy(s->jObj);
5469 S3JniUnrefGlobal(s->jObj);
5470 S3JniUnrefGlobal(s->jUserData);
5471 }
5472 sqlite3_free(s->zFuncName);
5473 sqlite3_free(s);
5474 }
5475
5476 static void Fts5JniAux_xDestroy(void *p){
5477 if( p ) Fts5JniAux_free(p);
5478 }
5479
5480 static Fts5JniAux * Fts5JniAux_alloc(JNIEnv * const env, jobject jObj){
5481 Fts5JniAux * s = s3jni_malloc( sizeof(Fts5JniAux));
5482
5483 if( s ){
5484 jclass klazz;
5485 memset(s, 0, sizeof(Fts5JniAux));
5486 s->jObj = S3JniRefGlobal(jObj);
5487 klazz = (*env)->GetObjectClass(env, jObj);
5488 s->jmid = (*env)->GetMethodID(env, klazz, "call",
5489 "(Lorg/sqlite/jni/fts5/Fts5ExtensionApi;"
5490 "Lorg/sqlite/jni/fts5/Fts5Context;"
5491 "Lorg/sqlite/jni/capi/sqlite3_context;"
5492 "[Lorg/sqlite/jni/capi/sqlite3_value;)V");
5493 S3JniUnrefLocal(klazz);
5494 S3JniIfThrew{
5495 S3JniExceptionReport;
5496 S3JniExceptionClear;
5497 Fts5JniAux_free(s);
5498 s = 0;
5499 }
5500 }
5501 return s;
5502 }
5503
5504 static inline jobject new_java_Fts5Context(JNIEnv * const env, Fts5Context *sv){
5505 return NativePointerHolder_new(env, S3JniNph(Fts5Context), sv);
5506 }
5507 static inline jobject new_java_fts5_api(JNIEnv * const env, fts5_api *sv){
5508 return NativePointerHolder_new(env, S3JniNph(fts5_api), sv);
5509 }
5510
5511 /*
5512 ** Returns a per-JNIEnv global ref to the Fts5ExtensionApi singleton
5513 ** instance, or NULL on OOM.
5514 */
5515 static jobject s3jni_getFts5ExensionApi(JNIEnv * const env){
5516 if( !SJG.fts5.jExt ){
5517 S3JniGlobal_mutex_enter;
5518 if( !SJG.fts5.jExt ){
5519 jobject const pNPH = NativePointerHolder_new(
5520 env, S3JniNph(Fts5ExtensionApi), s3jni_ftsext()
5521 );
5522 if( pNPH ){
5523 SJG.fts5.jExt = S3JniRefGlobal(pNPH);
5524 S3JniUnrefLocal(pNPH);
5525 }
5526 }
5527 S3JniGlobal_mutex_leave;
5528 }
5529 return SJG.fts5.jExt;
5530 }
5531
5532 /*
5533 ** Returns a pointer to the fts5_api instance for database connection
5534 ** db. If an error occurs, returns NULL and leaves an error in the
5535 ** database handle (accessible using sqlite3_errcode()/errmsg()).
5536 */
5537 static fts5_api *s3jni_fts5_api_from_db(sqlite3 *db){
5538 fts5_api *pRet = 0;
5539 sqlite3_stmt *pStmt = 0;
5540 if( SQLITE_OK==sqlite3_prepare(db, "SELECT fts5(?1)", -1, &pStmt, 0) ){
5541 sqlite3_bind_pointer(pStmt, 1, (void*)&pRet, "fts5_api_ptr", NULL);
5542 sqlite3_step(pStmt);
5543 }
5544 sqlite3_finalize(pStmt);
5545 return pRet;
5546 }
5547
5548 JniDeclFtsApi(jobject,getInstanceForDb)(JniArgsEnvClass,jobject jDb){
5549 S3JniDb * const ps = S3JniDb_from_java(jDb);
5550 #if 0
5551 jobject rv = 0;
5552 if( !ps ) return 0;
5553 else if( ps->fts.jApi ){
5554 rv = ps->fts.jApi;
5555 }else{
5556 fts5_api * const pApi = s3jni_fts5_api_from_db(ps->pDb);
5557 if( pApi ){
5558 rv = new_java_fts5_api(env, pApi);
5559 ps->fts.jApi = rv ? S3JniRefGlobal(rv) : 0;
5560 }
5561 }
5562 return rv;
5563 #else
5564 if( ps && !ps->fts.jApi ){
5565 S3JniDb_mutex_enter;
5566 if( !ps->fts.jApi ){
5567 fts5_api * const pApi = s3jni_fts5_api_from_db(ps->pDb);
5568 if( pApi ){
5569 jobject const rv = new_java_fts5_api(env, pApi);
5570 ps->fts.jApi = rv ? S3JniRefGlobal(rv) : 0;
5571 }
5572 }
5573 S3JniDb_mutex_leave;
5574 }
5575 return ps ? ps->fts.jApi : 0;
5576 #endif
5577 }
5578
5579
5580 JniDeclFtsXA(jobject,getInstance)(JniArgsEnvClass){
5581 return s3jni_getFts5ExensionApi(env);
5582 }
5583
5584 JniDeclFtsXA(jint,xColumnCount)(JniArgsEnvObj,jobject jCtx){
5585 Fts5ExtDecl;
5586 return (jint)ext->xColumnCount(PtrGet_Fts5Context(jCtx));
5587 }
5588
5589 JniDeclFtsXA(jint,xColumnSize)(JniArgsEnvObj,jobject jCtx, jint iIdx, jobject jOut32){
5590 Fts5ExtDecl;
5591 int n1 = 0;
5592 int const rc = ext->xColumnSize(PtrGet_Fts5Context(jCtx), (int)iIdx, &n1);
5593 if( 0==rc ) OutputPointer_set_Int32(env, jOut32, n1);
5594 return rc;
5595 }
5596
5597 JniDeclFtsXA(jint,xColumnText)(JniArgsEnvObj,jobject jCtx, jint iCol,
5598 jobject jOut){
5599 Fts5ExtDecl;
5600 const char *pz = 0;
5601 int pn = 0;
5602 int rc = ext->xColumnText(PtrGet_Fts5Context(jCtx), (int)iCol,
5603 &pz, &pn);
5604 if( 0==rc ){
5605 jstring jstr = pz ? s3jni_utf8_to_jstring( pz, pn) : 0;
5606 if( pz ){
5607 if( jstr ){
5608 OutputPointer_set_String(env, jOut, jstr);
5609 S3JniUnrefLocal(jstr)/*jOut has a reference*/;
5610 }else{
5611 rc = SQLITE_NOMEM;
5612 }
5613 }
5614 }
5615 return (jint)rc;
5616 }
5617
5618 JniDeclFtsXA(jint,xColumnTotalSize)(JniArgsEnvObj,jobject jCtx, jint iCol, jobject jOut64){
5619 Fts5ExtDecl;
5620 sqlite3_int64 nOut = 0;
5621 int const rc = ext->xColumnTotalSize(PtrGet_Fts5Context(jCtx), (int)iCol, &nOut);
5622 if( 0==rc && jOut64 ) OutputPointer_set_Int64(env, jOut64, (jlong)nOut);
5623 return (jint)rc;
5624 }
5625
5626 /*
5627 ** Proxy for fts5_extension_function instances plugged in via
5628 ** fts5_api::xCreateFunction().
5629 */
5630 static void s3jni_fts5_extension_function(Fts5ExtensionApi const *pApi,
5631 Fts5Context *pFts,
5632 sqlite3_context *pCx,
5633 int argc,
5634 sqlite3_value **argv){
5635 Fts5JniAux * const pAux = pApi->xUserData(pFts);
5636 jobject jpCx = 0;
5637 jobjectArray jArgv = 0;
5638 jobject jpFts = 0;
5639 jobject jFXA;
5640 int rc;
5641 S3JniDeclLocal_env;
5642
5643 assert(pAux);
5644 jFXA = s3jni_getFts5ExensionApi(env);
5645 if( !jFXA ) goto error_oom;
5646 jpFts = new_java_Fts5Context(env, pFts);
5647 if( !jpFts ) goto error_oom;
5648 rc = udf_args(env, pCx, argc, argv, &jpCx, &jArgv);
5649 if( rc ) goto error_oom;
5650 (*env)->CallVoidMethod(env, pAux->jObj, pAux->jmid,
5651 jFXA, jpFts, jpCx, jArgv);
5652 S3JniIfThrew{
5653 udf_report_exception(env, 1, pCx, pAux->zFuncName, "call");
5654 }
5655 udf_unargs(env, jpCx, argc, jArgv);
5656 S3JniUnrefLocal(jpFts);
5657 S3JniUnrefLocal(jpCx);
5658 S3JniUnrefLocal(jArgv);
5659 return;
5660 error_oom:
5661 s3jni_db_oom( sqlite3_context_db_handle(pCx) );
5662 assert( !jArgv );
5663 assert( !jpCx );
5664 S3JniUnrefLocal(jpFts);
5665 sqlite3_result_error_nomem(pCx);
5666 return;
5667 }
5668
5669 JniDeclFtsApi(jint,xCreateFunction)(JniArgsEnvObj, jstring jName,
5670 jobject jUserData, jobject jFunc){
5671 fts5_api * const pApi = PtrGet_fts5_api(jSelf);
5672 int rc;
5673 char * zName;
5674 Fts5JniAux * pAux;
5675
5676 assert(pApi);
5677 zName = s3jni_jstring_to_utf8( jName, 0);
5678 if(!zName) return SQLITE_NOMEM;
5679 pAux = Fts5JniAux_alloc(env, jFunc);
5680 if( pAux ){
5681 rc = pApi->xCreateFunction(pApi, zName, pAux,
5682 s3jni_fts5_extension_function,
5683 Fts5JniAux_xDestroy);
5684 }else{
5685 rc = SQLITE_NOMEM;
5686 }
5687 if( 0==rc ){
5688 pAux->jUserData = jUserData ? S3JniRefGlobal(jUserData) : 0;
5689 pAux->zFuncName = zName;
5690 }else{
5691 sqlite3_free(zName);
5692 }
5693 return (jint)rc;
5694 }
5695
5696
5697 typedef struct S3JniFts5AuxData S3JniFts5AuxData;
5698 /*
5699 ** TODO: this middle-man struct is no longer necessary. Conider
5700 ** removing it and passing around jObj itself instead.
5701 */
5702 struct S3JniFts5AuxData {
5703 jobject jObj;
5704 };
5705
5706 static void S3JniFts5AuxData_xDestroy(void *x){
5707 if( x ){
5708 S3JniFts5AuxData * const p = x;
5709 if( p->jObj ){
5710 S3JniDeclLocal_env;
5711 s3jni_call_xDestroy(p->jObj);
5712 S3JniUnrefGlobal(p->jObj);
5713 }
5714 sqlite3_free(x);
5715 }
5716 }
5717
5718 JniDeclFtsXA(jobject,xGetAuxdata)(JniArgsEnvObj,jobject jCtx, jboolean bClear){
5719 Fts5ExtDecl;
5720 jobject rv = 0;
5721 S3JniFts5AuxData * const pAux = ext->xGetAuxdata(PtrGet_Fts5Context(jCtx), bClear);
5722 if( pAux ){
5723 if( bClear ){
5724 if( pAux->jObj ){
5725 rv = S3JniRefLocal(pAux->jObj);
5726 S3JniUnrefGlobal(pAux->jObj);
5727 }
5728 /* Note that we do not call xDestroy() in this case. */
5729 sqlite3_free(pAux);
5730 }else{
5731 rv = pAux->jObj;
5732 }
5733 }
5734 return rv;
5735 }
5736
5737 JniDeclFtsXA(jint,xInst)(JniArgsEnvObj,jobject jCtx, jint iIdx, jobject jOutPhrase,
5738 jobject jOutCol, jobject jOutOff){
5739 Fts5ExtDecl;
5740 int n1 = 0, n2 = 2, n3 = 0;
5741 int const rc = ext->xInst(PtrGet_Fts5Context(jCtx), (int)iIdx, &n1, &n2, &n3);
5742 if( 0==rc ){
5743 OutputPointer_set_Int32(env, jOutPhrase, n1);
5744 OutputPointer_set_Int32(env, jOutCol, n2);
5745 OutputPointer_set_Int32(env, jOutOff, n3);
5746 }
5747 return rc;
5748 }
5749
5750 JniDeclFtsXA(jint,xInstCount)(JniArgsEnvObj,jobject jCtx, jobject jOut32){
5751 Fts5ExtDecl;
5752 int nOut = 0;
5753 int const rc = ext->xInstCount(PtrGet_Fts5Context(jCtx), &nOut);
5754 if( 0==rc && jOut32 ) OutputPointer_set_Int32(env, jOut32, nOut);
5755 return (jint)rc;
5756 }
5757
5758 JniDeclFtsXA(jint,xPhraseCount)(JniArgsEnvObj,jobject jCtx){
5759 Fts5ExtDecl;
5760 return (jint)ext->xPhraseCount(PtrGet_Fts5Context(jCtx));
5761 }
5762
5763 /* Copy the 'a' and 'b' fields from pSrc to Fts5PhraseIter object jIter. */
5764 static void s3jni_phraseIter_NToJ(JNIEnv *const env,
5765 Fts5PhraseIter const * const pSrc,
5766 jobject jIter){
5767 S3JniGlobalType * const g = &S3JniGlobal;
5768 assert(g->fts5.jPhraseIter.fidA);
5769 (*env)->SetLongField(env, jIter, g->fts5.jPhraseIter.fidA,
5770 S3JniCast_P2L(pSrc->a));
5771 S3JniExceptionIsFatal("Cannot set Fts5PhraseIter.a field.");
5772 (*env)->SetLongField(env, jIter, g->fts5.jPhraseIter.fidB,
5773 S3JniCast_P2L(pSrc->b));
5774 S3JniExceptionIsFatal("Cannot set Fts5PhraseIter.b field.");
5775 }
5776
5777 /* Copy the 'a' and 'b' fields from Fts5PhraseIter object jIter to pDest. */
5778 static void s3jni_phraseIter_JToN(JNIEnv *const env, jobject jIter,
5779 Fts5PhraseIter * const pDest){
5780 S3JniGlobalType * const g = &S3JniGlobal;
5781 assert(g->fts5.jPhraseIter.fidA);
5782 pDest->a = S3JniCast_L2P(
5783 (*env)->GetLongField(env, jIter, g->fts5.jPhraseIter.fidA)
5784 );
5785 S3JniExceptionIsFatal("Cannot get Fts5PhraseIter.a field.");
5786 pDest->b = S3JniCast_L2P(
5787 (*env)->GetLongField(env, jIter, g->fts5.jPhraseIter.fidB)
5788 );
5789 S3JniExceptionIsFatal("Cannot get Fts5PhraseIter.b field.");
5790 }
5791
5792 JniDeclFtsXA(jint,xPhraseFirst)(JniArgsEnvObj,jobject jCtx, jint iPhrase,
5793 jobject jIter, jobject jOutCol,
5794 jobject jOutOff){
5795 Fts5ExtDecl;
5796 Fts5PhraseIter iter;
5797 int rc, iCol = 0, iOff = 0;
5798 rc = ext->xPhraseFirst(PtrGet_Fts5Context(jCtx), (int)iPhrase,
5799 &iter, &iCol, &iOff);
5800 if( 0==rc ){
5801 OutputPointer_set_Int32(env, jOutCol, iCol);
5802 OutputPointer_set_Int32(env, jOutOff, iOff);
5803 s3jni_phraseIter_NToJ(env, &iter, jIter);
5804 }
5805 return rc;
5806 }
5807
5808 JniDeclFtsXA(jint,xPhraseFirstColumn)(JniArgsEnvObj,jobject jCtx, jint iPhrase,
5809 jobject jIter, jobject jOutCol){
5810 Fts5ExtDecl;
5811 Fts5PhraseIter iter;
5812 int rc, iCol = 0;
5813 rc = ext->xPhraseFirstColumn(PtrGet_Fts5Context(jCtx), (int)iPhrase,
5814 &iter, &iCol);
5815 if( 0==rc ){
5816 OutputPointer_set_Int32(env, jOutCol, iCol);
5817 s3jni_phraseIter_NToJ(env, &iter, jIter);
5818 }
5819 return rc;
5820 }
5821
5822 JniDeclFtsXA(void,xPhraseNext)(JniArgsEnvObj,jobject jCtx, jobject jIter,
5823 jobject jOutCol, jobject jOutOff){
5824 Fts5ExtDecl;
5825 Fts5PhraseIter iter;
5826 int iCol = 0, iOff = 0;
5827 s3jni_phraseIter_JToN(env, jIter, &iter);
5828 ext->xPhraseNext(PtrGet_Fts5Context(jCtx), &iter, &iCol, &iOff);
5829 OutputPointer_set_Int32(env, jOutCol, iCol);
5830 OutputPointer_set_Int32(env, jOutOff, iOff);
5831 s3jni_phraseIter_NToJ(env, &iter, jIter);
5832 }
5833
5834 JniDeclFtsXA(void,xPhraseNextColumn)(JniArgsEnvObj,jobject jCtx, jobject jIter,
5835 jobject jOutCol){
5836 Fts5ExtDecl;
5837 Fts5PhraseIter iter;
5838 int iCol = 0;
5839 s3jni_phraseIter_JToN(env, jIter, &iter);
5840 ext->xPhraseNextColumn(PtrGet_Fts5Context(jCtx), &iter, &iCol);
5841 OutputPointer_set_Int32(env, jOutCol, iCol);
5842 s3jni_phraseIter_NToJ(env, &iter, jIter);
5843 }
5844
5845
5846 JniDeclFtsXA(jint,xPhraseSize)(JniArgsEnvObj,jobject jCtx, jint iPhrase){
5847 Fts5ExtDecl;
5848 return (jint)ext->xPhraseSize(PtrGet_Fts5Context(jCtx), (int)iPhrase);
5849 }
5850
5851 /* State for use with xQueryPhrase() and xTokenize(). */
5852 struct s3jni_xQueryPhraseState {
5853 Fts5ExtensionApi const * ext;
5854 jmethodID midCallback; /* jCallback->call() method */
5855 jobject jCallback; /* Fts5ExtensionApi.XQueryPhraseCallback instance */
5856 jobject jFcx; /* (Fts5Context*) for xQueryPhrase()
5857 callback. This is NOT the instance that is
5858 passed to xQueryPhrase(), it's the one
5859 created by xQueryPhrase() for use by its
5860 callback. */
5861 /* State for xTokenize() */
5862 struct {
5863 const char * zPrev;
5864 int nPrev;
5865 jbyteArray jba;
5866 } tok;
5867 };
5868
5869 static int s3jni_xQueryPhrase(const Fts5ExtensionApi *xapi,
5870 Fts5Context * pFcx, void *pData){
5871 struct s3jni_xQueryPhraseState * const s = pData;
5872 S3JniDeclLocal_env;
5873
5874 if( !s->jFcx ){
5875 s->jFcx = new_java_Fts5Context(env, pFcx);
5876 if( !s->jFcx ) return SQLITE_NOMEM;
5877 }
5878 int rc = (int)(*env)->CallIntMethod(env, s->jCallback, s->midCallback,
5879 SJG.fts5.jExt, s->jFcx);
5880 S3JniIfThrew{
5881 S3JniExceptionWarnCallbackThrew("xQueryPhrase() callback");
5882 S3JniExceptionClear;
5883 rc = SQLITE_ERROR;
5884 }
5885 return rc;
5886 }
5887
5888 JniDeclFtsXA(jint,xQueryPhrase)(JniArgsEnvObj,jobject jFcx, jint iPhrase,
5889 jobject jCallback){
5890 Fts5ExtDecl;
5891 int rc;
5892 struct s3jni_xQueryPhraseState s;
5893 jclass klazz = jCallback ? (*env)->GetObjectClass(env, jCallback) : NULL;
5894
5895 if( !klazz ) return SQLITE_MISUSE;
5896 s.jCallback = jCallback;
5897 s.jFcx = 0;
5898 s.ext = ext;
5899 s.midCallback = (*env)->GetMethodID(env, klazz, "call",
5900 "(Lorg/sqlite/jni/fts5/Fts5ExtensionApi;"
5901 "Lorg/sqlite/jni/fts5/Fts5Context;)I");
5902 S3JniUnrefLocal(klazz);
5903 S3JniExceptionIsFatal("Could not extract xQueryPhraseCallback.call() method.");
5904 rc = ext->xQueryPhrase(PtrGet_Fts5Context(jFcx), iPhrase, &s,
5905 s3jni_xQueryPhrase);
5906 S3JniUnrefLocal(s.jFcx);
5907 return (jint)rc;
5908 }
5909
5910
5911 JniDeclFtsXA(jint,xRowCount)(JniArgsEnvObj,jobject jCtx, jobject jOut64){
5912 Fts5ExtDecl;
5913 sqlite3_int64 nOut = 0;
5914 int const rc = ext->xRowCount(PtrGet_Fts5Context(jCtx), &nOut);
5915 if( 0==rc && jOut64 ) OutputPointer_set_Int64(env, jOut64, (jlong)nOut);
5916 return (jint)rc;
5917 }
5918
5919 JniDeclFtsXA(jlong,xRowid)(JniArgsEnvObj,jobject jCtx){
5920 Fts5ExtDecl;
5921 return (jlong)ext->xRowid(PtrGet_Fts5Context(jCtx));
5922 }
5923
5924 JniDeclFtsXA(jint,xSetAuxdata)(JniArgsEnvObj,jobject jCtx, jobject jAux){
5925 Fts5ExtDecl;
5926 int rc;
5927 S3JniFts5AuxData * pAux;
5928
5929 pAux = s3jni_malloc( sizeof(*pAux));
5930 if( !pAux ){
5931 if( jAux ){
5932 /* Emulate how xSetAuxdata() behaves when it cannot alloc
5933 ** its auxdata wrapper. */
5934 s3jni_call_xDestroy(jAux);
5935 }
5936 return SQLITE_NOMEM;
5937 }
5938 pAux->jObj = S3JniRefGlobal(jAux);
5939 rc = ext->xSetAuxdata(PtrGet_Fts5Context(jCtx), pAux,
5940 S3JniFts5AuxData_xDestroy);
5941 return rc;
5942 }
5943
5944 /* xToken() impl for xTokenize(). */
5945 static int s3jni_xTokenize_xToken(void *p, int tFlags, const char* z,
5946 int nZ, int iStart, int iEnd){
5947 int rc;
5948 S3JniDeclLocal_env;
5949 struct s3jni_xQueryPhraseState * const s = p;
5950 jbyteArray jba;
5951
5952 S3JniUnrefLocal(s->tok.jba);
5953 s->tok.zPrev = z;
5954 s->tok.nPrev = nZ;
5955 s->tok.jba = s3jni_new_jbyteArray(z, nZ);
5956 if( !s->tok.jba ) return SQLITE_NOMEM;
5957 jba = s->tok.jba;
5958 rc = (int)(*env)->CallIntMethod(env, s->jCallback, s->midCallback,
5959 (jint)tFlags, jba, (jint)iStart,
5960 (jint)iEnd);
5961 S3JniIfThrew {
5962 S3JniExceptionWarnCallbackThrew("xTokenize() callback");
5963 rc = SQLITE_ERROR;
5964 }
5965 return rc;
5966 }
5967
5968 /*
5969 ** Proxy for Fts5ExtensionApi.xTokenize() and
5970 ** fts5_tokenizer.xTokenize()
5971 */
5972 static jint s3jni_fts5_xTokenize(JniArgsEnvObj, S3JniNphOp const *pRef,
5973 jint tokFlags, jobject jFcx,
5974 jbyteArray jbaText, jobject jCallback){
5975 Fts5ExtDecl;
5976 struct s3jni_xQueryPhraseState s;
5977 int rc = 0;
5978 jbyte * const pText = jCallback ? s3jni_jbyteArray_bytes(jbaText) : 0;
5979 jsize nText = pText ? (*env)->GetArrayLength(env, jbaText) : 0;
5980 jclass const klazz = jCallback ? (*env)->GetObjectClass(env, jCallback) : NULL;
5981
5982 if( !klazz ) return SQLITE_MISUSE;
5983 memset(&s, 0, sizeof(s));
5984 s.jCallback = jCallback;
5985 s.jFcx = jFcx;
5986 s.ext = ext;
5987 s.midCallback = (*env)->GetMethodID(env, klazz, "call", "(I[BII)I");
5988 S3JniUnrefLocal(klazz);
5989 S3JniIfThrew {
5990 S3JniExceptionReport;
5991 S3JniExceptionClear;
5992 s3jni_jbyteArray_release(jbaText, pText);
5993 return SQLITE_ERROR;
5994 }
5995 s.tok.jba = S3JniRefLocal(jbaText);
5996 s.tok.zPrev = (const char *)pText;
5997 s.tok.nPrev = (int)nText;
5998 if( pRef == S3JniNph(Fts5ExtensionApi) ){
5999 rc = ext->xTokenize(PtrGet_Fts5Context(jFcx),
6000 (const char *)pText, (int)nText,
6001 &s, s3jni_xTokenize_xToken);
6002 }else if( pRef == S3JniNph(fts5_tokenizer) ){
6003 fts5_tokenizer * const pTok = PtrGet_fts5_tokenizer(jSelf);
6004 rc = pTok->xTokenize(PtrGet_Fts5Tokenizer(jFcx), &s, tokFlags,
6005 (const char *)pText, (int)nText,
6006 s3jni_xTokenize_xToken);
6007 }else{
6008 (*env)->FatalError(env, "This cannot happen. Maintenance required.");
6009 }
6010 if( s.tok.jba ){
6011 assert( s.tok.zPrev );
6012 S3JniUnrefLocal(s.tok.jba);
6013 }
6014 s3jni_jbyteArray_release(jbaText, pText);
6015 return (jint)rc;
6016 }
6017
6018 JniDeclFtsXA(jint,xTokenize)(JniArgsEnvObj,jobject jFcx, jbyteArray jbaText,
6019 jobject jCallback){
6020 return s3jni_fts5_xTokenize(env, jSelf, S3JniNph(Fts5ExtensionApi),
6021 0, jFcx, jbaText, jCallback);
6022 }
6023
6024 JniDeclFtsTok(jint,xTokenize)(JniArgsEnvObj,jobject jFcx, jint tokFlags,
6025 jbyteArray jbaText, jobject jCallback){
6026 return s3jni_fts5_xTokenize(env, jSelf, S3JniNph(Fts5Tokenizer),
6027 tokFlags, jFcx, jbaText, jCallback);
6028 }
6029
6030
6031 JniDeclFtsXA(jobject,xUserData)(JniArgsEnvObj,jobject jFcx){
6032 Fts5ExtDecl;
6033 Fts5JniAux * const pAux = ext->xUserData(PtrGet_Fts5Context(jFcx));
6034 return pAux ? pAux->jUserData : 0;
6035 }
6036
6037 #endif /* SQLITE_ENABLE_FTS5 */
6038
6039 ////////////////////////////////////////////////////////////////////////
6040 // End of the main API bindings. Start of SQLTester bits...
6041 ////////////////////////////////////////////////////////////////////////
6042
6043 #ifdef SQLITE_JNI_ENABLE_SQLTester
6044 typedef struct SQLTesterJni SQLTesterJni;
6045 struct SQLTesterJni {
6046 sqlite3_int64 nDup;
6047 };
6048 static SQLTesterJni SQLTester = {
6049 0
6050 };
6051
6052 static void SQLTester_dup_destructor(void*pToFree){
6053 u64 *p = (u64*)pToFree;
6054 assert( p!=0 );
6055 p--;
6056 assert( p[0]==0x2bbf4b7c );
6057 p[0] = 0;
6058 p[1] = 0;
6059 sqlite3_free(p);
6060 }
6061
6062 /*
6063 ** Implementation of
6064 **
6065 ** dup(TEXT)
6066 **
6067 ** This SQL function simply makes a copy of its text argument. But it
6068 ** returns the result using a custom destructor, in order to provide
6069 ** tests for the use of Mem.xDel() in the SQLite VDBE.
6070 */
6071 static void SQLTester_dup_func(
6072 sqlite3_context *context,
6073 int argc,
6074 sqlite3_value **argv
6075 ){
6076 u64 *pOut;
6077 char *z;
6078 int n = sqlite3_value_bytes(argv[0]);
6079 SQLTesterJni * const p = (SQLTesterJni *)sqlite3_user_data(context);
6080 S3JniDeclLocal_env;
6081
6082 ++p->nDup;
6083 if( n>0 && (pOut = s3jni_malloc( (n+16)&~7 ))!=0 ){
6084 pOut[0] = 0x2bbf4b7c;
6085 z = (char*)&pOut[1];
6086 memcpy(z, sqlite3_value_text(argv[0]), n);
6087 z[n] = 0;
6088 sqlite3_result_text(context, z, n, SQLTester_dup_destructor);
6089 }
6090 return;
6091 }
6092
6093 /*
6094 ** Return the number of calls to the dup() SQL function since the
6095 ** SQLTester context was opened or since the last dup_count() call.
6096 */
6097 static void SQLTester_dup_count_func(
6098 sqlite3_context *context,
6099 int argc,
6100 sqlite3_value **argv
6101 ){
6102 SQLTesterJni * const p = (SQLTesterJni *)sqlite3_user_data(context);
6103 sqlite3_result_int64(context, p->nDup);
6104 p->nDup = 0;
6105 }
6106
6107 /*
6108 ** Return non-zero if string z matches glob pattern zGlob and zero if the
6109 ** pattern does not match.
6110 **
6111 ** To repeat:
6112 **
6113 ** zero == no match
6114 ** non-zero == match
6115 **
6116 ** Globbing rules:
6117 **
6118 ** '*' Matches any sequence of zero or more characters.
6119 **
6120 ** '?' Matches exactly one character.
6121 **
6122 ** [...] Matches one character from the enclosed list of
6123 ** characters.
6124 **
6125 ** [^...] Matches one character not in the enclosed list.
6126 **
6127 ** '#' Matches any sequence of one or more digits with an
6128 ** optional + or - sign in front, or a hexadecimal
6129 ** literal of the form 0x...
6130 */
6131 static int SQLTester_strnotglob(const char *zGlob, const char *z){
6132 int c, c2;
6133 int invert;
6134 int seen;
6135
6136 while( (c = (*(zGlob++)))!=0 ){
6137 if( c=='*' ){
6138 while( (c=(*(zGlob++))) == '*' || c=='?' ){
6139 if( c=='?' && (*(z++))==0 ) return 0;
6140 }
6141 if( c==0 ){
6142 return 1;
6143 }else if( c=='[' ){
6144 while( *z && SQLTester_strnotglob(zGlob-1,z)==0 ){
6145 z++;
6146 }
6147 return (*z)!=0;
6148 }
6149 while( (c2 = (*(z++)))!=0 ){
6150 while( c2!=c ){
6151 c2 = *(z++);
6152 if( c2==0 ) return 0;
6153 }
6154 if( SQLTester_strnotglob(zGlob,z) ) return 1;
6155 }
6156 return 0;
6157 }else if( c=='?' ){
6158 if( (*(z++))==0 ) return 0;
6159 }else if( c=='[' ){
6160 int prior_c = 0;
6161 seen = 0;
6162 invert = 0;
6163 c = *(z++);
6164 if( c==0 ) return 0;
6165 c2 = *(zGlob++);
6166 if( c2=='^' ){
6167 invert = 1;
6168 c2 = *(zGlob++);
6169 }
6170 if( c2==']' ){
6171 if( c==']' ) seen = 1;
6172 c2 = *(zGlob++);
6173 }
6174 while( c2 && c2!=']' ){
6175 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
6176 c2 = *(zGlob++);
6177 if( c>=prior_c && c<=c2 ) seen = 1;
6178 prior_c = 0;
6179 }else{
6180 if( c==c2 ){
6181 seen = 1;
6182 }
6183 prior_c = c2;
6184 }
6185 c2 = *(zGlob++);
6186 }
6187 if( c2==0 || (seen ^ invert)==0 ) return 0;
6188 }else if( c=='#' ){
6189 if( z[0]=='0'
6190 && (z[1]=='x' || z[1]=='X')
6191 && sqlite3Isxdigit(z[2])
6192 ){
6193 z += 3;
6194 while( sqlite3Isxdigit(z[0]) ){ z++; }
6195 }else{
6196 if( (z[0]=='-' || z[0]=='+') && sqlite3Isdigit(z[1]) ) z++;
6197 if( !sqlite3Isdigit(z[0]) ) return 0;
6198 z++;
6199 while( sqlite3Isdigit(z[0]) ){ z++; }
6200 }
6201 }else{
6202 if( c!=(*(z++)) ) return 0;
6203 }
6204 }
6205 return *z==0;
6206 }
6207
6208 JNIEXPORT jint JNICALL
6209 Java_org_sqlite_jni_capi_SQLTester_strglob(
6210 JniArgsEnvClass, jbyteArray baG, jbyteArray baT
6211 ){
6212 int rc = 0;
6213 jbyte * const pG = s3jni_jbyteArray_bytes(baG);
6214 jbyte * const pT = pG ? s3jni_jbyteArray_bytes(baT) : 0;
6215
6216 s3jni_oom_fatal(pT);
6217 /* Note that we're relying on the byte arrays having been
6218 NUL-terminated on the Java side. */
6219 rc = !SQLTester_strnotglob((const char *)pG, (const char *)pT);
6220 s3jni_jbyteArray_release(baG, pG);
6221 s3jni_jbyteArray_release(baT, pT);
6222 return rc;
6223 }
6224
6225
6226 static int SQLTester_auto_extension(sqlite3 *pDb, const char **pzErr,
6227 const struct sqlite3_api_routines *ignored){
6228 sqlite3_create_function(pDb, "dup", 1, SQLITE_UTF8, &SQLTester,
6229 SQLTester_dup_func, 0, 0);
6230 sqlite3_create_function(pDb, "dup_count", 0, SQLITE_UTF8, &SQLTester,
6231 SQLTester_dup_count_func, 0, 0);
6232 return 0;
6233 }
6234
6235 JNIEXPORT void JNICALL
6236 Java_org_sqlite_jni_capi_SQLTester_installCustomExtensions(JniArgsEnvClass){
6237 sqlite3_auto_extension( (void(*)(void))SQLTester_auto_extension );
6238 }
6239
6240 #endif /* SQLITE_JNI_ENABLE_SQLTester */
6241 ////////////////////////////////////////////////////////////////////////
6242 // End of SQLTester bindings. Start of lower-level bits.
6243 ////////////////////////////////////////////////////////////////////////
6244
6245 /*
6246 ** Called during static init of the CApi class to set up global
6247 ** state.
6248 */
6249 JNIEXPORT void JNICALL
6250 Java_org_sqlite_jni_capi_CApi_init(JniArgsEnvClass){
6251 jclass klazz;
6252
6253 memset(&S3JniGlobal, 0, sizeof(S3JniGlobal));
6254 if( (*env)->GetJavaVM(env, &SJG.jvm) ){
6255 (*env)->FatalError(env, "GetJavaVM() failure shouldn't be possible.");
6256 return;
6257 }
6258
6259 /* Grab references to various global classes and objects... */
6260 SJG.g.cLong = S3JniRefGlobal((*env)->FindClass(env,"java/lang/Long"));
6261 S3JniExceptionIsFatal("Error getting reference to Long class.");
6262 SJG.g.ctorLong1 = (*env)->GetMethodID(env, SJG.g.cLong,
6263 "<init>", "(J)V");
6264 S3JniExceptionIsFatal("Error getting reference to Long constructor.");
6265
6266 SJG.g.cString = S3JniRefGlobal((*env)->FindClass(env,"java/lang/String"));
6267 S3JniExceptionIsFatal("Error getting reference to String class.");
6268 SJG.g.ctorStringBA =
6269 (*env)->GetMethodID(env, SJG.g.cString,
6270 "<init>", "([BLjava/nio/charset/Charset;)V");
6271 S3JniExceptionIsFatal("Error getting reference to String(byte[],Charset) ctor.");
6272 SJG.g.stringGetBytes =
6273 (*env)->GetMethodID(env, SJG.g.cString,
6274 "getBytes", "(Ljava/nio/charset/Charset;)[B");
6275 S3JniExceptionIsFatal("Error getting reference to String.getBytes(Charset).");
6276
6277 { /* java.nio.charset.StandardCharsets.UTF_8 */
6278 jfieldID fUtf8;
6279 klazz = (*env)->FindClass(env,"java/nio/charset/StandardCharsets");
6280 S3JniExceptionIsFatal("Error getting reference to StandardCharsets class.");
6281 fUtf8 = (*env)->GetStaticFieldID(env, klazz, "UTF_8",
6282 "Ljava/nio/charset/Charset;");
6283 S3JniExceptionIsFatal("Error getting StandardCharsets.UTF_8 field.");
6284 SJG.g.oCharsetUtf8 =
6285 S3JniRefGlobal((*env)->GetStaticObjectField(env, klazz, fUtf8));
6286 S3JniExceptionIsFatal("Error getting reference to StandardCharsets.UTF_8.");
6287 S3JniUnrefLocal(klazz);
6288 }
6289
6290 #ifdef SQLITE_ENABLE_FTS5
6291 klazz = (*env)->FindClass(env, "org/sqlite/jni/fts5/Fts5PhraseIter");
6292 S3JniExceptionIsFatal("Error getting reference to org.sqlite.jni.fts5.Fts5PhraseIter.");
6293 SJG.fts5.jPhraseIter.fidA = (*env)->GetFieldID(env, klazz, "a", "J");
6294 S3JniExceptionIsFatal("Cannot get Fts5PhraseIter.a field.");
6295 SJG.fts5.jPhraseIter.fidB = (*env)->GetFieldID(env, klazz, "b", "J");
6296 S3JniExceptionIsFatal("Cannot get Fts5PhraseIter.b field.");
6297 S3JniUnrefLocal(klazz);
6298 #endif
6299
6300 SJG.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
6301 s3jni_oom_fatal( SJG.mutex );
6302 SJG.hook.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
6303 s3jni_oom_fatal( SJG.hook.mutex );
6304 SJG.nph.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
6305 s3jni_oom_fatal( SJG.nph.mutex );
6306 SJG.envCache.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
6307 s3jni_oom_fatal( SJG.envCache.mutex );
6308 SJG.perDb.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
6309 s3jni_oom_fatal( SJG.perDb.mutex );
6310 SJG.autoExt.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
6311 s3jni_oom_fatal( SJG.autoExt.mutex );
6312
6313 #if S3JNI_METRICS_MUTEX
6314 SJG.metrics.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
6315 s3jni_oom_fatal( SJG.metrics.mutex );
6316 #endif
6317
6318 {
6319 /* Test whether this JVM supports direct memory access via
6320 ByteBuffer. */
6321 unsigned char buf[16] = {0};
6322 jobject bb = (*env)->NewDirectByteBuffer(env, buf, 16);
6323 if( bb ){
6324 SJG.g.byteBuffer.klazz = S3JniRefGlobal((*env)->GetObjectClass(env, bb));
6325 SJG.g.byteBuffer.midAlloc = (*env)->GetStaticMethodID(
6326 env, SJG.g.byteBuffer.klazz, "allocateDirect", "(I)Ljava/nio/ByteBuffer;"
6327 );
6328 S3JniExceptionIsFatal("Error getting ByteBuffer.allocateDirect() method.");
6329 SJG.g.byteBuffer.midLimit = (*env)->GetMethodID(
6330 env, SJG.g.byteBuffer.klazz, "limit", "()I"
6331 );
6332 S3JniExceptionIsFatal("Error getting ByteBuffer.limit() method.");
6333 S3JniUnrefLocal(bb);
6334 }else{
6335 SJG.g.byteBuffer.klazz = 0;
6336 SJG.g.byteBuffer.midAlloc = 0;
6337 }
6338 }
6339
6340 sqlite3_shutdown()
6341 /* So that it becomes legal for Java-level code to call
6342 ** sqlite3_config(). */;
6343 }