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