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