xref: /sqlite-3.40.0/ext/wasm/api/sqlite3-wasm.c (revision de033d07)
1 /*
2 ** This file requires access to sqlite3.c static state in order to
3 ** implement certain WASM-specific features, and thus directly
4 ** includes that file. Unlike the rest of sqlite3.c, this file
5 ** requires compiling with -std=c99 (or equivalent, or a later C
6 ** version) because it makes use of features not available in C89.
7 **
8 ** At its simplest, to build sqlite3.wasm either place this file
9 ** in the same directory as sqlite3.c/h before compilation or use the
10 ** -I/path flag to tell the compiler where to find both of those
11 ** files, then compile this file. For example:
12 **
13 ** emcc -o sqlite3.wasm ... -I/path/to/sqlite3-c-and-h sqlite3-wasm.c
14 */
15 
16 #define SQLITE_WASM
17 #ifdef SQLITE_WASM_ENABLE_C_TESTS
18 /*
19 ** Functions blocked off by SQLITE_WASM_TESTS are intended solely for
20 ** use in unit/regression testing. They may be safely omitted from
21 ** client-side builds.
22 */
23 #  define SQLITE_WASM_TESTS 1
24 #else
25 #  define SQLITE_WASM_TESTS 0
26 #endif
27 
28 /*
29 ** Threading and file locking: JS is single-threaded. Each Worker
30 ** thread is a separate instance of the JS engine so can never access
31 ** the same db handle as another thread, thus multi-threading support
32 ** is unnecessary in the library. Because the filesystems are virtual
33 ** and local to a given wasm runtime instance, two Workers can never
34 ** access the same db file at once, with the exception of OPFS. As of
35 ** this writing (2022-09-30), OPFS exclusively locks a file when
36 ** opening it, so two Workers can never open the same OPFS-backed file
37 ** at once. That situation will change if and when lower-level locking
38 ** features are added to OPFS (as is currently planned, per folks
39 ** involved with its development).
40 **
41 ** Summary: except for the case of future OPFS, which supports
42 ** locking, and any similar future filesystems, threading and file
43 ** locking support are unnecessary in the wasm build.
44 */
45 
46 /*
47 ** Undefine any SQLITE_... config flags which we specifically do not
48 ** want undefined. Please keep these alphabetized.
49 */
50 #undef SQLITE_OMIT_DESERIALIZE
51 #undef SQLITE_OMIT_MEMORYDB
52 
53 /*
54 ** Define any SQLITE_... config defaults we want if they aren't
55 ** overridden by the builder. Please keep these alphabetized.
56 */
57 
58 /**********************************************************************/
59 /* SQLITE_DEFAULT_... */
60 #ifndef SQLITE_DEFAULT_CACHE_SIZE
61 /*
62 ** The OPFS impls benefit tremendously from an increased cache size
63 ** when working on large workloads, e.g. speedtest1 --size 50 or
64 ** higher. On smaller workloads, e.g. speedtest1 --size 25, they
65 ** clearly benefit from having 4mb of cache, but not as much as a
66 ** larger cache benefits the larger workloads. Speed differences
67 ** between 2x and nearly 3x have been measured with ample page cache.
68 */
69 # define SQLITE_DEFAULT_CACHE_SIZE -16777216
70 #endif
71 #if 0 && !defined(SQLITE_DEFAULT_PAGE_SIZE)
72 /* TODO: experiment with this. */
73 # define SQLITE_DEFAULT_PAGE_SIZE 8192 /*4096*/
74 #endif
75 #ifndef SQLITE_DEFAULT_UNIX_VFS
76 # define SQLITE_DEFAULT_UNIX_VFS "unix-none"
77 #endif
78 
79 /**********************************************************************/
80 /* SQLITE_ENABLE_... */
81 #ifndef SQLITE_ENABLE_BYTECODE_VTAB
82 #  define SQLITE_ENABLE_BYTECODE_VTAB 1
83 #endif
84 #ifndef SQLITE_ENABLE_DBPAGE_VTAB
85 #  define SQLITE_ENABLE_DBPAGE_VTAB 1
86 #endif
87 #ifndef SQLITE_ENABLE_DBSTAT_VTAB
88 #  define SQLITE_ENABLE_DBSTAT_VTAB 1
89 #endif
90 #ifndef SQLITE_ENABLE_EXPLAIN_COMMENTS
91 #  define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
92 #endif
93 #ifndef SQLITE_ENABLE_FTS4
94 #  define SQLITE_ENABLE_FTS4 1
95 #endif
96 #ifndef SQLITE_ENABLE_OFFSET_SQL_FUNC
97 #  define SQLITE_ENABLE_OFFSET_SQL_FUNC 1
98 #endif
99 #ifndef SQLITE_ENABLE_RTREE
100 #  define SQLITE_ENABLE_RTREE 1
101 #endif
102 #ifndef SQLITE_ENABLE_STMTVTAB
103 #  define SQLITE_ENABLE_STMTVTAB 1
104 #endif
105 #ifndef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
106 #  define SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
107 #endif
108 
109 /**********************************************************************/
110 /* SQLITE_O... */
111 #ifndef SQLITE_OMIT_DEPRECATED
112 # define SQLITE_OMIT_DEPRECATED 1
113 #endif
114 #ifndef SQLITE_OMIT_LOAD_EXTENSION
115 # define SQLITE_OMIT_LOAD_EXTENSION 1
116 #endif
117 #ifndef SQLITE_OMIT_SHARED_CACHE
118 # define SQLITE_OMIT_SHARED_CACHE 1
119 #endif
120 #ifndef SQLITE_OMIT_UTF16
121 # define SQLITE_OMIT_UTF16 1
122 #endif
123 #ifndef SQLITE_OMIT_WAL
124 # define SQLITE_OMIT_WAL 1
125 #endif
126 #ifndef SQLITE_OS_KV_OPTIONAL
127 # define SQLITE_OS_KV_OPTIONAL 1
128 #endif
129 
130 /**********************************************************************/
131 /* SQLITE_T... */
132 #ifndef SQLITE_TEMP_STORE
133 # define SQLITE_TEMP_STORE 3
134 #endif
135 #ifndef SQLITE_THREADSAFE
136 # define SQLITE_THREADSAFE 0
137 #endif
138 
139 /**********************************************************************/
140 /* SQLITE_USE_... */
141 #ifndef SQLITE_USE_URI
142 #  define SQLITE_USE_URI 1
143 #endif
144 
145 #include <assert.h>
146 #include "sqlite3.c" /* yes, .c instead of .h. */
147 
148 #if defined(__EMSCRIPTEN__)
149 #  include <emscripten/console.h>
150 #endif
151 
152 /*
153 ** SQLITE_WASM_KEEP is functionally identical to EMSCRIPTEN_KEEPALIVE
154 ** but is not Emscripten-specific. It explicitly marks functions for
155 ** export into the target wasm file without requiring explicit listing
156 ** of those functions in Emscripten's -sEXPORTED_FUNCTIONS=... list
157 ** (or equivalent in other build platforms). Any function with neither
158 ** this attribute nor which is listed as an explicit export will not
159 ** be exported from the wasm file (but may still be used internally
160 ** within the wasm file).
161 **
162 ** The functions in this file (sqlite3-wasm.c) which require exporting
163 ** are marked with this flag. They may also be added to any explicit
164 ** build-time export list but need not be. All of these APIs are
165 ** intended for use only within the project's own JS/WASM code, and
166 ** not by client code, so an argument can be made for reducing their
167 ** visibility by not including them in any build-time export lists.
168 **
169 ** 2022-09-11: it's not yet _proven_ that this approach works in
170 ** non-Emscripten builds. If not, such builds will need to export
171 ** those using the --export=... wasm-ld flag (or equivalent). As of
172 ** this writing we are tied to Emscripten for various reasons
173 ** and cannot test the library with other build environments.
174 */
175 #define SQLITE_WASM_KEEP __attribute__((used,visibility("default")))
176 // See also:
177 //__attribute__((export_name("theExportedName"), used, visibility("default")))
178 
179 
180 #if 0
181 /*
182 ** An EXPERIMENT in implementing a stack-based allocator analog to
183 ** Emscripten's stackSave(), stackAlloc(), stackRestore().
184 ** Unfortunately, this cannot work together with Emscripten because
185 ** Emscripten defines its own native one and we'd stomp on each
186 ** other's memory. Other than that complication, basic tests show it
187 ** to work just fine.
188 **
189 ** Another option is to malloc() a chunk of our own and call that our
190 ** "stack".
191 */
192 SQLITE_WASM_KEEP void * sqlite3_wasm_stack_end(void){
193   extern void __heap_base
194     /* see https://stackoverflow.com/questions/10038964 */;
195   return &__heap_base;
196 }
197 SQLITE_WASM_KEEP void * sqlite3_wasm_stack_begin(void){
198   extern void __data_end;
199   return &__data_end;
200 }
201 static void * pWasmStackPtr = 0;
202 SQLITE_WASM_KEEP void * sqlite3_wasm_stack_ptr(void){
203   if(!pWasmStackPtr) pWasmStackPtr = sqlite3_wasm_stack_end();
204   return pWasmStackPtr;
205 }
206 SQLITE_WASM_KEEP void sqlite3_wasm_stack_restore(void * p){
207   pWasmStackPtr = p;
208 }
209 SQLITE_WASM_KEEP void * sqlite3_wasm_stack_alloc(int n){
210   if(n<=0) return 0;
211   n = (n + 7) & ~7 /* align to 8-byte boundary */;
212   unsigned char * const p = (unsigned char *)sqlite3_wasm_stack_ptr();
213   unsigned const char * const b = (unsigned const char *)sqlite3_wasm_stack_begin();
214   if(b + n >= p || b + n < b/*overflow*/) return 0;
215   return pWasmStackPtr = p - n;
216 }
217 #endif /* stack allocator experiment */
218 
219 /*
220 ** State for the "pseudo-stack" allocator implemented in
221 ** sqlite3_wasm_pstack_xyz(). In order to avoid colliding with
222 ** Emscripten-controled stack space, it carves out a bit of stack
223 ** memory to use for that purpose. This memory ends up in the
224 ** WASM-managed memory, such that routines which manipulate the wasm
225 ** heap can also be used to manipulate this memory.
226 **
227 ** This particular allocator is intended for small allocations such as
228 ** storage for output pointers. We cannot reasonably size it large
229 ** enough for general-purpose string conversions because some of our
230 ** tests use input files (strings) of 16MB+.
231 */
232 static unsigned char PStack_mem[512 * 8] = {0};
233 static struct {
234   unsigned const char * const pBegin;/* Start (inclusive) of memory */
235   unsigned const char * const pEnd;  /* One-after-the-end of memory */
236   unsigned char * pPos;              /* Current stack pointer */
237 } PStack = {
238   &PStack_mem[0],
239   &PStack_mem[0] + sizeof(PStack_mem),
240   &PStack_mem[0] + sizeof(PStack_mem)
241 };
242 /*
243 ** Returns the current pstack position.
244 */
245 SQLITE_WASM_KEEP void * sqlite3_wasm_pstack_ptr(void){
246   return PStack.pPos;
247 }
248 /*
249 ** Sets the pstack position poitner to p. Results are undefined if the
250 ** given value did not come from sqlite3_wasm_pstack_ptr().
251 */
252 SQLITE_WASM_KEEP void sqlite3_wasm_pstack_restore(unsigned char * p){
253   assert(p>=PStack.pBegin && p<=PStack.pEnd && p>=PStack.pPos);
254   assert(0==(p & 0x7));
255   if(p>=PStack.pBegin && p<=PStack.pEnd /*&& p>=PStack.pPos*/){
256     PStack.pPos = p;
257   }
258 }
259 /*
260 ** Allocate and zero out n bytes from the pstack. Returns a pointer to
261 ** the memory on success, 0 on error (including a negative n value). n
262 ** is always adjusted to be a multiple of 8 and returned memory is
263 ** always zeroed out before returning (because this keeps the client
264 ** JS code from having to do so, and most uses of the pstack will
265 ** call for doing so).
266 */
267 SQLITE_WASM_KEEP void * sqlite3_wasm_pstack_alloc(int n){
268   if( n<=0 ) return 0;
269   //if( n & 0x7 ) n += 8 - (n & 0x7) /* align to 8-byte boundary */;
270   n = (n + 7) & ~7 /* align to 8-byte boundary */;
271   if( PStack.pBegin + n > PStack.pPos /*not enough space left*/
272       || PStack.pBegin + n <= PStack.pBegin /*overflow*/ ) return 0;
273   memset((PStack.pPos = PStack.pPos - n), 0, (unsigned int)n);
274   return PStack.pPos;
275 }
276 /*
277 ** Return the number of bytes left which can be
278 ** sqlite3_wasm_pstack_alloc()'d.
279 */
280 SQLITE_WASM_KEEP int sqlite3_wasm_pstack_remaining(void){
281   assert(PStack.pPos >= PStack.pBegin);
282   assert(PStack.pPos <= PStack.pEnd);
283   return (int)(PStack.pPos - PStack.pBegin);
284 }
285 
286 /*
287 ** Return the total number of bytes available in the pstack, including
288 ** any space which is currently allocated. This value is a
289 ** compile-time constant.
290 */
291 SQLITE_WASM_KEEP int sqlite3_wasm_pstack_quota(void){
292   return (int)(PStack.pEnd - PStack.pBegin);
293 }
294 
295 /*
296 ** This function is NOT part of the sqlite3 public API. It is strictly
297 ** for use by the sqlite project's own JS/WASM bindings.
298 **
299 ** For purposes of certain hand-crafted C/Wasm function bindings, we
300 ** need a way of reporting errors which is consistent with the rest of
301 ** the C API, as opposed to throwing JS exceptions. To that end, this
302 ** internal-use-only function is a thin proxy around
303 ** sqlite3ErrorWithMessage(). The intent is that it only be used from
304 ** Wasm bindings such as sqlite3_prepare_v2/v3(), and definitely not
305 ** from client code.
306 **
307 ** Returns err_code.
308 */
309 SQLITE_WASM_KEEP
310 int sqlite3_wasm_db_error(sqlite3*db, int err_code, const char *zMsg){
311   if( 0!=zMsg ){
312     const int nMsg = sqlite3Strlen30(zMsg);
313     sqlite3ErrorWithMsg(db, err_code, "%.*s", nMsg, zMsg);
314   }else{
315     sqlite3ErrorWithMsg(db, err_code, NULL);
316   }
317   return err_code;
318 }
319 
320 #if SQLITE_WASM_TESTS
321 struct WasmTestStruct {
322   int v4;
323   void * ppV;
324   const char * cstr;
325   int64_t v8;
326   void (*xFunc)(void*);
327 };
328 typedef struct WasmTestStruct WasmTestStruct;
329 SQLITE_WASM_KEEP
330 void sqlite3_wasm_test_struct(WasmTestStruct * s){
331   if(s){
332     s->v4 *= 2;
333     s->v8 = s->v4 * 2;
334     s->ppV = s;
335     s->cstr = __FILE__;
336     if(s->xFunc) s->xFunc(s);
337   }
338   return;
339 }
340 #endif /* SQLITE_WASM_TESTS */
341 
342 /*
343 ** This function is NOT part of the sqlite3 public API. It is strictly
344 ** for use by the sqlite project's own JS/WASM bindings. Unlike the
345 ** rest of the sqlite3 API, this part requires C99 for snprintf() and
346 ** variadic macros.
347 **
348 ** Returns a string containing a JSON-format "enum" of C-level
349 ** constants and struct-related metadata intended to be imported into
350 ** the JS environment. The JSON is initialized the first time this
351 ** function is called and that result is reused for all future calls.
352 **
353 ** If this function returns NULL then it means that the internal
354 ** buffer is not large enough for the generated JSON and needs to be
355 ** increased. In debug builds that will trigger an assert().
356 */
357 SQLITE_WASM_KEEP
358 const char * sqlite3_wasm_enum_json(void){
359   static char aBuffer[1024 * 12] = {0} /* where the JSON goes */;
360   int n = 0, nChildren = 0, nStruct = 0
361     /* output counters for figuring out where commas go */;
362   char * zPos = &aBuffer[1] /* skip first byte for now to help protect
363                           ** against a small race condition */;
364   char const * const zEnd = &aBuffer[0] + sizeof(aBuffer) /* one-past-the-end */;
365   if(aBuffer[0]) return aBuffer;
366   /* Leave aBuffer[0] at 0 until the end to help guard against a tiny
367   ** race condition. If this is called twice concurrently, they might
368   ** end up both writing to aBuffer, but they'll both write the same
369   ** thing, so that's okay. If we set byte 0 up front then the 2nd
370   ** instance might return and use the string before the 1st instance
371   ** is done filling it. */
372 
373 /* Core output macros... */
374 #define lenCheck assert(zPos < zEnd - 128 \
375   && "sqlite3_wasm_enum_json() buffer is too small."); \
376   if( zPos >= zEnd - 128 ) return 0
377 #define outf(format,...) \
378   zPos += snprintf(zPos, ((size_t)(zEnd - zPos)), format, __VA_ARGS__); \
379   lenCheck
380 #define out(TXT) outf("%s",TXT)
381 #define CloseBrace(LEVEL) \
382   assert(LEVEL<5); memset(zPos, '}', LEVEL); zPos+=LEVEL; lenCheck
383 
384 /* Macros for emitting maps of integer- and string-type macros to
385 ** their values. */
386 #define DefGroup(KEY) n = 0; \
387   outf("%s\"" #KEY "\": {",(nChildren++ ? "," : ""));
388 #define DefInt(KEY)                                     \
389   outf("%s\"%s\": %d", (n++ ? ", " : ""), #KEY, (int)KEY)
390 #define DefStr(KEY)                                     \
391   outf("%s\"%s\": \"%s\"", (n++ ? ", " : ""), #KEY, KEY)
392 #define _DefGroup CloseBrace(1)
393 
394   /* The following groups are sorted alphabetic by group name. */
395   DefGroup(access){
396     DefInt(SQLITE_ACCESS_EXISTS);
397     DefInt(SQLITE_ACCESS_READWRITE);
398     DefInt(SQLITE_ACCESS_READ)/*docs say this is unused*/;
399   } _DefGroup;
400 
401   DefGroup(blobFinalizers) {
402     /* SQLITE_STATIC/TRANSIENT need to be handled explicitly as
403     ** integers to avoid casting-related warnings. */
404     out("\"SQLITE_STATIC\":0, \"SQLITE_TRANSIENT\":-1");
405   } _DefGroup;
406 
407   DefGroup(dataTypes) {
408     DefInt(SQLITE_INTEGER);
409     DefInt(SQLITE_FLOAT);
410     DefInt(SQLITE_TEXT);
411     DefInt(SQLITE_BLOB);
412     DefInt(SQLITE_NULL);
413   } _DefGroup;
414 
415   DefGroup(encodings) {
416     /* Noting that the wasm binding only aims to support UTF-8. */
417     DefInt(SQLITE_UTF8);
418     DefInt(SQLITE_UTF16LE);
419     DefInt(SQLITE_UTF16BE);
420     DefInt(SQLITE_UTF16);
421     /*deprecated DefInt(SQLITE_ANY); */
422     DefInt(SQLITE_UTF16_ALIGNED);
423   } _DefGroup;
424 
425   DefGroup(fcntl) {
426     DefInt(SQLITE_FCNTL_LOCKSTATE);
427     DefInt(SQLITE_FCNTL_GET_LOCKPROXYFILE);
428     DefInt(SQLITE_FCNTL_SET_LOCKPROXYFILE);
429     DefInt(SQLITE_FCNTL_LAST_ERRNO);
430     DefInt(SQLITE_FCNTL_SIZE_HINT);
431     DefInt(SQLITE_FCNTL_CHUNK_SIZE);
432     DefInt(SQLITE_FCNTL_FILE_POINTER);
433     DefInt(SQLITE_FCNTL_SYNC_OMITTED);
434     DefInt(SQLITE_FCNTL_WIN32_AV_RETRY);
435     DefInt(SQLITE_FCNTL_PERSIST_WAL);
436     DefInt(SQLITE_FCNTL_OVERWRITE);
437     DefInt(SQLITE_FCNTL_VFSNAME);
438     DefInt(SQLITE_FCNTL_POWERSAFE_OVERWRITE);
439     DefInt(SQLITE_FCNTL_PRAGMA);
440     DefInt(SQLITE_FCNTL_BUSYHANDLER);
441     DefInt(SQLITE_FCNTL_TEMPFILENAME);
442     DefInt(SQLITE_FCNTL_MMAP_SIZE);
443     DefInt(SQLITE_FCNTL_TRACE);
444     DefInt(SQLITE_FCNTL_HAS_MOVED);
445     DefInt(SQLITE_FCNTL_SYNC);
446     DefInt(SQLITE_FCNTL_COMMIT_PHASETWO);
447     DefInt(SQLITE_FCNTL_WIN32_SET_HANDLE);
448     DefInt(SQLITE_FCNTL_WAL_BLOCK);
449     DefInt(SQLITE_FCNTL_ZIPVFS);
450     DefInt(SQLITE_FCNTL_RBU);
451     DefInt(SQLITE_FCNTL_VFS_POINTER);
452     DefInt(SQLITE_FCNTL_JOURNAL_POINTER);
453     DefInt(SQLITE_FCNTL_WIN32_GET_HANDLE);
454     DefInt(SQLITE_FCNTL_PDB);
455     DefInt(SQLITE_FCNTL_BEGIN_ATOMIC_WRITE);
456     DefInt(SQLITE_FCNTL_COMMIT_ATOMIC_WRITE);
457     DefInt(SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE);
458     DefInt(SQLITE_FCNTL_LOCK_TIMEOUT);
459     DefInt(SQLITE_FCNTL_DATA_VERSION);
460     DefInt(SQLITE_FCNTL_SIZE_LIMIT);
461     DefInt(SQLITE_FCNTL_CKPT_DONE);
462     DefInt(SQLITE_FCNTL_RESERVE_BYTES);
463     DefInt(SQLITE_FCNTL_CKPT_START);
464     DefInt(SQLITE_FCNTL_EXTERNAL_READER);
465     DefInt(SQLITE_FCNTL_CKSM_FILE);
466   } _DefGroup;
467 
468   DefGroup(flock) {
469     DefInt(SQLITE_LOCK_NONE);
470     DefInt(SQLITE_LOCK_SHARED);
471     DefInt(SQLITE_LOCK_RESERVED);
472     DefInt(SQLITE_LOCK_PENDING);
473     DefInt(SQLITE_LOCK_EXCLUSIVE);
474   } _DefGroup;
475 
476   DefGroup(ioCap) {
477     DefInt(SQLITE_IOCAP_ATOMIC);
478     DefInt(SQLITE_IOCAP_ATOMIC512);
479     DefInt(SQLITE_IOCAP_ATOMIC1K);
480     DefInt(SQLITE_IOCAP_ATOMIC2K);
481     DefInt(SQLITE_IOCAP_ATOMIC4K);
482     DefInt(SQLITE_IOCAP_ATOMIC8K);
483     DefInt(SQLITE_IOCAP_ATOMIC16K);
484     DefInt(SQLITE_IOCAP_ATOMIC32K);
485     DefInt(SQLITE_IOCAP_ATOMIC64K);
486     DefInt(SQLITE_IOCAP_SAFE_APPEND);
487     DefInt(SQLITE_IOCAP_SEQUENTIAL);
488     DefInt(SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN);
489     DefInt(SQLITE_IOCAP_POWERSAFE_OVERWRITE);
490     DefInt(SQLITE_IOCAP_IMMUTABLE);
491     DefInt(SQLITE_IOCAP_BATCH_ATOMIC);
492   } _DefGroup;
493 
494   DefGroup(openFlags) {
495     /* Noting that not all of these will have any effect in
496     ** WASM-space. */
497     DefInt(SQLITE_OPEN_READONLY);
498     DefInt(SQLITE_OPEN_READWRITE);
499     DefInt(SQLITE_OPEN_CREATE);
500     DefInt(SQLITE_OPEN_URI);
501     DefInt(SQLITE_OPEN_MEMORY);
502     DefInt(SQLITE_OPEN_NOMUTEX);
503     DefInt(SQLITE_OPEN_FULLMUTEX);
504     DefInt(SQLITE_OPEN_SHAREDCACHE);
505     DefInt(SQLITE_OPEN_PRIVATECACHE);
506     DefInt(SQLITE_OPEN_EXRESCODE);
507     DefInt(SQLITE_OPEN_NOFOLLOW);
508     /* OPEN flags for use with VFSes... */
509     DefInt(SQLITE_OPEN_MAIN_DB);
510     DefInt(SQLITE_OPEN_MAIN_JOURNAL);
511     DefInt(SQLITE_OPEN_TEMP_DB);
512     DefInt(SQLITE_OPEN_TEMP_JOURNAL);
513     DefInt(SQLITE_OPEN_TRANSIENT_DB);
514     DefInt(SQLITE_OPEN_SUBJOURNAL);
515     DefInt(SQLITE_OPEN_SUPER_JOURNAL);
516     DefInt(SQLITE_OPEN_WAL);
517     DefInt(SQLITE_OPEN_DELETEONCLOSE);
518     DefInt(SQLITE_OPEN_EXCLUSIVE);
519   } _DefGroup;
520 
521   DefGroup(prepareFlags) {
522     DefInt(SQLITE_PREPARE_PERSISTENT);
523     DefInt(SQLITE_PREPARE_NORMALIZE);
524     DefInt(SQLITE_PREPARE_NO_VTAB);
525   } _DefGroup;
526 
527   DefGroup(resultCodes) {
528     DefInt(SQLITE_OK);
529     DefInt(SQLITE_ERROR);
530     DefInt(SQLITE_INTERNAL);
531     DefInt(SQLITE_PERM);
532     DefInt(SQLITE_ABORT);
533     DefInt(SQLITE_BUSY);
534     DefInt(SQLITE_LOCKED);
535     DefInt(SQLITE_NOMEM);
536     DefInt(SQLITE_READONLY);
537     DefInt(SQLITE_INTERRUPT);
538     DefInt(SQLITE_IOERR);
539     DefInt(SQLITE_CORRUPT);
540     DefInt(SQLITE_NOTFOUND);
541     DefInt(SQLITE_FULL);
542     DefInt(SQLITE_CANTOPEN);
543     DefInt(SQLITE_PROTOCOL);
544     DefInt(SQLITE_EMPTY);
545     DefInt(SQLITE_SCHEMA);
546     DefInt(SQLITE_TOOBIG);
547     DefInt(SQLITE_CONSTRAINT);
548     DefInt(SQLITE_MISMATCH);
549     DefInt(SQLITE_MISUSE);
550     DefInt(SQLITE_NOLFS);
551     DefInt(SQLITE_AUTH);
552     DefInt(SQLITE_FORMAT);
553     DefInt(SQLITE_RANGE);
554     DefInt(SQLITE_NOTADB);
555     DefInt(SQLITE_NOTICE);
556     DefInt(SQLITE_WARNING);
557     DefInt(SQLITE_ROW);
558     DefInt(SQLITE_DONE);
559     // Extended Result Codes
560     DefInt(SQLITE_ERROR_MISSING_COLLSEQ);
561     DefInt(SQLITE_ERROR_RETRY);
562     DefInt(SQLITE_ERROR_SNAPSHOT);
563     DefInt(SQLITE_IOERR_READ);
564     DefInt(SQLITE_IOERR_SHORT_READ);
565     DefInt(SQLITE_IOERR_WRITE);
566     DefInt(SQLITE_IOERR_FSYNC);
567     DefInt(SQLITE_IOERR_DIR_FSYNC);
568     DefInt(SQLITE_IOERR_TRUNCATE);
569     DefInt(SQLITE_IOERR_FSTAT);
570     DefInt(SQLITE_IOERR_UNLOCK);
571     DefInt(SQLITE_IOERR_RDLOCK);
572     DefInt(SQLITE_IOERR_DELETE);
573     DefInt(SQLITE_IOERR_BLOCKED);
574     DefInt(SQLITE_IOERR_NOMEM);
575     DefInt(SQLITE_IOERR_ACCESS);
576     DefInt(SQLITE_IOERR_CHECKRESERVEDLOCK);
577     DefInt(SQLITE_IOERR_LOCK);
578     DefInt(SQLITE_IOERR_CLOSE);
579     DefInt(SQLITE_IOERR_DIR_CLOSE);
580     DefInt(SQLITE_IOERR_SHMOPEN);
581     DefInt(SQLITE_IOERR_SHMSIZE);
582     DefInt(SQLITE_IOERR_SHMLOCK);
583     DefInt(SQLITE_IOERR_SHMMAP);
584     DefInt(SQLITE_IOERR_SEEK);
585     DefInt(SQLITE_IOERR_DELETE_NOENT);
586     DefInt(SQLITE_IOERR_MMAP);
587     DefInt(SQLITE_IOERR_GETTEMPPATH);
588     DefInt(SQLITE_IOERR_CONVPATH);
589     DefInt(SQLITE_IOERR_VNODE);
590     DefInt(SQLITE_IOERR_AUTH);
591     DefInt(SQLITE_IOERR_BEGIN_ATOMIC);
592     DefInt(SQLITE_IOERR_COMMIT_ATOMIC);
593     DefInt(SQLITE_IOERR_ROLLBACK_ATOMIC);
594     DefInt(SQLITE_IOERR_DATA);
595     DefInt(SQLITE_IOERR_CORRUPTFS);
596     DefInt(SQLITE_LOCKED_SHAREDCACHE);
597     DefInt(SQLITE_LOCKED_VTAB);
598     DefInt(SQLITE_BUSY_RECOVERY);
599     DefInt(SQLITE_BUSY_SNAPSHOT);
600     DefInt(SQLITE_BUSY_TIMEOUT);
601     DefInt(SQLITE_CANTOPEN_NOTEMPDIR);
602     DefInt(SQLITE_CANTOPEN_ISDIR);
603     DefInt(SQLITE_CANTOPEN_FULLPATH);
604     DefInt(SQLITE_CANTOPEN_CONVPATH);
605     //DefInt(SQLITE_CANTOPEN_DIRTYWAL)/*docs say not used*/;
606     DefInt(SQLITE_CANTOPEN_SYMLINK);
607     DefInt(SQLITE_CORRUPT_VTAB);
608     DefInt(SQLITE_CORRUPT_SEQUENCE);
609     DefInt(SQLITE_CORRUPT_INDEX);
610     DefInt(SQLITE_READONLY_RECOVERY);
611     DefInt(SQLITE_READONLY_CANTLOCK);
612     DefInt(SQLITE_READONLY_ROLLBACK);
613     DefInt(SQLITE_READONLY_DBMOVED);
614     DefInt(SQLITE_READONLY_CANTINIT);
615     DefInt(SQLITE_READONLY_DIRECTORY);
616     DefInt(SQLITE_ABORT_ROLLBACK);
617     DefInt(SQLITE_CONSTRAINT_CHECK);
618     DefInt(SQLITE_CONSTRAINT_COMMITHOOK);
619     DefInt(SQLITE_CONSTRAINT_FOREIGNKEY);
620     DefInt(SQLITE_CONSTRAINT_FUNCTION);
621     DefInt(SQLITE_CONSTRAINT_NOTNULL);
622     DefInt(SQLITE_CONSTRAINT_PRIMARYKEY);
623     DefInt(SQLITE_CONSTRAINT_TRIGGER);
624     DefInt(SQLITE_CONSTRAINT_UNIQUE);
625     DefInt(SQLITE_CONSTRAINT_VTAB);
626     DefInt(SQLITE_CONSTRAINT_ROWID);
627     DefInt(SQLITE_CONSTRAINT_PINNED);
628     DefInt(SQLITE_CONSTRAINT_DATATYPE);
629     DefInt(SQLITE_NOTICE_RECOVER_WAL);
630     DefInt(SQLITE_NOTICE_RECOVER_ROLLBACK);
631     DefInt(SQLITE_WARNING_AUTOINDEX);
632     DefInt(SQLITE_AUTH_USER);
633     DefInt(SQLITE_OK_LOAD_PERMANENTLY);
634     //DefInt(SQLITE_OK_SYMLINK) /* internal use only */;
635   } _DefGroup;
636 
637   DefGroup(serialize){
638     DefInt(SQLITE_SERIALIZE_NOCOPY);
639     DefInt(SQLITE_DESERIALIZE_FREEONCLOSE);
640     DefInt(SQLITE_DESERIALIZE_READONLY);
641     DefInt(SQLITE_DESERIALIZE_RESIZEABLE);
642   } _DefGroup;
643 
644   DefGroup(syncFlags) {
645     DefInt(SQLITE_SYNC_NORMAL);
646     DefInt(SQLITE_SYNC_FULL);
647     DefInt(SQLITE_SYNC_DATAONLY);
648   } _DefGroup;
649 
650   DefGroup(trace) {
651     DefInt(SQLITE_TRACE_STMT);
652     DefInt(SQLITE_TRACE_PROFILE);
653     DefInt(SQLITE_TRACE_ROW);
654     DefInt(SQLITE_TRACE_CLOSE);
655   } _DefGroup;
656 
657   DefGroup(udfFlags) {
658     DefInt(SQLITE_DETERMINISTIC);
659     DefInt(SQLITE_DIRECTONLY);
660     DefInt(SQLITE_INNOCUOUS);
661   } _DefGroup;
662 
663   DefGroup(version) {
664     DefInt(SQLITE_VERSION_NUMBER);
665     DefStr(SQLITE_VERSION);
666     DefStr(SQLITE_SOURCE_ID);
667   } _DefGroup;
668 
669 #undef DefGroup
670 #undef DefStr
671 #undef DefInt
672 #undef _DefGroup
673 
674   /*
675   ** Emit an array of "StructBinder" struct descripions, which look
676   ** like:
677   **
678   ** {
679   **   "name": "MyStruct",
680   **   "sizeof": 16,
681   **   "members": {
682   **     "member1": {"offset": 0,"sizeof": 4,"signature": "i"},
683   **     "member2": {"offset": 4,"sizeof": 4,"signature": "p"},
684   **     "member3": {"offset": 8,"sizeof": 8,"signature": "j"}
685   **   }
686   ** }
687   **
688   ** Detailed documentation for those bits are in the docs for the
689   ** Jaccwabyt JS-side component.
690   */
691 
692   /** Macros for emitting StructBinder description. */
693 #define StructBinder__(TYPE)                 \
694   n = 0;                                     \
695   outf("%s{", (nStruct++ ? ", " : ""));  \
696   out("\"name\": \"" # TYPE "\",");         \
697   outf("\"sizeof\": %d", (int)sizeof(TYPE)); \
698   out(",\"members\": {");
699 #define StructBinder_(T) StructBinder__(T)
700   /** ^^^ indirection needed to expand CurrentStruct */
701 #define StructBinder StructBinder_(CurrentStruct)
702 #define _StructBinder CloseBrace(2)
703 #define M(MEMBER,SIG)                                         \
704   outf("%s\"%s\": "                                           \
705        "{\"offset\":%d,\"sizeof\": %d,\"signature\":\"%s\"}", \
706        (n++ ? ", " : ""), #MEMBER,                            \
707        (int)offsetof(CurrentStruct,MEMBER),                   \
708        (int)sizeof(((CurrentStruct*)0)->MEMBER),              \
709        SIG)
710 
711   nStruct = 0;
712   out(", \"structs\": ["); {
713 
714 #define CurrentStruct sqlite3_vfs
715     StructBinder {
716       M(iVersion,"i");
717       M(szOsFile,"i");
718       M(mxPathname,"i");
719       M(pNext,"p");
720       M(zName,"s");
721       M(pAppData,"p");
722       M(xOpen,"i(pppip)");
723       M(xDelete,"i(ppi)");
724       M(xAccess,"i(ppip)");
725       M(xFullPathname,"i(ppip)");
726       M(xDlOpen,"p(pp)");
727       M(xDlError,"p(pip)");
728       M(xDlSym,"p()");
729       M(xDlClose,"v(pp)");
730       M(xRandomness,"i(pip)");
731       M(xSleep,"i(pi)");
732       M(xCurrentTime,"i(pp)");
733       M(xGetLastError,"i(pip)");
734       M(xCurrentTimeInt64,"i(pp)");
735       M(xSetSystemCall,"i(ppp)");
736       M(xGetSystemCall,"p(pp)");
737       M(xNextSystemCall,"p(pp)");
738     } _StructBinder;
739 #undef CurrentStruct
740 
741 #define CurrentStruct sqlite3_io_methods
742     StructBinder {
743       M(iVersion,"i");
744       M(xClose,"i(p)");
745       M(xRead,"i(ppij)");
746       M(xWrite,"i(ppij)");
747       M(xTruncate,"i(pj)");
748       M(xSync,"i(pi)");
749       M(xFileSize,"i(pp)");
750       M(xLock,"i(pi)");
751       M(xUnlock,"i(pi)");
752       M(xCheckReservedLock,"i(pp)");
753       M(xFileControl,"i(pip)");
754       M(xSectorSize,"i(p)");
755       M(xDeviceCharacteristics,"i(p)");
756       M(xShmMap,"i(piiip)");
757       M(xShmLock,"i(piii)");
758       M(xShmBarrier,"v(p)");
759       M(xShmUnmap,"i(pi)");
760       M(xFetch,"i(pjip)");
761       M(xUnfetch,"i(pjp)");
762     } _StructBinder;
763 #undef CurrentStruct
764 
765 #define CurrentStruct sqlite3_file
766     StructBinder {
767       M(pMethods,"p");
768     } _StructBinder;
769 #undef CurrentStruct
770 
771 #define CurrentStruct sqlite3_kvvfs_methods
772     StructBinder {
773       M(xRead,"i(sspi)");
774       M(xWrite,"i(sss)");
775       M(xDelete,"i(ss)");
776       M(nKeySize,"i");
777     } _StructBinder;
778 #undef CurrentStruct
779 
780 #if SQLITE_WASM_TESTS
781 #define CurrentStruct WasmTestStruct
782     StructBinder {
783       M(v4,"i");
784       M(cstr,"s");
785       M(ppV,"p");
786       M(v8,"j");
787       M(xFunc,"v(p)");
788     } _StructBinder;
789 #undef CurrentStruct
790 #endif
791 
792   } out( "]"/*structs*/);
793 
794   out("}"/*top-level object*/);
795   *zPos = 0;
796   aBuffer[0] = '{'/*end of the race-condition workaround*/;
797   return aBuffer;
798 #undef StructBinder
799 #undef StructBinder_
800 #undef StructBinder__
801 #undef M
802 #undef _StructBinder
803 #undef CloseBrace
804 #undef out
805 #undef outf
806 #undef lenCheck
807 }
808 
809 /*
810 ** This function is NOT part of the sqlite3 public API. It is strictly
811 ** for use by the sqlite project's own JS/WASM bindings.
812 **
813 ** This function invokes the xDelete method of the given VFS (or the
814 ** default VFS if pVfs is NULL), passing on the given filename. If
815 ** zName is NULL, no default VFS is found, or it has no xDelete
816 ** method, SQLITE_MISUSE is returned, else the result of the xDelete()
817 ** call is returned.
818 */
819 SQLITE_WASM_KEEP
820 int sqlite3_wasm_vfs_unlink(sqlite3_vfs *pVfs, const char * zName){
821   int rc = SQLITE_MISUSE /* ??? */;
822   if( 0==pVfs && 0!=zName ) pVfs = sqlite3_vfs_find(0);
823   if( zName && pVfs && pVfs->xDelete ){
824     rc = pVfs->xDelete(pVfs, zName, 1);
825   }
826   return rc;
827 }
828 
829 /*
830 ** This function is NOT part of the sqlite3 public API. It is strictly
831 ** for use by the sqlite project's own JS/WASM bindings.
832 **
833 ** Returns a pointer to the given DB's VFS for the given DB name,
834 ** defaulting to "main" if zDbName is 0. Returns 0 if no db with the
835 ** given name is open.
836 */
837 SQLITE_WASM_KEEP
838 sqlite3_vfs * sqlite3_wasm_db_vfs(sqlite3 *pDb, const char *zDbName){
839   sqlite3_vfs * pVfs = 0;
840   sqlite3_file_control(pDb, zDbName ? zDbName : "main",
841                        SQLITE_FCNTL_VFS_POINTER, &pVfs);
842   return pVfs;
843 }
844 
845 /*
846 ** This function is NOT part of the sqlite3 public API. It is strictly
847 ** for use by the sqlite project's own JS/WASM bindings.
848 **
849 ** This function resets the given db pointer's database as described at
850 **
851 ** https://www.sqlite.org/c3ref/c_dbconfig_defensive.html#sqlitedbconfigresetdatabase
852 **
853 ** Returns 0 on success, an SQLITE_xxx code on error. Returns
854 ** SQLITE_MISUSE if pDb is NULL.
855 */
856 SQLITE_WASM_KEEP
857 int sqlite3_wasm_db_reset(sqlite3*pDb){
858   int rc = SQLITE_MISUSE;
859   if( pDb ){
860     rc = sqlite3_db_config(pDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
861     if( 0==rc ) rc = sqlite3_exec(pDb, "VACUUM", 0, 0, 0);
862     sqlite3_db_config(pDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
863   }
864   return rc;
865 }
866 
867 /*
868 ** Uses the given database's VFS xRead to stream the db file's
869 ** contents out to the given callback. The callback gets a single
870 ** chunk of size n (its 2nd argument) on each call and must return 0
871 ** on success, non-0 on error. This function returns 0 on success,
872 ** SQLITE_NOTFOUND if no db is open, or propagates any other non-0
873 ** code from the callback. Note that this is not thread-friendly: it
874 ** expects that it will be the only thread reading the db file and
875 ** takes no measures to ensure that is the case.
876 **
877 ** This implementation appears to work fine, but
878 ** sqlite3_wasm_db_serialize() is arguably the better way to achieve
879 ** this.
880 */
881 SQLITE_WASM_KEEP
882 int sqlite3_wasm_db_export_chunked( sqlite3* pDb,
883                                     int (*xCallback)(unsigned const char *zOut, int n) ){
884   sqlite3_int64 nSize = 0;
885   sqlite3_int64 nPos = 0;
886   sqlite3_file * pFile = 0;
887   unsigned char buf[1024 * 8];
888   int nBuf = (int)sizeof(buf);
889   int rc = pDb
890     ? sqlite3_file_control(pDb, "main",
891                            SQLITE_FCNTL_FILE_POINTER, &pFile)
892     : SQLITE_NOTFOUND;
893   if( rc ) return rc;
894   rc = pFile->pMethods->xFileSize(pFile, &nSize);
895   if( rc ) return rc;
896   if(nSize % nBuf){
897     /* DB size is not an even multiple of the buffer size. Reduce
898     ** buffer size so that we do not unduly inflate the db size
899     ** with zero-padding when exporting. */
900     if(0 == nSize % 4096) nBuf = 4096;
901     else if(0 == nSize % 2048) nBuf = 2048;
902     else if(0 == nSize % 1024) nBuf = 1024;
903     else nBuf = 512;
904   }
905   for( ; 0==rc && nPos<nSize; nPos += nBuf ){
906     rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos);
907     if(SQLITE_IOERR_SHORT_READ == rc){
908       rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/;
909     }
910     if( 0==rc ) rc = xCallback(buf, nBuf);
911   }
912   return rc;
913 }
914 
915 /*
916 ** A proxy for sqlite3_serialize() which serializes the "main" schema
917 ** of pDb, placing the serialized output in pOut and nOut. nOut may be
918 ** NULL. If pDb or pOut are NULL then SQLITE_MISUSE is returned. If
919 ** allocation of the serialized copy fails, SQLITE_NOMEM is returned.
920 ** On success, 0 is returned and `*pOut` will contain a pointer to the
921 ** memory unless mFlags includes SQLITE_SERIALIZE_NOCOPY and the
922 ** database has no contiguous memory representation, in which case
923 ** `*pOut` will be NULL but 0 will be returned.
924 **
925 ** If `*pOut` is not NULL, the caller is responsible for passing it to
926 ** sqlite3_free() to free it.
927 */
928 SQLITE_WASM_KEEP
929 int sqlite3_wasm_db_serialize( sqlite3* pDb, unsigned char **pOut,
930                                sqlite3_int64 * nOut, unsigned int mFlags ){
931   unsigned char * z;
932   if( !pDb || !pOut ) return SQLITE_MISUSE;
933   if(nOut) *nOut = 0;
934   z = sqlite3_serialize(pDb, "main", nOut, mFlags);
935   if( z || (SQLITE_SERIALIZE_NOCOPY & mFlags) ){
936     *pOut = z;
937     return 0;
938   }else{
939     return SQLITE_NOMEM;
940   }
941 }
942 
943 /*
944 ** This function is NOT part of the sqlite3 public API. It is strictly
945 ** for use by the sqlite project's own JS/WASM bindings.
946 **
947 ** Allocates sqlite3KvvfsMethods.nKeySize bytes from
948 ** sqlite3_wasm_pstack_alloc() and returns 0 if that allocation fails,
949 ** else it passes that string to kvstorageMakeKey() and returns a
950 ** NUL-terminated pointer to that string. It is up to the caller to
951 ** use sqlite3_wasm_pstack_restore() to free the returned pointer.
952 */
953 SQLITE_WASM_KEEP
954 char * sqlite3_wasm_kvvfsMakeKeyOnPstack(const char *zClass,
955                                          const char *zKeyIn){
956   assert(sqlite3KvvfsMethods.nKeySize>24);
957   char *zKeyOut =
958     (char *)sqlite3_wasm_pstack_alloc(sqlite3KvvfsMethods.nKeySize);
959   if(zKeyOut){
960     kvstorageMakeKey(zClass, zKeyIn, zKeyOut);
961   }
962   return zKeyOut;
963 }
964 
965 /*
966 ** This function is NOT part of the sqlite3 public API. It is strictly
967 ** for use by the sqlite project's own JS/WASM bindings.
968 **
969 ** Returns the pointer to the singleton object which holds the kvvfs
970 ** I/O methods and associated state.
971 */
972 SQLITE_WASM_KEEP
973 sqlite3_kvvfs_methods * sqlite3_wasm_kvvfs_methods(void){
974   return &sqlite3KvvfsMethods;
975 }
976 
977 #if defined(__EMSCRIPTEN__) && defined(SQLITE_WASM_WASMFS)
978 #include <emscripten/wasmfs.h>
979 
980 /*
981 ** This function is NOT part of the sqlite3 public API. It is strictly
982 ** for use by the sqlite project's own JS/WASM bindings, specifically
983 ** only when building with Emscripten's WASMFS support.
984 **
985 ** This function should only be called if the JS side detects the
986 ** existence of the Origin-Private FileSystem (OPFS) APIs in the
987 ** client. The first time it is called, this function instantiates a
988 ** WASMFS backend impl for OPFS. On success, subsequent calls are
989 ** no-ops.
990 **
991 ** This function may be passed a "mount point" name, which must have a
992 ** leading "/" and is currently restricted to a single path component,
993 ** e.g. "/foo" is legal but "/foo/" and "/foo/bar" are not. If it is
994 ** NULL or empty, it defaults to "/opfs".
995 **
996 ** Returns 0 on success, SQLITE_NOMEM if instantiation of the backend
997 ** object fails, SQLITE_IOERR if mkdir() of the zMountPoint dir in
998 ** the virtual FS fails. In builds compiled without SQLITE_WASM_WASMFS
999 ** defined, SQLITE_NOTFOUND is returned without side effects.
1000 */
1001 SQLITE_WASM_KEEP
1002 int sqlite3_wasm_init_wasmfs(const char *zMountPoint){
1003   static backend_t pOpfs = 0;
1004   if( !zMountPoint || !*zMountPoint ) zMountPoint = "/opfs";
1005   if( !pOpfs ){
1006     pOpfs = wasmfs_create_opfs_backend();
1007     if( pOpfs ){
1008       emscripten_console_log("Created WASMFS OPFS backend.");
1009     }
1010   }
1011   /** It's not enough to instantiate the backend. We have to create a
1012       mountpoint in the VFS and attach the backend to it. */
1013   if( pOpfs && 0!=access(zMountPoint, F_OK) ){
1014     /* mkdir() simply hangs when called from fiddle app. Cause is
1015        not yet determined but the hypothesis is an init-order
1016        issue. */
1017     /* Note that this check and is not robust but it will
1018        hypothetically suffice for the transient wasm-based virtual
1019        filesystem we're currently running in. */
1020     const int rc = wasmfs_create_directory(zMountPoint, 0777, pOpfs);
1021     /*emscripten_console_logf("OPFS mkdir(%s) rc=%d", zMountPoint, rc);*/
1022     if(rc) return SQLITE_IOERR;
1023   }
1024   return pOpfs ? 0 : SQLITE_NOMEM;
1025 }
1026 #else
1027 SQLITE_WASM_KEEP
1028 int sqlite3_wasm_init_wasmfs(const char *zUnused){
1029   emscripten_console_warn("WASMFS OPFS is not compiled in.");
1030   if(zUnused){/*unused*/}
1031   return SQLITE_NOTFOUND;
1032 }
1033 #endif /* __EMSCRIPTEN__ && SQLITE_WASM_WASMFS */
1034 
1035 #if SQLITE_WASM_TESTS
1036 
1037 SQLITE_WASM_KEEP
1038 int sqlite3_wasm_test_intptr(int * p){
1039   return *p = *p * 2;
1040 }
1041 
1042 SQLITE_WASM_KEEP
1043 int64_t sqlite3_wasm_test_int64_max(void){
1044   return (int64_t)0x7fffffffffffffff;
1045 }
1046 
1047 SQLITE_WASM_KEEP
1048 int64_t sqlite3_wasm_test_int64_min(void){
1049   return ~sqlite3_wasm_test_int64_max();
1050 }
1051 
1052 SQLITE_WASM_KEEP
1053 int64_t sqlite3_wasm_test_int64_times2(int64_t x){
1054   return x * 2;
1055 }
1056 
1057 SQLITE_WASM_KEEP
1058 void sqlite3_wasm_test_int64_minmax(int64_t * min, int64_t *max){
1059   *max = sqlite3_wasm_test_int64_max();
1060   *min = sqlite3_wasm_test_int64_min();
1061   /*printf("minmax: min=%lld, max=%lld\n", *min, *max);*/
1062 }
1063 
1064 SQLITE_WASM_KEEP
1065 int64_t sqlite3_wasm_test_int64ptr(int64_t * p){
1066   /*printf("sqlite3_wasm_test_int64ptr( @%lld = 0x%llx )\n", (int64_t)p, *p);*/
1067   return *p = *p * 2;
1068 }
1069 
1070 SQLITE_WASM_KEEP
1071 void sqlite3_wasm_test_stack_overflow(int recurse){
1072   if(recurse) sqlite3_wasm_test_stack_overflow(recurse);
1073 }
1074 
1075 /* For testing the 'string-free' whwasmutil.xWrap() conversion. */
1076 SQLITE_WASM_KEEP
1077 char * sqlite3_wasm_test_str_hello(int fail){
1078   char * s = fail ? 0 : (char *)malloc(6);
1079   if(s){
1080     memcpy(s, "hello", 5);
1081     s[5] = 0;
1082   }
1083   return s;
1084 }
1085 #endif /* SQLITE_WASM_TESTS */
1086 
1087 #undef SQLITE_WASM_KEEP
1088