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