xref: /sqlite-3.40.0/src/main.c (revision 57fec54b)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** Main file for the SQLite library.  The routines in this file
13 ** implement the programmer interface to the library.  Routines in
14 ** other files are for internal use by SQLite and should not be
15 ** accessed by users of the library.
16 */
17 #include "sqliteInt.h"
18 
19 #ifdef SQLITE_ENABLE_FTS3
20 # include "fts3.h"
21 #endif
22 #ifdef SQLITE_ENABLE_FTS5
23 int sqlite3Fts5Init(sqlite3*);
24 #endif
25 #ifdef SQLITE_ENABLE_RTREE
26 # include "rtree.h"
27 #endif
28 #ifdef SQLITE_ENABLE_ICU
29 # include "sqliteicu.h"
30 #endif
31 
32 #ifndef SQLITE_AMALGAMATION
33 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
34 ** contains the text of SQLITE_VERSION macro.
35 */
36 const char sqlite3_version[] = SQLITE_VERSION;
37 #endif
38 
39 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
40 ** a pointer to the to the sqlite3_version[] string constant.
41 */
42 const char *sqlite3_libversion(void){ return sqlite3_version; }
43 
44 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
45 ** pointer to a string constant whose value is the same as the
46 ** SQLITE_SOURCE_ID C preprocessor macro.
47 */
48 const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
49 
50 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
51 ** returns an integer equal to SQLITE_VERSION_NUMBER.
52 */
53 int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
54 
55 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
56 ** zero if and only if SQLite was compiled with mutexing code omitted due to
57 ** the SQLITE_THREADSAFE compile-time option being set to 0.
58 */
59 int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
60 
61 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
62 /*
63 ** If the following function pointer is not NULL and if
64 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
65 ** I/O active are written using this function.  These messages
66 ** are intended for debugging activity only.
67 */
68 /* not-private */ void (*sqlite3IoTrace)(const char*, ...) = 0;
69 #endif
70 
71 /*
72 ** If the following global variable points to a string which is the
73 ** name of a directory, then that directory will be used to store
74 ** temporary files.
75 **
76 ** See also the "PRAGMA temp_store_directory" SQL command.
77 */
78 char *sqlite3_temp_directory = 0;
79 
80 /*
81 ** If the following global variable points to a string which is the
82 ** name of a directory, then that directory will be used to store
83 ** all database files specified with a relative pathname.
84 **
85 ** See also the "PRAGMA data_store_directory" SQL command.
86 */
87 char *sqlite3_data_directory = 0;
88 
89 /*
90 ** Initialize SQLite.
91 **
92 ** This routine must be called to initialize the memory allocation,
93 ** VFS, and mutex subsystems prior to doing any serious work with
94 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
95 ** this routine will be called automatically by key routines such as
96 ** sqlite3_open().
97 **
98 ** This routine is a no-op except on its very first call for the process,
99 ** or for the first call after a call to sqlite3_shutdown.
100 **
101 ** The first thread to call this routine runs the initialization to
102 ** completion.  If subsequent threads call this routine before the first
103 ** thread has finished the initialization process, then the subsequent
104 ** threads must block until the first thread finishes with the initialization.
105 **
106 ** The first thread might call this routine recursively.  Recursive
107 ** calls to this routine should not block, of course.  Otherwise the
108 ** initialization process would never complete.
109 **
110 ** Let X be the first thread to enter this routine.  Let Y be some other
111 ** thread.  Then while the initial invocation of this routine by X is
112 ** incomplete, it is required that:
113 **
114 **    *  Calls to this routine from Y must block until the outer-most
115 **       call by X completes.
116 **
117 **    *  Recursive calls to this routine from thread X return immediately
118 **       without blocking.
119 */
120 int sqlite3_initialize(void){
121   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
122   int rc;                                      /* Result code */
123 #ifdef SQLITE_EXTRA_INIT
124   int bRunExtraInit = 0;                       /* Extra initialization needed */
125 #endif
126 
127 #ifdef SQLITE_OMIT_WSD
128   rc = sqlite3_wsd_init(4096, 24);
129   if( rc!=SQLITE_OK ){
130     return rc;
131   }
132 #endif
133 
134   /* If SQLite is already completely initialized, then this call
135   ** to sqlite3_initialize() should be a no-op.  But the initialization
136   ** must be complete.  So isInit must not be set until the very end
137   ** of this routine.
138   */
139   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
140 
141   /* Make sure the mutex subsystem is initialized.  If unable to
142   ** initialize the mutex subsystem, return early with the error.
143   ** If the system is so sick that we are unable to allocate a mutex,
144   ** there is not much SQLite is going to be able to do.
145   **
146   ** The mutex subsystem must take care of serializing its own
147   ** initialization.
148   */
149   rc = sqlite3MutexInit();
150   if( rc ) return rc;
151 
152   /* Initialize the malloc() system and the recursive pInitMutex mutex.
153   ** This operation is protected by the STATIC_MASTER mutex.  Note that
154   ** MutexAlloc() is called for a static mutex prior to initializing the
155   ** malloc subsystem - this implies that the allocation of a static
156   ** mutex must not require support from the malloc subsystem.
157   */
158   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
159   sqlite3_mutex_enter(pMaster);
160   sqlite3GlobalConfig.isMutexInit = 1;
161   if( !sqlite3GlobalConfig.isMallocInit ){
162     rc = sqlite3MallocInit();
163   }
164   if( rc==SQLITE_OK ){
165     sqlite3GlobalConfig.isMallocInit = 1;
166     if( !sqlite3GlobalConfig.pInitMutex ){
167       sqlite3GlobalConfig.pInitMutex =
168            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
169       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
170         rc = SQLITE_NOMEM;
171       }
172     }
173   }
174   if( rc==SQLITE_OK ){
175     sqlite3GlobalConfig.nRefInitMutex++;
176   }
177   sqlite3_mutex_leave(pMaster);
178 
179   /* If rc is not SQLITE_OK at this point, then either the malloc
180   ** subsystem could not be initialized or the system failed to allocate
181   ** the pInitMutex mutex. Return an error in either case.  */
182   if( rc!=SQLITE_OK ){
183     return rc;
184   }
185 
186   /* Do the rest of the initialization under the recursive mutex so
187   ** that we will be able to handle recursive calls into
188   ** sqlite3_initialize().  The recursive calls normally come through
189   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
190   ** recursive calls might also be possible.
191   **
192   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
193   ** to the xInit method, so the xInit method need not be threadsafe.
194   **
195   ** The following mutex is what serializes access to the appdef pcache xInit
196   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
197   ** call to sqlite3PcacheInitialize().
198   */
199   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
200   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
201     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
202     sqlite3GlobalConfig.inProgress = 1;
203     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
204     sqlite3RegisterGlobalFunctions();
205     if( sqlite3GlobalConfig.isPCacheInit==0 ){
206       rc = sqlite3PcacheInitialize();
207     }
208     if( rc==SQLITE_OK ){
209       sqlite3GlobalConfig.isPCacheInit = 1;
210       rc = sqlite3OsInit();
211     }
212     if( rc==SQLITE_OK ){
213       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
214           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
215       sqlite3GlobalConfig.isInit = 1;
216 #ifdef SQLITE_EXTRA_INIT
217       bRunExtraInit = 1;
218 #endif
219     }
220     sqlite3GlobalConfig.inProgress = 0;
221   }
222   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
223 
224   /* Go back under the static mutex and clean up the recursive
225   ** mutex to prevent a resource leak.
226   */
227   sqlite3_mutex_enter(pMaster);
228   sqlite3GlobalConfig.nRefInitMutex--;
229   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
230     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
231     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
232     sqlite3GlobalConfig.pInitMutex = 0;
233   }
234   sqlite3_mutex_leave(pMaster);
235 
236   /* The following is just a sanity check to make sure SQLite has
237   ** been compiled correctly.  It is important to run this code, but
238   ** we don't want to run it too often and soak up CPU cycles for no
239   ** reason.  So we run it once during initialization.
240   */
241 #ifndef NDEBUG
242 #ifndef SQLITE_OMIT_FLOATING_POINT
243   /* This section of code's only "output" is via assert() statements. */
244   if ( rc==SQLITE_OK ){
245     u64 x = (((u64)1)<<63)-1;
246     double y;
247     assert(sizeof(x)==8);
248     assert(sizeof(x)==sizeof(y));
249     memcpy(&y, &x, 8);
250     assert( sqlite3IsNaN(y) );
251   }
252 #endif
253 #endif
254 
255   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
256   ** compile-time option.
257   */
258 #ifdef SQLITE_EXTRA_INIT
259   if( bRunExtraInit ){
260     int SQLITE_EXTRA_INIT(const char*);
261     rc = SQLITE_EXTRA_INIT(0);
262   }
263 #endif
264 
265   return rc;
266 }
267 
268 /*
269 ** Undo the effects of sqlite3_initialize().  Must not be called while
270 ** there are outstanding database connections or memory allocations or
271 ** while any part of SQLite is otherwise in use in any thread.  This
272 ** routine is not threadsafe.  But it is safe to invoke this routine
273 ** on when SQLite is already shut down.  If SQLite is already shut down
274 ** when this routine is invoked, then this routine is a harmless no-op.
275 */
276 int sqlite3_shutdown(void){
277 #ifdef SQLITE_OMIT_WSD
278   int rc = sqlite3_wsd_init(4096, 24);
279   if( rc!=SQLITE_OK ){
280     return rc;
281   }
282 #endif
283 
284   if( sqlite3GlobalConfig.isInit ){
285 #ifdef SQLITE_EXTRA_SHUTDOWN
286     void SQLITE_EXTRA_SHUTDOWN(void);
287     SQLITE_EXTRA_SHUTDOWN();
288 #endif
289     sqlite3_os_end();
290     sqlite3_reset_auto_extension();
291     sqlite3GlobalConfig.isInit = 0;
292   }
293   if( sqlite3GlobalConfig.isPCacheInit ){
294     sqlite3PcacheShutdown();
295     sqlite3GlobalConfig.isPCacheInit = 0;
296   }
297   if( sqlite3GlobalConfig.isMallocInit ){
298     sqlite3MallocEnd();
299     sqlite3GlobalConfig.isMallocInit = 0;
300 
301 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
302     /* The heap subsystem has now been shutdown and these values are supposed
303     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
304     ** which would rely on that heap subsystem; therefore, make sure these
305     ** values cannot refer to heap memory that was just invalidated when the
306     ** heap subsystem was shutdown.  This is only done if the current call to
307     ** this function resulted in the heap subsystem actually being shutdown.
308     */
309     sqlite3_data_directory = 0;
310     sqlite3_temp_directory = 0;
311 #endif
312   }
313   if( sqlite3GlobalConfig.isMutexInit ){
314     sqlite3MutexEnd();
315     sqlite3GlobalConfig.isMutexInit = 0;
316   }
317 
318   return SQLITE_OK;
319 }
320 
321 /*
322 ** This API allows applications to modify the global configuration of
323 ** the SQLite library at run-time.
324 **
325 ** This routine should only be called when there are no outstanding
326 ** database connections or memory allocations.  This routine is not
327 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
328 ** behavior.
329 */
330 int sqlite3_config(int op, ...){
331   va_list ap;
332   int rc = SQLITE_OK;
333 
334   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
335   ** the SQLite library is in use. */
336   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
337 
338   va_start(ap, op);
339   switch( op ){
340 
341     /* Mutex configuration options are only available in a threadsafe
342     ** compile.
343     */
344 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
345     case SQLITE_CONFIG_SINGLETHREAD: {
346       /* Disable all mutexing */
347       sqlite3GlobalConfig.bCoreMutex = 0;
348       sqlite3GlobalConfig.bFullMutex = 0;
349       break;
350     }
351 #endif
352 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
353     case SQLITE_CONFIG_MULTITHREAD: {
354       /* Disable mutexing of database connections */
355       /* Enable mutexing of core data structures */
356       sqlite3GlobalConfig.bCoreMutex = 1;
357       sqlite3GlobalConfig.bFullMutex = 0;
358       break;
359     }
360 #endif
361 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
362     case SQLITE_CONFIG_SERIALIZED: {
363       /* Enable all mutexing */
364       sqlite3GlobalConfig.bCoreMutex = 1;
365       sqlite3GlobalConfig.bFullMutex = 1;
366       break;
367     }
368 #endif
369 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
370     case SQLITE_CONFIG_MUTEX: {
371       /* Specify an alternative mutex implementation */
372       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
373       break;
374     }
375 #endif
376 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
377     case SQLITE_CONFIG_GETMUTEX: {
378       /* Retrieve the current mutex implementation */
379       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
380       break;
381     }
382 #endif
383 
384     case SQLITE_CONFIG_MALLOC: {
385       /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
386       ** single argument which is a pointer to an instance of the
387       ** sqlite3_mem_methods structure. The argument specifies alternative
388       ** low-level memory allocation routines to be used in place of the memory
389       ** allocation routines built into SQLite. */
390       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
391       break;
392     }
393     case SQLITE_CONFIG_GETMALLOC: {
394       /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
395       ** single argument which is a pointer to an instance of the
396       ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
397       ** filled with the currently defined memory allocation routines. */
398       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
399       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
400       break;
401     }
402     case SQLITE_CONFIG_MEMSTATUS: {
403       /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
404       ** single argument of type int, interpreted as a boolean, which enables
405       ** or disables the collection of memory allocation statistics. */
406       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
407       break;
408     }
409     case SQLITE_CONFIG_SCRATCH: {
410       /* EVIDENCE-OF: R-08404-60887 There are three arguments to
411       ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
412       ** which the scratch allocations will be drawn, the size of each scratch
413       ** allocation (sz), and the maximum number of scratch allocations (N). */
414       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
415       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
416       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
417       break;
418     }
419     case SQLITE_CONFIG_PAGECACHE: {
420       /* EVIDENCE-OF: R-31408-40510 There are three arguments to
421       ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory, the size
422       ** of each page buffer (sz), and the number of pages (N). */
423       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
424       sqlite3GlobalConfig.szPage = va_arg(ap, int);
425       sqlite3GlobalConfig.nPage = va_arg(ap, int);
426       break;
427     }
428     case SQLITE_CONFIG_PCACHE_HDRSZ: {
429       /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
430       ** a single parameter which is a pointer to an integer and writes into
431       ** that integer the number of extra bytes per page required for each page
432       ** in SQLITE_CONFIG_PAGECACHE. */
433       *va_arg(ap, int*) =
434           sqlite3HeaderSizeBtree() +
435           sqlite3HeaderSizePcache() +
436           sqlite3HeaderSizePcache1();
437       break;
438     }
439 
440     case SQLITE_CONFIG_PCACHE: {
441       /* no-op */
442       break;
443     }
444     case SQLITE_CONFIG_GETPCACHE: {
445       /* now an error */
446       rc = SQLITE_ERROR;
447       break;
448     }
449 
450     case SQLITE_CONFIG_PCACHE2: {
451       /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
452       ** single argument which is a pointer to an sqlite3_pcache_methods2
453       ** object. This object specifies the interface to a custom page cache
454       ** implementation. */
455       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
456       break;
457     }
458     case SQLITE_CONFIG_GETPCACHE2: {
459       /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
460       ** single argument which is a pointer to an sqlite3_pcache_methods2
461       ** object. SQLite copies of the current page cache implementation into
462       ** that object. */
463       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
464         sqlite3PCacheSetDefault();
465       }
466       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
467       break;
468     }
469 
470 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
471 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
472 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
473 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
474     case SQLITE_CONFIG_HEAP: {
475       /* EVIDENCE-OF: R-19854-42126 There are three arguments to
476       ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
477       ** number of bytes in the memory buffer, and the minimum allocation size. */
478       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
479       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
480       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
481 
482       if( sqlite3GlobalConfig.mnReq<1 ){
483         sqlite3GlobalConfig.mnReq = 1;
484       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
485         /* cap min request size at 2^12 */
486         sqlite3GlobalConfig.mnReq = (1<<12);
487       }
488 
489       if( sqlite3GlobalConfig.pHeap==0 ){
490         /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
491         ** is NULL, then SQLite reverts to using its default memory allocator
492         ** (the system malloc() implementation), undoing any prior invocation of
493         ** SQLITE_CONFIG_MALLOC.
494         **
495         ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
496         ** revert to its default implementation when sqlite3_initialize() is run
497         */
498         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
499       }else{
500         /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
501         ** alternative memory allocator is engaged to handle all of SQLites
502         ** memory allocation needs. */
503 #ifdef SQLITE_ENABLE_MEMSYS3
504         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
505 #endif
506 #ifdef SQLITE_ENABLE_MEMSYS5
507         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
508 #endif
509       }
510       break;
511     }
512 #endif
513 
514     case SQLITE_CONFIG_LOOKASIDE: {
515       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
516       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
517       break;
518     }
519 
520     /* Record a pointer to the logger function and its first argument.
521     ** The default is NULL.  Logging is disabled if the function pointer is
522     ** NULL.
523     */
524     case SQLITE_CONFIG_LOG: {
525       /* MSVC is picky about pulling func ptrs from va lists.
526       ** http://support.microsoft.com/kb/47961
527       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
528       */
529       typedef void(*LOGFUNC_t)(void*,int,const char*);
530       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
531       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
532       break;
533     }
534 
535     /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
536     ** can be changed at start-time using the
537     ** sqlite3_config(SQLITE_CONFIG_URI,1) or
538     ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
539     */
540     case SQLITE_CONFIG_URI: {
541       /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
542       ** argument of type int. If non-zero, then URI handling is globally
543       ** enabled. If the parameter is zero, then URI handling is globally
544       ** disabled. */
545       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
546       break;
547     }
548 
549     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
550       /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
551       ** option takes a single integer argument which is interpreted as a
552       ** boolean in order to enable or disable the use of covering indices for
553       ** full table scans in the query optimizer. */
554       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
555       break;
556     }
557 
558 #ifdef SQLITE_ENABLE_SQLLOG
559     case SQLITE_CONFIG_SQLLOG: {
560       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
561       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
562       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
563       break;
564     }
565 #endif
566 
567     case SQLITE_CONFIG_MMAP_SIZE: {
568       /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
569       ** integer (sqlite3_int64) values that are the default mmap size limit
570       ** (the default setting for PRAGMA mmap_size) and the maximum allowed
571       ** mmap size limit. */
572       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
573       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
574       /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
575       ** negative, then that argument is changed to its compile-time default.
576       **
577       ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
578       ** silently truncated if necessary so that it does not exceed the
579       ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
580       ** compile-time option.
581       */
582       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ) mxMmap = SQLITE_MAX_MMAP_SIZE;
583       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
584       if( szMmap>mxMmap) szMmap = mxMmap;
585       sqlite3GlobalConfig.mxMmap = mxMmap;
586       sqlite3GlobalConfig.szMmap = szMmap;
587       break;
588     }
589 
590 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
591     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
592       /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
593       ** unsigned integer value that specifies the maximum size of the created
594       ** heap. */
595       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
596       break;
597     }
598 #endif
599 
600     case SQLITE_CONFIG_PMASZ: {
601       sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
602       break;
603     }
604 
605     default: {
606       rc = SQLITE_ERROR;
607       break;
608     }
609   }
610   va_end(ap);
611   return rc;
612 }
613 
614 /*
615 ** Set up the lookaside buffers for a database connection.
616 ** Return SQLITE_OK on success.
617 ** If lookaside is already active, return SQLITE_BUSY.
618 **
619 ** The sz parameter is the number of bytes in each lookaside slot.
620 ** The cnt parameter is the number of slots.  If pStart is NULL the
621 ** space for the lookaside memory is obtained from sqlite3_malloc().
622 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
623 ** the lookaside memory.
624 */
625 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
626   void *pStart;
627   if( db->lookaside.nOut ){
628     return SQLITE_BUSY;
629   }
630   /* Free any existing lookaside buffer for this handle before
631   ** allocating a new one so we don't have to have space for
632   ** both at the same time.
633   */
634   if( db->lookaside.bMalloced ){
635     sqlite3_free(db->lookaside.pStart);
636   }
637   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
638   ** than a pointer to be useful.
639   */
640   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
641   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
642   if( cnt<0 ) cnt = 0;
643   if( sz==0 || cnt==0 ){
644     sz = 0;
645     pStart = 0;
646   }else if( pBuf==0 ){
647     sqlite3BeginBenignMalloc();
648     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
649     sqlite3EndBenignMalloc();
650     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
651   }else{
652     pStart = pBuf;
653   }
654   db->lookaside.pStart = pStart;
655   db->lookaside.pFree = 0;
656   db->lookaside.sz = (u16)sz;
657   if( pStart ){
658     int i;
659     LookasideSlot *p;
660     assert( sz > (int)sizeof(LookasideSlot*) );
661     p = (LookasideSlot*)pStart;
662     for(i=cnt-1; i>=0; i--){
663       p->pNext = db->lookaside.pFree;
664       db->lookaside.pFree = p;
665       p = (LookasideSlot*)&((u8*)p)[sz];
666     }
667     db->lookaside.pEnd = p;
668     db->lookaside.bEnabled = 1;
669     db->lookaside.bMalloced = pBuf==0 ?1:0;
670   }else{
671     db->lookaside.pStart = db;
672     db->lookaside.pEnd = db;
673     db->lookaside.bEnabled = 0;
674     db->lookaside.bMalloced = 0;
675   }
676   return SQLITE_OK;
677 }
678 
679 /*
680 ** Return the mutex associated with a database connection.
681 */
682 sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
683 #ifdef SQLITE_ENABLE_API_ARMOR
684   if( !sqlite3SafetyCheckOk(db) ){
685     (void)SQLITE_MISUSE_BKPT;
686     return 0;
687   }
688 #endif
689   return db->mutex;
690 }
691 
692 /*
693 ** Free up as much memory as we can from the given database
694 ** connection.
695 */
696 int sqlite3_db_release_memory(sqlite3 *db){
697   int i;
698 
699 #ifdef SQLITE_ENABLE_API_ARMOR
700   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
701 #endif
702   sqlite3_mutex_enter(db->mutex);
703   sqlite3BtreeEnterAll(db);
704   for(i=0; i<db->nDb; i++){
705     Btree *pBt = db->aDb[i].pBt;
706     if( pBt ){
707       Pager *pPager = sqlite3BtreePager(pBt);
708       sqlite3PagerShrink(pPager);
709     }
710   }
711   sqlite3BtreeLeaveAll(db);
712   sqlite3_mutex_leave(db->mutex);
713   return SQLITE_OK;
714 }
715 
716 /*
717 ** Configuration settings for an individual database connection
718 */
719 int sqlite3_db_config(sqlite3 *db, int op, ...){
720   va_list ap;
721   int rc;
722   va_start(ap, op);
723   switch( op ){
724     case SQLITE_DBCONFIG_LOOKASIDE: {
725       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
726       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
727       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
728       rc = setupLookaside(db, pBuf, sz, cnt);
729       break;
730     }
731     default: {
732       static const struct {
733         int op;      /* The opcode */
734         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
735       } aFlagOp[] = {
736         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
737         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
738       };
739       unsigned int i;
740       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
741       for(i=0; i<ArraySize(aFlagOp); i++){
742         if( aFlagOp[i].op==op ){
743           int onoff = va_arg(ap, int);
744           int *pRes = va_arg(ap, int*);
745           int oldFlags = db->flags;
746           if( onoff>0 ){
747             db->flags |= aFlagOp[i].mask;
748           }else if( onoff==0 ){
749             db->flags &= ~aFlagOp[i].mask;
750           }
751           if( oldFlags!=db->flags ){
752             sqlite3ExpirePreparedStatements(db);
753           }
754           if( pRes ){
755             *pRes = (db->flags & aFlagOp[i].mask)!=0;
756           }
757           rc = SQLITE_OK;
758           break;
759         }
760       }
761       break;
762     }
763   }
764   va_end(ap);
765   return rc;
766 }
767 
768 
769 /*
770 ** Return true if the buffer z[0..n-1] contains all spaces.
771 */
772 static int allSpaces(const char *z, int n){
773   while( n>0 && z[n-1]==' ' ){ n--; }
774   return n==0;
775 }
776 
777 /*
778 ** This is the default collating function named "BINARY" which is always
779 ** available.
780 **
781 ** If the padFlag argument is not NULL then space padding at the end
782 ** of strings is ignored.  This implements the RTRIM collation.
783 */
784 static int binCollFunc(
785   void *padFlag,
786   int nKey1, const void *pKey1,
787   int nKey2, const void *pKey2
788 ){
789   int rc, n;
790   n = nKey1<nKey2 ? nKey1 : nKey2;
791   /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
792   ** strings byte by byte using the memcmp() function from the standard C
793   ** library. */
794   rc = memcmp(pKey1, pKey2, n);
795   if( rc==0 ){
796     if( padFlag
797      && allSpaces(((char*)pKey1)+n, nKey1-n)
798      && allSpaces(((char*)pKey2)+n, nKey2-n)
799     ){
800       /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
801       ** spaces at the end of either string do not change the result. In other
802       ** words, strings will compare equal to one another as long as they
803       ** differ only in the number of spaces at the end.
804       */
805     }else{
806       rc = nKey1 - nKey2;
807     }
808   }
809   return rc;
810 }
811 
812 /*
813 ** Another built-in collating sequence: NOCASE.
814 **
815 ** This collating sequence is intended to be used for "case independent
816 ** comparison". SQLite's knowledge of upper and lower case equivalents
817 ** extends only to the 26 characters used in the English language.
818 **
819 ** At the moment there is only a UTF-8 implementation.
820 */
821 static int nocaseCollatingFunc(
822   void *NotUsed,
823   int nKey1, const void *pKey1,
824   int nKey2, const void *pKey2
825 ){
826   int r = sqlite3StrNICmp(
827       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
828   UNUSED_PARAMETER(NotUsed);
829   if( 0==r ){
830     r = nKey1-nKey2;
831   }
832   return r;
833 }
834 
835 /*
836 ** Return the ROWID of the most recent insert
837 */
838 sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
839 #ifdef SQLITE_ENABLE_API_ARMOR
840   if( !sqlite3SafetyCheckOk(db) ){
841     (void)SQLITE_MISUSE_BKPT;
842     return 0;
843   }
844 #endif
845   return db->lastRowid;
846 }
847 
848 /*
849 ** Return the number of changes in the most recent call to sqlite3_exec().
850 */
851 int sqlite3_changes(sqlite3 *db){
852 #ifdef SQLITE_ENABLE_API_ARMOR
853   if( !sqlite3SafetyCheckOk(db) ){
854     (void)SQLITE_MISUSE_BKPT;
855     return 0;
856   }
857 #endif
858   return db->nChange;
859 }
860 
861 /*
862 ** Return the number of changes since the database handle was opened.
863 */
864 int sqlite3_total_changes(sqlite3 *db){
865 #ifdef SQLITE_ENABLE_API_ARMOR
866   if( !sqlite3SafetyCheckOk(db) ){
867     (void)SQLITE_MISUSE_BKPT;
868     return 0;
869   }
870 #endif
871   return db->nTotalChange;
872 }
873 
874 /*
875 ** Close all open savepoints. This function only manipulates fields of the
876 ** database handle object, it does not close any savepoints that may be open
877 ** at the b-tree/pager level.
878 */
879 void sqlite3CloseSavepoints(sqlite3 *db){
880   while( db->pSavepoint ){
881     Savepoint *pTmp = db->pSavepoint;
882     db->pSavepoint = pTmp->pNext;
883     sqlite3DbFree(db, pTmp);
884   }
885   db->nSavepoint = 0;
886   db->nStatement = 0;
887   db->isTransactionSavepoint = 0;
888 }
889 
890 /*
891 ** Invoke the destructor function associated with FuncDef p, if any. Except,
892 ** if this is not the last copy of the function, do not invoke it. Multiple
893 ** copies of a single function are created when create_function() is called
894 ** with SQLITE_ANY as the encoding.
895 */
896 static void functionDestroy(sqlite3 *db, FuncDef *p){
897   FuncDestructor *pDestructor = p->pDestructor;
898   if( pDestructor ){
899     pDestructor->nRef--;
900     if( pDestructor->nRef==0 ){
901       pDestructor->xDestroy(pDestructor->pUserData);
902       sqlite3DbFree(db, pDestructor);
903     }
904   }
905 }
906 
907 /*
908 ** Disconnect all sqlite3_vtab objects that belong to database connection
909 ** db. This is called when db is being closed.
910 */
911 static void disconnectAllVtab(sqlite3 *db){
912 #ifndef SQLITE_OMIT_VIRTUALTABLE
913   int i;
914   sqlite3BtreeEnterAll(db);
915   for(i=0; i<db->nDb; i++){
916     Schema *pSchema = db->aDb[i].pSchema;
917     if( db->aDb[i].pSchema ){
918       HashElem *p;
919       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
920         Table *pTab = (Table *)sqliteHashData(p);
921         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
922       }
923     }
924   }
925   sqlite3VtabUnlockList(db);
926   sqlite3BtreeLeaveAll(db);
927 #else
928   UNUSED_PARAMETER(db);
929 #endif
930 }
931 
932 /*
933 ** Return TRUE if database connection db has unfinalized prepared
934 ** statements or unfinished sqlite3_backup objects.
935 */
936 static int connectionIsBusy(sqlite3 *db){
937   int j;
938   assert( sqlite3_mutex_held(db->mutex) );
939   if( db->pVdbe ) return 1;
940   for(j=0; j<db->nDb; j++){
941     Btree *pBt = db->aDb[j].pBt;
942     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
943   }
944   return 0;
945 }
946 
947 /*
948 ** Close an existing SQLite database
949 */
950 static int sqlite3Close(sqlite3 *db, int forceZombie){
951   if( !db ){
952     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
953     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
954     return SQLITE_OK;
955   }
956   if( !sqlite3SafetyCheckSickOrOk(db) ){
957     return SQLITE_MISUSE_BKPT;
958   }
959   sqlite3_mutex_enter(db->mutex);
960 
961   /* Force xDisconnect calls on all virtual tables */
962   disconnectAllVtab(db);
963 
964   /* If a transaction is open, the disconnectAllVtab() call above
965   ** will not have called the xDisconnect() method on any virtual
966   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
967   ** call will do so. We need to do this before the check for active
968   ** SQL statements below, as the v-table implementation may be storing
969   ** some prepared statements internally.
970   */
971   sqlite3VtabRollback(db);
972 
973   /* Legacy behavior (sqlite3_close() behavior) is to return
974   ** SQLITE_BUSY if the connection can not be closed immediately.
975   */
976   if( !forceZombie && connectionIsBusy(db) ){
977     sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
978        "statements or unfinished backups");
979     sqlite3_mutex_leave(db->mutex);
980     return SQLITE_BUSY;
981   }
982 
983 #ifdef SQLITE_ENABLE_SQLLOG
984   if( sqlite3GlobalConfig.xSqllog ){
985     /* Closing the handle. Fourth parameter is passed the value 2. */
986     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
987   }
988 #endif
989 
990   /* Convert the connection into a zombie and then close it.
991   */
992   db->magic = SQLITE_MAGIC_ZOMBIE;
993   sqlite3LeaveMutexAndCloseZombie(db);
994   return SQLITE_OK;
995 }
996 
997 /*
998 ** Two variations on the public interface for closing a database
999 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
1000 ** leaves the connection option if there are unfinalized prepared
1001 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
1002 ** version forces the connection to become a zombie if there are
1003 ** unclosed resources, and arranges for deallocation when the last
1004 ** prepare statement or sqlite3_backup closes.
1005 */
1006 int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
1007 int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
1008 
1009 
1010 /*
1011 ** Close the mutex on database connection db.
1012 **
1013 ** Furthermore, if database connection db is a zombie (meaning that there
1014 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
1015 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
1016 ** finished, then free all resources.
1017 */
1018 void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
1019   HashElem *i;                    /* Hash table iterator */
1020   int j;
1021 
1022   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
1023   ** or if the connection has not yet been closed by sqlite3_close_v2(),
1024   ** then just leave the mutex and return.
1025   */
1026   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
1027     sqlite3_mutex_leave(db->mutex);
1028     return;
1029   }
1030 
1031   /* If we reach this point, it means that the database connection has
1032   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
1033   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
1034   ** go ahead and free all resources.
1035   */
1036 
1037   /* If a transaction is open, roll it back. This also ensures that if
1038   ** any database schemas have been modified by an uncommitted transaction
1039   ** they are reset. And that the required b-tree mutex is held to make
1040   ** the pager rollback and schema reset an atomic operation. */
1041   sqlite3RollbackAll(db, SQLITE_OK);
1042 
1043   /* Free any outstanding Savepoint structures. */
1044   sqlite3CloseSavepoints(db);
1045 
1046   /* Close all database connections */
1047   for(j=0; j<db->nDb; j++){
1048     struct Db *pDb = &db->aDb[j];
1049     if( pDb->pBt ){
1050       sqlite3BtreeClose(pDb->pBt);
1051       pDb->pBt = 0;
1052       if( j!=1 ){
1053         pDb->pSchema = 0;
1054       }
1055     }
1056   }
1057   /* Clear the TEMP schema separately and last */
1058   if( db->aDb[1].pSchema ){
1059     sqlite3SchemaClear(db->aDb[1].pSchema);
1060   }
1061   sqlite3VtabUnlockList(db);
1062 
1063   /* Free up the array of auxiliary databases */
1064   sqlite3CollapseDatabaseArray(db);
1065   assert( db->nDb<=2 );
1066   assert( db->aDb==db->aDbStatic );
1067 
1068   /* Tell the code in notify.c that the connection no longer holds any
1069   ** locks and does not require any further unlock-notify callbacks.
1070   */
1071   sqlite3ConnectionClosed(db);
1072 
1073   for(j=0; j<ArraySize(db->aFunc.a); j++){
1074     FuncDef *pNext, *pHash, *p;
1075     for(p=db->aFunc.a[j]; p; p=pHash){
1076       pHash = p->pHash;
1077       while( p ){
1078         functionDestroy(db, p);
1079         pNext = p->pNext;
1080         sqlite3DbFree(db, p);
1081         p = pNext;
1082       }
1083     }
1084   }
1085   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
1086     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
1087     /* Invoke any destructors registered for collation sequence user data. */
1088     for(j=0; j<3; j++){
1089       if( pColl[j].xDel ){
1090         pColl[j].xDel(pColl[j].pUser);
1091       }
1092     }
1093     sqlite3DbFree(db, pColl);
1094   }
1095   sqlite3HashClear(&db->aCollSeq);
1096 #ifndef SQLITE_OMIT_VIRTUALTABLE
1097   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
1098     Module *pMod = (Module *)sqliteHashData(i);
1099     if( pMod->xDestroy ){
1100       pMod->xDestroy(pMod->pAux);
1101     }
1102     sqlite3DbFree(db, pMod);
1103   }
1104   sqlite3HashClear(&db->aModule);
1105 #endif
1106 
1107   sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
1108   sqlite3ValueFree(db->pErr);
1109   sqlite3CloseExtensions(db);
1110 #if SQLITE_USER_AUTHENTICATION
1111   sqlite3_free(db->auth.zAuthUser);
1112   sqlite3_free(db->auth.zAuthPW);
1113 #endif
1114 
1115   db->magic = SQLITE_MAGIC_ERROR;
1116 
1117   /* The temp-database schema is allocated differently from the other schema
1118   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
1119   ** So it needs to be freed here. Todo: Why not roll the temp schema into
1120   ** the same sqliteMalloc() as the one that allocates the database
1121   ** structure?
1122   */
1123   sqlite3DbFree(db, db->aDb[1].pSchema);
1124   sqlite3_mutex_leave(db->mutex);
1125   db->magic = SQLITE_MAGIC_CLOSED;
1126   sqlite3_mutex_free(db->mutex);
1127   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
1128   if( db->lookaside.bMalloced ){
1129     sqlite3_free(db->lookaside.pStart);
1130   }
1131   sqlite3_free(db);
1132 }
1133 
1134 /*
1135 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
1136 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
1137 ** breaker") and made to return tripCode if there are any further
1138 ** attempts to use that cursor.  Read cursors remain open and valid
1139 ** but are "saved" in case the table pages are moved around.
1140 */
1141 void sqlite3RollbackAll(sqlite3 *db, int tripCode){
1142   int i;
1143   int inTrans = 0;
1144   int schemaChange;
1145   assert( sqlite3_mutex_held(db->mutex) );
1146   sqlite3BeginBenignMalloc();
1147 
1148   /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
1149   ** This is important in case the transaction being rolled back has
1150   ** modified the database schema. If the b-tree mutexes are not taken
1151   ** here, then another shared-cache connection might sneak in between
1152   ** the database rollback and schema reset, which can cause false
1153   ** corruption reports in some cases.  */
1154   sqlite3BtreeEnterAll(db);
1155   schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
1156 
1157   for(i=0; i<db->nDb; i++){
1158     Btree *p = db->aDb[i].pBt;
1159     if( p ){
1160       if( sqlite3BtreeIsInTrans(p) ){
1161         inTrans = 1;
1162       }
1163       sqlite3BtreeRollback(p, tripCode, !schemaChange);
1164     }
1165   }
1166   sqlite3VtabRollback(db);
1167   sqlite3EndBenignMalloc();
1168 
1169   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
1170     sqlite3ExpirePreparedStatements(db);
1171     sqlite3ResetAllSchemasOfConnection(db);
1172   }
1173   sqlite3BtreeLeaveAll(db);
1174 
1175   /* Any deferred constraint violations have now been resolved. */
1176   db->nDeferredCons = 0;
1177   db->nDeferredImmCons = 0;
1178   db->flags &= ~SQLITE_DeferFKs;
1179 
1180   /* If one has been configured, invoke the rollback-hook callback */
1181   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
1182     db->xRollbackCallback(db->pRollbackArg);
1183   }
1184 }
1185 
1186 /*
1187 ** Return a static string containing the name corresponding to the error code
1188 ** specified in the argument.
1189 */
1190 #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
1191 const char *sqlite3ErrName(int rc){
1192   const char *zName = 0;
1193   int i, origRc = rc;
1194   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
1195     switch( rc ){
1196       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
1197       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
1198       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
1199       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
1200       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
1201       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
1202       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
1203       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
1204       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
1205       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
1206       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
1207       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
1208       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
1209       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
1210       case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
1211       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
1212       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
1213       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
1214       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
1215       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
1216       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
1217       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
1218       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
1219       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
1220       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
1221       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
1222       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
1223       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
1224       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
1225       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
1226       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
1227       case SQLITE_IOERR_CHECKRESERVEDLOCK:
1228                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
1229       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
1230       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
1231       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
1232       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
1233       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
1234       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
1235       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
1236       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
1237       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
1238       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
1239       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
1240       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
1241       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
1242       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
1243       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
1244       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
1245       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
1246       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
1247       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
1248       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
1249       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
1250       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
1251       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
1252       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
1253       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
1254       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
1255       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
1256       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
1257       case SQLITE_CONSTRAINT_FOREIGNKEY:
1258                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
1259       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
1260       case SQLITE_CONSTRAINT_PRIMARYKEY:
1261                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
1262       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
1263       case SQLITE_CONSTRAINT_COMMITHOOK:
1264                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
1265       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
1266       case SQLITE_CONSTRAINT_FUNCTION:
1267                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
1268       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
1269       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
1270       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
1271       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
1272       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
1273       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
1274       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
1275       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
1276       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
1277       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
1278       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
1279       case SQLITE_NOTICE_RECOVER_ROLLBACK:
1280                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
1281       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
1282       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
1283       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
1284     }
1285   }
1286   if( zName==0 ){
1287     static char zBuf[50];
1288     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
1289     zName = zBuf;
1290   }
1291   return zName;
1292 }
1293 #endif
1294 
1295 /*
1296 ** Return a static string that describes the kind of error specified in the
1297 ** argument.
1298 */
1299 const char *sqlite3ErrStr(int rc){
1300   static const char* const aMsg[] = {
1301     /* SQLITE_OK          */ "not an error",
1302     /* SQLITE_ERROR       */ "SQL logic error or missing database",
1303     /* SQLITE_INTERNAL    */ 0,
1304     /* SQLITE_PERM        */ "access permission denied",
1305     /* SQLITE_ABORT       */ "callback requested query abort",
1306     /* SQLITE_BUSY        */ "database is locked",
1307     /* SQLITE_LOCKED      */ "database table is locked",
1308     /* SQLITE_NOMEM       */ "out of memory",
1309     /* SQLITE_READONLY    */ "attempt to write a readonly database",
1310     /* SQLITE_INTERRUPT   */ "interrupted",
1311     /* SQLITE_IOERR       */ "disk I/O error",
1312     /* SQLITE_CORRUPT     */ "database disk image is malformed",
1313     /* SQLITE_NOTFOUND    */ "unknown operation",
1314     /* SQLITE_FULL        */ "database or disk is full",
1315     /* SQLITE_CANTOPEN    */ "unable to open database file",
1316     /* SQLITE_PROTOCOL    */ "locking protocol",
1317     /* SQLITE_EMPTY       */ "table contains no data",
1318     /* SQLITE_SCHEMA      */ "database schema has changed",
1319     /* SQLITE_TOOBIG      */ "string or blob too big",
1320     /* SQLITE_CONSTRAINT  */ "constraint failed",
1321     /* SQLITE_MISMATCH    */ "datatype mismatch",
1322     /* SQLITE_MISUSE      */ "library routine called out of sequence",
1323     /* SQLITE_NOLFS       */ "large file support is disabled",
1324     /* SQLITE_AUTH        */ "authorization denied",
1325     /* SQLITE_FORMAT      */ "auxiliary database format error",
1326     /* SQLITE_RANGE       */ "bind or column index out of range",
1327     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
1328   };
1329   const char *zErr = "unknown error";
1330   switch( rc ){
1331     case SQLITE_ABORT_ROLLBACK: {
1332       zErr = "abort due to ROLLBACK";
1333       break;
1334     }
1335     default: {
1336       rc &= 0xff;
1337       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
1338         zErr = aMsg[rc];
1339       }
1340       break;
1341     }
1342   }
1343   return zErr;
1344 }
1345 
1346 /*
1347 ** This routine implements a busy callback that sleeps and tries
1348 ** again until a timeout value is reached.  The timeout value is
1349 ** an integer number of milliseconds passed in as the first
1350 ** argument.
1351 */
1352 static int sqliteDefaultBusyCallback(
1353  void *ptr,               /* Database connection */
1354  int count                /* Number of times table has been busy */
1355 ){
1356 #if SQLITE_OS_WIN || HAVE_USLEEP
1357   static const u8 delays[] =
1358      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
1359   static const u8 totals[] =
1360      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
1361 # define NDELAY ArraySize(delays)
1362   sqlite3 *db = (sqlite3 *)ptr;
1363   int timeout = db->busyTimeout;
1364   int delay, prior;
1365 
1366   assert( count>=0 );
1367   if( count < NDELAY ){
1368     delay = delays[count];
1369     prior = totals[count];
1370   }else{
1371     delay = delays[NDELAY-1];
1372     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
1373   }
1374   if( prior + delay > timeout ){
1375     delay = timeout - prior;
1376     if( delay<=0 ) return 0;
1377   }
1378   sqlite3OsSleep(db->pVfs, delay*1000);
1379   return 1;
1380 #else
1381   sqlite3 *db = (sqlite3 *)ptr;
1382   int timeout = ((sqlite3 *)ptr)->busyTimeout;
1383   if( (count+1)*1000 > timeout ){
1384     return 0;
1385   }
1386   sqlite3OsSleep(db->pVfs, 1000000);
1387   return 1;
1388 #endif
1389 }
1390 
1391 /*
1392 ** Invoke the given busy handler.
1393 **
1394 ** This routine is called when an operation failed with a lock.
1395 ** If this routine returns non-zero, the lock is retried.  If it
1396 ** returns 0, the operation aborts with an SQLITE_BUSY error.
1397 */
1398 int sqlite3InvokeBusyHandler(BusyHandler *p){
1399   int rc;
1400   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
1401   rc = p->xFunc(p->pArg, p->nBusy);
1402   if( rc==0 ){
1403     p->nBusy = -1;
1404   }else{
1405     p->nBusy++;
1406   }
1407   return rc;
1408 }
1409 
1410 /*
1411 ** This routine sets the busy callback for an Sqlite database to the
1412 ** given callback function with the given argument.
1413 */
1414 int sqlite3_busy_handler(
1415   sqlite3 *db,
1416   int (*xBusy)(void*,int),
1417   void *pArg
1418 ){
1419 #ifdef SQLITE_ENABLE_API_ARMOR
1420   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE;
1421 #endif
1422   sqlite3_mutex_enter(db->mutex);
1423   db->busyHandler.xFunc = xBusy;
1424   db->busyHandler.pArg = pArg;
1425   db->busyHandler.nBusy = 0;
1426   db->busyTimeout = 0;
1427   sqlite3_mutex_leave(db->mutex);
1428   return SQLITE_OK;
1429 }
1430 
1431 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
1432 /*
1433 ** This routine sets the progress callback for an Sqlite database to the
1434 ** given callback function with the given argument. The progress callback will
1435 ** be invoked every nOps opcodes.
1436 */
1437 void sqlite3_progress_handler(
1438   sqlite3 *db,
1439   int nOps,
1440   int (*xProgress)(void*),
1441   void *pArg
1442 ){
1443 #ifdef SQLITE_ENABLE_API_ARMOR
1444   if( !sqlite3SafetyCheckOk(db) ){
1445     (void)SQLITE_MISUSE_BKPT;
1446     return;
1447   }
1448 #endif
1449   sqlite3_mutex_enter(db->mutex);
1450   if( nOps>0 ){
1451     db->xProgress = xProgress;
1452     db->nProgressOps = (unsigned)nOps;
1453     db->pProgressArg = pArg;
1454   }else{
1455     db->xProgress = 0;
1456     db->nProgressOps = 0;
1457     db->pProgressArg = 0;
1458   }
1459   sqlite3_mutex_leave(db->mutex);
1460 }
1461 #endif
1462 
1463 
1464 /*
1465 ** This routine installs a default busy handler that waits for the
1466 ** specified number of milliseconds before returning 0.
1467 */
1468 int sqlite3_busy_timeout(sqlite3 *db, int ms){
1469 #ifdef SQLITE_ENABLE_API_ARMOR
1470   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1471 #endif
1472   if( ms>0 ){
1473     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
1474     db->busyTimeout = ms;
1475   }else{
1476     sqlite3_busy_handler(db, 0, 0);
1477   }
1478   return SQLITE_OK;
1479 }
1480 
1481 /*
1482 ** Cause any pending operation to stop at its earliest opportunity.
1483 */
1484 void sqlite3_interrupt(sqlite3 *db){
1485 #ifdef SQLITE_ENABLE_API_ARMOR
1486   if( !sqlite3SafetyCheckOk(db) ){
1487     (void)SQLITE_MISUSE_BKPT;
1488     return;
1489   }
1490 #endif
1491   db->u1.isInterrupted = 1;
1492 }
1493 
1494 
1495 /*
1496 ** This function is exactly the same as sqlite3_create_function(), except
1497 ** that it is designed to be called by internal code. The difference is
1498 ** that if a malloc() fails in sqlite3_create_function(), an error code
1499 ** is returned and the mallocFailed flag cleared.
1500 */
1501 int sqlite3CreateFunc(
1502   sqlite3 *db,
1503   const char *zFunctionName,
1504   int nArg,
1505   int enc,
1506   void *pUserData,
1507   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1508   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1509   void (*xFinal)(sqlite3_context*),
1510   FuncDestructor *pDestructor
1511 ){
1512   FuncDef *p;
1513   int nName;
1514   int extraFlags;
1515 
1516   assert( sqlite3_mutex_held(db->mutex) );
1517   if( zFunctionName==0 ||
1518       (xFunc && (xFinal || xStep)) ||
1519       (!xFunc && (xFinal && !xStep)) ||
1520       (!xFunc && (!xFinal && xStep)) ||
1521       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
1522       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
1523     return SQLITE_MISUSE_BKPT;
1524   }
1525 
1526   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
1527   extraFlags = enc &  SQLITE_DETERMINISTIC;
1528   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
1529 
1530 #ifndef SQLITE_OMIT_UTF16
1531   /* If SQLITE_UTF16 is specified as the encoding type, transform this
1532   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
1533   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
1534   **
1535   ** If SQLITE_ANY is specified, add three versions of the function
1536   ** to the hash table.
1537   */
1538   if( enc==SQLITE_UTF16 ){
1539     enc = SQLITE_UTF16NATIVE;
1540   }else if( enc==SQLITE_ANY ){
1541     int rc;
1542     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
1543          pUserData, xFunc, xStep, xFinal, pDestructor);
1544     if( rc==SQLITE_OK ){
1545       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
1546           pUserData, xFunc, xStep, xFinal, pDestructor);
1547     }
1548     if( rc!=SQLITE_OK ){
1549       return rc;
1550     }
1551     enc = SQLITE_UTF16BE;
1552   }
1553 #else
1554   enc = SQLITE_UTF8;
1555 #endif
1556 
1557   /* Check if an existing function is being overridden or deleted. If so,
1558   ** and there are active VMs, then return SQLITE_BUSY. If a function
1559   ** is being overridden/deleted but there are no active VMs, allow the
1560   ** operation to continue but invalidate all precompiled statements.
1561   */
1562   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
1563   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
1564     if( db->nVdbeActive ){
1565       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
1566         "unable to delete/modify user-function due to active statements");
1567       assert( !db->mallocFailed );
1568       return SQLITE_BUSY;
1569     }else{
1570       sqlite3ExpirePreparedStatements(db);
1571     }
1572   }
1573 
1574   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
1575   assert(p || db->mallocFailed);
1576   if( !p ){
1577     return SQLITE_NOMEM;
1578   }
1579 
1580   /* If an older version of the function with a configured destructor is
1581   ** being replaced invoke the destructor function here. */
1582   functionDestroy(db, p);
1583 
1584   if( pDestructor ){
1585     pDestructor->nRef++;
1586   }
1587   p->pDestructor = pDestructor;
1588   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
1589   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
1590   p->xFunc = xFunc;
1591   p->xStep = xStep;
1592   p->xFinalize = xFinal;
1593   p->pUserData = pUserData;
1594   p->nArg = (u16)nArg;
1595   return SQLITE_OK;
1596 }
1597 
1598 /*
1599 ** Create new user functions.
1600 */
1601 int sqlite3_create_function(
1602   sqlite3 *db,
1603   const char *zFunc,
1604   int nArg,
1605   int enc,
1606   void *p,
1607   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1608   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1609   void (*xFinal)(sqlite3_context*)
1610 ){
1611   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
1612                                     xFinal, 0);
1613 }
1614 
1615 int sqlite3_create_function_v2(
1616   sqlite3 *db,
1617   const char *zFunc,
1618   int nArg,
1619   int enc,
1620   void *p,
1621   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
1622   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
1623   void (*xFinal)(sqlite3_context*),
1624   void (*xDestroy)(void *)
1625 ){
1626   int rc = SQLITE_ERROR;
1627   FuncDestructor *pArg = 0;
1628 
1629 #ifdef SQLITE_ENABLE_API_ARMOR
1630   if( !sqlite3SafetyCheckOk(db) ){
1631     return SQLITE_MISUSE_BKPT;
1632   }
1633 #endif
1634   sqlite3_mutex_enter(db->mutex);
1635   if( xDestroy ){
1636     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
1637     if( !pArg ){
1638       xDestroy(p);
1639       goto out;
1640     }
1641     pArg->xDestroy = xDestroy;
1642     pArg->pUserData = p;
1643   }
1644   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
1645   if( pArg && pArg->nRef==0 ){
1646     assert( rc!=SQLITE_OK );
1647     xDestroy(p);
1648     sqlite3DbFree(db, pArg);
1649   }
1650 
1651  out:
1652   rc = sqlite3ApiExit(db, rc);
1653   sqlite3_mutex_leave(db->mutex);
1654   return rc;
1655 }
1656 
1657 #ifndef SQLITE_OMIT_UTF16
1658 int sqlite3_create_function16(
1659   sqlite3 *db,
1660   const void *zFunctionName,
1661   int nArg,
1662   int eTextRep,
1663   void *p,
1664   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
1665   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
1666   void (*xFinal)(sqlite3_context*)
1667 ){
1668   int rc;
1669   char *zFunc8;
1670 
1671 #ifdef SQLITE_ENABLE_API_ARMOR
1672   if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
1673 #endif
1674   sqlite3_mutex_enter(db->mutex);
1675   assert( !db->mallocFailed );
1676   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
1677   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
1678   sqlite3DbFree(db, zFunc8);
1679   rc = sqlite3ApiExit(db, rc);
1680   sqlite3_mutex_leave(db->mutex);
1681   return rc;
1682 }
1683 #endif
1684 
1685 
1686 /*
1687 ** Declare that a function has been overloaded by a virtual table.
1688 **
1689 ** If the function already exists as a regular global function, then
1690 ** this routine is a no-op.  If the function does not exist, then create
1691 ** a new one that always throws a run-time error.
1692 **
1693 ** When virtual tables intend to provide an overloaded function, they
1694 ** should call this routine to make sure the global function exists.
1695 ** A global function must exist in order for name resolution to work
1696 ** properly.
1697 */
1698 int sqlite3_overload_function(
1699   sqlite3 *db,
1700   const char *zName,
1701   int nArg
1702 ){
1703   int nName = sqlite3Strlen30(zName);
1704   int rc = SQLITE_OK;
1705 
1706 #ifdef SQLITE_ENABLE_API_ARMOR
1707   if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
1708     return SQLITE_MISUSE_BKPT;
1709   }
1710 #endif
1711   sqlite3_mutex_enter(db->mutex);
1712   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
1713     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
1714                            0, sqlite3InvalidFunction, 0, 0, 0);
1715   }
1716   rc = sqlite3ApiExit(db, rc);
1717   sqlite3_mutex_leave(db->mutex);
1718   return rc;
1719 }
1720 
1721 #ifndef SQLITE_OMIT_TRACE
1722 /*
1723 ** Register a trace function.  The pArg from the previously registered trace
1724 ** is returned.
1725 **
1726 ** A NULL trace function means that no tracing is executes.  A non-NULL
1727 ** trace is a pointer to a function that is invoked at the start of each
1728 ** SQL statement.
1729 */
1730 void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
1731   void *pOld;
1732 
1733 #ifdef SQLITE_ENABLE_API_ARMOR
1734   if( !sqlite3SafetyCheckOk(db) ){
1735     (void)SQLITE_MISUSE_BKPT;
1736     return 0;
1737   }
1738 #endif
1739   sqlite3_mutex_enter(db->mutex);
1740   pOld = db->pTraceArg;
1741   db->xTrace = xTrace;
1742   db->pTraceArg = pArg;
1743   sqlite3_mutex_leave(db->mutex);
1744   return pOld;
1745 }
1746 /*
1747 ** Register a profile function.  The pArg from the previously registered
1748 ** profile function is returned.
1749 **
1750 ** A NULL profile function means that no profiling is executes.  A non-NULL
1751 ** profile is a pointer to a function that is invoked at the conclusion of
1752 ** each SQL statement that is run.
1753 */
1754 void *sqlite3_profile(
1755   sqlite3 *db,
1756   void (*xProfile)(void*,const char*,sqlite_uint64),
1757   void *pArg
1758 ){
1759   void *pOld;
1760 
1761 #ifdef SQLITE_ENABLE_API_ARMOR
1762   if( !sqlite3SafetyCheckOk(db) ){
1763     (void)SQLITE_MISUSE_BKPT;
1764     return 0;
1765   }
1766 #endif
1767   sqlite3_mutex_enter(db->mutex);
1768   pOld = db->pProfileArg;
1769   db->xProfile = xProfile;
1770   db->pProfileArg = pArg;
1771   sqlite3_mutex_leave(db->mutex);
1772   return pOld;
1773 }
1774 #endif /* SQLITE_OMIT_TRACE */
1775 
1776 /*
1777 ** Register a function to be invoked when a transaction commits.
1778 ** If the invoked function returns non-zero, then the commit becomes a
1779 ** rollback.
1780 */
1781 void *sqlite3_commit_hook(
1782   sqlite3 *db,              /* Attach the hook to this database */
1783   int (*xCallback)(void*),  /* Function to invoke on each commit */
1784   void *pArg                /* Argument to the function */
1785 ){
1786   void *pOld;
1787 
1788 #ifdef SQLITE_ENABLE_API_ARMOR
1789   if( !sqlite3SafetyCheckOk(db) ){
1790     (void)SQLITE_MISUSE_BKPT;
1791     return 0;
1792   }
1793 #endif
1794   sqlite3_mutex_enter(db->mutex);
1795   pOld = db->pCommitArg;
1796   db->xCommitCallback = xCallback;
1797   db->pCommitArg = pArg;
1798   sqlite3_mutex_leave(db->mutex);
1799   return pOld;
1800 }
1801 
1802 /*
1803 ** Register a callback to be invoked each time a row is updated,
1804 ** inserted or deleted using this database connection.
1805 */
1806 void *sqlite3_update_hook(
1807   sqlite3 *db,              /* Attach the hook to this database */
1808   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
1809   void *pArg                /* Argument to the function */
1810 ){
1811   void *pRet;
1812 
1813 #ifdef SQLITE_ENABLE_API_ARMOR
1814   if( !sqlite3SafetyCheckOk(db) ){
1815     (void)SQLITE_MISUSE_BKPT;
1816     return 0;
1817   }
1818 #endif
1819   sqlite3_mutex_enter(db->mutex);
1820   pRet = db->pUpdateArg;
1821   db->xUpdateCallback = xCallback;
1822   db->pUpdateArg = pArg;
1823   sqlite3_mutex_leave(db->mutex);
1824   return pRet;
1825 }
1826 
1827 /*
1828 ** Register a callback to be invoked each time a transaction is rolled
1829 ** back by this database connection.
1830 */
1831 void *sqlite3_rollback_hook(
1832   sqlite3 *db,              /* Attach the hook to this database */
1833   void (*xCallback)(void*), /* Callback function */
1834   void *pArg                /* Argument to the function */
1835 ){
1836   void *pRet;
1837 
1838 #ifdef SQLITE_ENABLE_API_ARMOR
1839   if( !sqlite3SafetyCheckOk(db) ){
1840     (void)SQLITE_MISUSE_BKPT;
1841     return 0;
1842   }
1843 #endif
1844   sqlite3_mutex_enter(db->mutex);
1845   pRet = db->pRollbackArg;
1846   db->xRollbackCallback = xCallback;
1847   db->pRollbackArg = pArg;
1848   sqlite3_mutex_leave(db->mutex);
1849   return pRet;
1850 }
1851 
1852 #ifndef SQLITE_OMIT_WAL
1853 /*
1854 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
1855 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
1856 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
1857 ** wal_autocheckpoint()).
1858 */
1859 int sqlite3WalDefaultHook(
1860   void *pClientData,     /* Argument */
1861   sqlite3 *db,           /* Connection */
1862   const char *zDb,       /* Database */
1863   int nFrame             /* Size of WAL */
1864 ){
1865   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
1866     sqlite3BeginBenignMalloc();
1867     sqlite3_wal_checkpoint(db, zDb);
1868     sqlite3EndBenignMalloc();
1869   }
1870   return SQLITE_OK;
1871 }
1872 #endif /* SQLITE_OMIT_WAL */
1873 
1874 /*
1875 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
1876 ** a database after committing a transaction if there are nFrame or
1877 ** more frames in the log file. Passing zero or a negative value as the
1878 ** nFrame parameter disables automatic checkpoints entirely.
1879 **
1880 ** The callback registered by this function replaces any existing callback
1881 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
1882 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
1883 ** configured by this function.
1884 */
1885 int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
1886 #ifdef SQLITE_OMIT_WAL
1887   UNUSED_PARAMETER(db);
1888   UNUSED_PARAMETER(nFrame);
1889 #else
1890 #ifdef SQLITE_ENABLE_API_ARMOR
1891   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1892 #endif
1893   if( nFrame>0 ){
1894     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
1895   }else{
1896     sqlite3_wal_hook(db, 0, 0);
1897   }
1898 #endif
1899   return SQLITE_OK;
1900 }
1901 
1902 /*
1903 ** Register a callback to be invoked each time a transaction is written
1904 ** into the write-ahead-log by this database connection.
1905 */
1906 void *sqlite3_wal_hook(
1907   sqlite3 *db,                    /* Attach the hook to this db handle */
1908   int(*xCallback)(void *, sqlite3*, const char*, int),
1909   void *pArg                      /* First argument passed to xCallback() */
1910 ){
1911 #ifndef SQLITE_OMIT_WAL
1912   void *pRet;
1913 #ifdef SQLITE_ENABLE_API_ARMOR
1914   if( !sqlite3SafetyCheckOk(db) ){
1915     (void)SQLITE_MISUSE_BKPT;
1916     return 0;
1917   }
1918 #endif
1919   sqlite3_mutex_enter(db->mutex);
1920   pRet = db->pWalArg;
1921   db->xWalCallback = xCallback;
1922   db->pWalArg = pArg;
1923   sqlite3_mutex_leave(db->mutex);
1924   return pRet;
1925 #else
1926   return 0;
1927 #endif
1928 }
1929 
1930 /*
1931 ** Checkpoint database zDb.
1932 */
1933 int sqlite3_wal_checkpoint_v2(
1934   sqlite3 *db,                    /* Database handle */
1935   const char *zDb,                /* Name of attached database (or NULL) */
1936   int eMode,                      /* SQLITE_CHECKPOINT_* value */
1937   int *pnLog,                     /* OUT: Size of WAL log in frames */
1938   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
1939 ){
1940 #ifdef SQLITE_OMIT_WAL
1941   return SQLITE_OK;
1942 #else
1943   int rc;                         /* Return code */
1944   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
1945 
1946 #ifdef SQLITE_ENABLE_API_ARMOR
1947   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
1948 #endif
1949 
1950   /* Initialize the output variables to -1 in case an error occurs. */
1951   if( pnLog ) *pnLog = -1;
1952   if( pnCkpt ) *pnCkpt = -1;
1953 
1954   assert( SQLITE_CHECKPOINT_PASSIVE==0 );
1955   assert( SQLITE_CHECKPOINT_FULL==1 );
1956   assert( SQLITE_CHECKPOINT_RESTART==2 );
1957   assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
1958   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
1959     /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
1960     ** mode: */
1961     return SQLITE_MISUSE;
1962   }
1963 
1964   sqlite3_mutex_enter(db->mutex);
1965   if( zDb && zDb[0] ){
1966     iDb = sqlite3FindDbName(db, zDb);
1967   }
1968   if( iDb<0 ){
1969     rc = SQLITE_ERROR;
1970     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
1971   }else{
1972     db->busyHandler.nBusy = 0;
1973     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
1974     sqlite3Error(db, rc);
1975   }
1976   rc = sqlite3ApiExit(db, rc);
1977   sqlite3_mutex_leave(db->mutex);
1978   return rc;
1979 #endif
1980 }
1981 
1982 
1983 /*
1984 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
1985 ** to contains a zero-length string, all attached databases are
1986 ** checkpointed.
1987 */
1988 int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
1989   /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
1990   ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
1991   return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
1992 }
1993 
1994 #ifndef SQLITE_OMIT_WAL
1995 /*
1996 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
1997 ** not currently open in WAL mode.
1998 **
1999 ** If a transaction is open on the database being checkpointed, this
2000 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
2001 ** an error occurs while running the checkpoint, an SQLite error code is
2002 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
2003 **
2004 ** The mutex on database handle db should be held by the caller. The mutex
2005 ** associated with the specific b-tree being checkpointed is taken by
2006 ** this function while the checkpoint is running.
2007 **
2008 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
2009 ** checkpointed. If an error is encountered it is returned immediately -
2010 ** no attempt is made to checkpoint any remaining databases.
2011 **
2012 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
2013 */
2014 int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
2015   int rc = SQLITE_OK;             /* Return code */
2016   int i;                          /* Used to iterate through attached dbs */
2017   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
2018 
2019   assert( sqlite3_mutex_held(db->mutex) );
2020   assert( !pnLog || *pnLog==-1 );
2021   assert( !pnCkpt || *pnCkpt==-1 );
2022 
2023   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
2024     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
2025       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
2026       pnLog = 0;
2027       pnCkpt = 0;
2028       if( rc==SQLITE_BUSY ){
2029         bBusy = 1;
2030         rc = SQLITE_OK;
2031       }
2032     }
2033   }
2034 
2035   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
2036 }
2037 #endif /* SQLITE_OMIT_WAL */
2038 
2039 /*
2040 ** This function returns true if main-memory should be used instead of
2041 ** a temporary file for transient pager files and statement journals.
2042 ** The value returned depends on the value of db->temp_store (runtime
2043 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
2044 ** following table describes the relationship between these two values
2045 ** and this functions return value.
2046 **
2047 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
2048 **   -----------------     --------------     ------------------------------
2049 **   0                     any                file      (return 0)
2050 **   1                     1                  file      (return 0)
2051 **   1                     2                  memory    (return 1)
2052 **   1                     0                  file      (return 0)
2053 **   2                     1                  file      (return 0)
2054 **   2                     2                  memory    (return 1)
2055 **   2                     0                  memory    (return 1)
2056 **   3                     any                memory    (return 1)
2057 */
2058 int sqlite3TempInMemory(const sqlite3 *db){
2059 #if SQLITE_TEMP_STORE==1
2060   return ( db->temp_store==2 );
2061 #endif
2062 #if SQLITE_TEMP_STORE==2
2063   return ( db->temp_store!=1 );
2064 #endif
2065 #if SQLITE_TEMP_STORE==3
2066   return 1;
2067 #endif
2068 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
2069   return 0;
2070 #endif
2071 }
2072 
2073 /*
2074 ** Return UTF-8 encoded English language explanation of the most recent
2075 ** error.
2076 */
2077 const char *sqlite3_errmsg(sqlite3 *db){
2078   const char *z;
2079   if( !db ){
2080     return sqlite3ErrStr(SQLITE_NOMEM);
2081   }
2082   if( !sqlite3SafetyCheckSickOrOk(db) ){
2083     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
2084   }
2085   sqlite3_mutex_enter(db->mutex);
2086   if( db->mallocFailed ){
2087     z = sqlite3ErrStr(SQLITE_NOMEM);
2088   }else{
2089     testcase( db->pErr==0 );
2090     z = (char*)sqlite3_value_text(db->pErr);
2091     assert( !db->mallocFailed );
2092     if( z==0 ){
2093       z = sqlite3ErrStr(db->errCode);
2094     }
2095   }
2096   sqlite3_mutex_leave(db->mutex);
2097   return z;
2098 }
2099 
2100 #ifndef SQLITE_OMIT_UTF16
2101 /*
2102 ** Return UTF-16 encoded English language explanation of the most recent
2103 ** error.
2104 */
2105 const void *sqlite3_errmsg16(sqlite3 *db){
2106   static const u16 outOfMem[] = {
2107     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
2108   };
2109   static const u16 misuse[] = {
2110     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
2111     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
2112     'c', 'a', 'l', 'l', 'e', 'd', ' ',
2113     'o', 'u', 't', ' ',
2114     'o', 'f', ' ',
2115     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
2116   };
2117 
2118   const void *z;
2119   if( !db ){
2120     return (void *)outOfMem;
2121   }
2122   if( !sqlite3SafetyCheckSickOrOk(db) ){
2123     return (void *)misuse;
2124   }
2125   sqlite3_mutex_enter(db->mutex);
2126   if( db->mallocFailed ){
2127     z = (void *)outOfMem;
2128   }else{
2129     z = sqlite3_value_text16(db->pErr);
2130     if( z==0 ){
2131       sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
2132       z = sqlite3_value_text16(db->pErr);
2133     }
2134     /* A malloc() may have failed within the call to sqlite3_value_text16()
2135     ** above. If this is the case, then the db->mallocFailed flag needs to
2136     ** be cleared before returning. Do this directly, instead of via
2137     ** sqlite3ApiExit(), to avoid setting the database handle error message.
2138     */
2139     db->mallocFailed = 0;
2140   }
2141   sqlite3_mutex_leave(db->mutex);
2142   return z;
2143 }
2144 #endif /* SQLITE_OMIT_UTF16 */
2145 
2146 /*
2147 ** Return the most recent error code generated by an SQLite routine. If NULL is
2148 ** passed to this function, we assume a malloc() failed during sqlite3_open().
2149 */
2150 int sqlite3_errcode(sqlite3 *db){
2151   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2152     return SQLITE_MISUSE_BKPT;
2153   }
2154   if( !db || db->mallocFailed ){
2155     return SQLITE_NOMEM;
2156   }
2157   return db->errCode & db->errMask;
2158 }
2159 int sqlite3_extended_errcode(sqlite3 *db){
2160   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
2161     return SQLITE_MISUSE_BKPT;
2162   }
2163   if( !db || db->mallocFailed ){
2164     return SQLITE_NOMEM;
2165   }
2166   return db->errCode;
2167 }
2168 
2169 /*
2170 ** Return a string that describes the kind of error specified in the
2171 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
2172 ** function.
2173 */
2174 const char *sqlite3_errstr(int rc){
2175   return sqlite3ErrStr(rc);
2176 }
2177 
2178 /*
2179 ** Create a new collating function for database "db".  The name is zName
2180 ** and the encoding is enc.
2181 */
2182 static int createCollation(
2183   sqlite3* db,
2184   const char *zName,
2185   u8 enc,
2186   void* pCtx,
2187   int(*xCompare)(void*,int,const void*,int,const void*),
2188   void(*xDel)(void*)
2189 ){
2190   CollSeq *pColl;
2191   int enc2;
2192 
2193   assert( sqlite3_mutex_held(db->mutex) );
2194 
2195   /* If SQLITE_UTF16 is specified as the encoding type, transform this
2196   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
2197   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
2198   */
2199   enc2 = enc;
2200   testcase( enc2==SQLITE_UTF16 );
2201   testcase( enc2==SQLITE_UTF16_ALIGNED );
2202   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
2203     enc2 = SQLITE_UTF16NATIVE;
2204   }
2205   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
2206     return SQLITE_MISUSE_BKPT;
2207   }
2208 
2209   /* Check if this call is removing or replacing an existing collation
2210   ** sequence. If so, and there are active VMs, return busy. If there
2211   ** are no active VMs, invalidate any pre-compiled statements.
2212   */
2213   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
2214   if( pColl && pColl->xCmp ){
2215     if( db->nVdbeActive ){
2216       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
2217         "unable to delete/modify collation sequence due to active statements");
2218       return SQLITE_BUSY;
2219     }
2220     sqlite3ExpirePreparedStatements(db);
2221 
2222     /* If collation sequence pColl was created directly by a call to
2223     ** sqlite3_create_collation, and not generated by synthCollSeq(),
2224     ** then any copies made by synthCollSeq() need to be invalidated.
2225     ** Also, collation destructor - CollSeq.xDel() - function may need
2226     ** to be called.
2227     */
2228     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
2229       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
2230       int j;
2231       for(j=0; j<3; j++){
2232         CollSeq *p = &aColl[j];
2233         if( p->enc==pColl->enc ){
2234           if( p->xDel ){
2235             p->xDel(p->pUser);
2236           }
2237           p->xCmp = 0;
2238         }
2239       }
2240     }
2241   }
2242 
2243   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
2244   if( pColl==0 ) return SQLITE_NOMEM;
2245   pColl->xCmp = xCompare;
2246   pColl->pUser = pCtx;
2247   pColl->xDel = xDel;
2248   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
2249   sqlite3Error(db, SQLITE_OK);
2250   return SQLITE_OK;
2251 }
2252 
2253 
2254 /*
2255 ** This array defines hard upper bounds on limit values.  The
2256 ** initializer must be kept in sync with the SQLITE_LIMIT_*
2257 ** #defines in sqlite3.h.
2258 */
2259 static const int aHardLimit[] = {
2260   SQLITE_MAX_LENGTH,
2261   SQLITE_MAX_SQL_LENGTH,
2262   SQLITE_MAX_COLUMN,
2263   SQLITE_MAX_EXPR_DEPTH,
2264   SQLITE_MAX_COMPOUND_SELECT,
2265   SQLITE_MAX_VDBE_OP,
2266   SQLITE_MAX_FUNCTION_ARG,
2267   SQLITE_MAX_ATTACHED,
2268   SQLITE_MAX_LIKE_PATTERN_LENGTH,
2269   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
2270   SQLITE_MAX_TRIGGER_DEPTH,
2271   SQLITE_MAX_WORKER_THREADS,
2272 };
2273 
2274 /*
2275 ** Make sure the hard limits are set to reasonable values
2276 */
2277 #if SQLITE_MAX_LENGTH<100
2278 # error SQLITE_MAX_LENGTH must be at least 100
2279 #endif
2280 #if SQLITE_MAX_SQL_LENGTH<100
2281 # error SQLITE_MAX_SQL_LENGTH must be at least 100
2282 #endif
2283 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
2284 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
2285 #endif
2286 #if SQLITE_MAX_COMPOUND_SELECT<2
2287 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
2288 #endif
2289 #if SQLITE_MAX_VDBE_OP<40
2290 # error SQLITE_MAX_VDBE_OP must be at least 40
2291 #endif
2292 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
2293 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
2294 #endif
2295 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
2296 # error SQLITE_MAX_ATTACHED must be between 0 and 125
2297 #endif
2298 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
2299 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
2300 #endif
2301 #if SQLITE_MAX_COLUMN>32767
2302 # error SQLITE_MAX_COLUMN must not exceed 32767
2303 #endif
2304 #if SQLITE_MAX_TRIGGER_DEPTH<1
2305 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
2306 #endif
2307 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
2308 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
2309 #endif
2310 
2311 
2312 /*
2313 ** Change the value of a limit.  Report the old value.
2314 ** If an invalid limit index is supplied, report -1.
2315 ** Make no changes but still report the old value if the
2316 ** new limit is negative.
2317 **
2318 ** A new lower limit does not shrink existing constructs.
2319 ** It merely prevents new constructs that exceed the limit
2320 ** from forming.
2321 */
2322 int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
2323   int oldLimit;
2324 
2325 #ifdef SQLITE_ENABLE_API_ARMOR
2326   if( !sqlite3SafetyCheckOk(db) ){
2327     (void)SQLITE_MISUSE_BKPT;
2328     return -1;
2329   }
2330 #endif
2331 
2332   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
2333   ** there is a hard upper bound set at compile-time by a C preprocessor
2334   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
2335   ** "_MAX_".)
2336   */
2337   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
2338   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
2339   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
2340   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
2341   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
2342   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
2343   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
2344   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
2345   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
2346                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
2347   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
2348   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
2349   assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
2350   assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
2351 
2352 
2353   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
2354     return -1;
2355   }
2356   oldLimit = db->aLimit[limitId];
2357   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
2358     if( newLimit>aHardLimit[limitId] ){
2359       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
2360     }
2361     db->aLimit[limitId] = newLimit;
2362   }
2363   return oldLimit;                     /* IMP: R-53341-35419 */
2364 }
2365 
2366 /*
2367 ** This function is used to parse both URIs and non-URI filenames passed by the
2368 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
2369 ** URIs specified as part of ATTACH statements.
2370 **
2371 ** The first argument to this function is the name of the VFS to use (or
2372 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
2373 ** query parameter. The second argument contains the URI (or non-URI filename)
2374 ** itself. When this function is called the *pFlags variable should contain
2375 ** the default flags to open the database handle with. The value stored in
2376 ** *pFlags may be updated before returning if the URI filename contains
2377 ** "cache=xxx" or "mode=xxx" query parameters.
2378 **
2379 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
2380 ** the VFS that should be used to open the database file. *pzFile is set to
2381 ** point to a buffer containing the name of the file to open. It is the
2382 ** responsibility of the caller to eventually call sqlite3_free() to release
2383 ** this buffer.
2384 **
2385 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
2386 ** may be set to point to a buffer containing an English language error
2387 ** message. It is the responsibility of the caller to eventually release
2388 ** this buffer by calling sqlite3_free().
2389 */
2390 int sqlite3ParseUri(
2391   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
2392   const char *zUri,               /* Nul-terminated URI to parse */
2393   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
2394   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
2395   char **pzFile,                  /* OUT: Filename component of URI */
2396   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
2397 ){
2398   int rc = SQLITE_OK;
2399   unsigned int flags = *pFlags;
2400   const char *zVfs = zDefaultVfs;
2401   char *zFile;
2402   char c;
2403   int nUri = sqlite3Strlen30(zUri);
2404 
2405   assert( *pzErrMsg==0 );
2406 
2407   if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
2408             || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
2409    && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
2410   ){
2411     char *zOpt;
2412     int eState;                   /* Parser state when parsing URI */
2413     int iIn;                      /* Input character index */
2414     int iOut = 0;                 /* Output character index */
2415     int nByte = nUri+2;           /* Bytes of space to allocate */
2416 
2417     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
2418     ** method that there may be extra parameters following the file-name.  */
2419     flags |= SQLITE_OPEN_URI;
2420 
2421     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
2422     zFile = sqlite3_malloc(nByte);
2423     if( !zFile ) return SQLITE_NOMEM;
2424 
2425     iIn = 5;
2426 #ifndef SQLITE_ALLOW_URI_AUTHORITY
2427     /* Discard the scheme and authority segments of the URI. */
2428     if( zUri[5]=='/' && zUri[6]=='/' ){
2429       iIn = 7;
2430       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
2431       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
2432         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
2433             iIn-7, &zUri[7]);
2434         rc = SQLITE_ERROR;
2435         goto parse_uri_out;
2436       }
2437     }
2438 #endif
2439 
2440     /* Copy the filename and any query parameters into the zFile buffer.
2441     ** Decode %HH escape codes along the way.
2442     **
2443     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
2444     ** on the parsing context. As follows:
2445     **
2446     **   0: Parsing file-name.
2447     **   1: Parsing name section of a name=value query parameter.
2448     **   2: Parsing value section of a name=value query parameter.
2449     */
2450     eState = 0;
2451     while( (c = zUri[iIn])!=0 && c!='#' ){
2452       iIn++;
2453       if( c=='%'
2454        && sqlite3Isxdigit(zUri[iIn])
2455        && sqlite3Isxdigit(zUri[iIn+1])
2456       ){
2457         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
2458         octet += sqlite3HexToInt(zUri[iIn++]);
2459 
2460         assert( octet>=0 && octet<256 );
2461         if( octet==0 ){
2462           /* This branch is taken when "%00" appears within the URI. In this
2463           ** case we ignore all text in the remainder of the path, name or
2464           ** value currently being parsed. So ignore the current character
2465           ** and skip to the next "?", "=" or "&", as appropriate. */
2466           while( (c = zUri[iIn])!=0 && c!='#'
2467               && (eState!=0 || c!='?')
2468               && (eState!=1 || (c!='=' && c!='&'))
2469               && (eState!=2 || c!='&')
2470           ){
2471             iIn++;
2472           }
2473           continue;
2474         }
2475         c = octet;
2476       }else if( eState==1 && (c=='&' || c=='=') ){
2477         if( zFile[iOut-1]==0 ){
2478           /* An empty option name. Ignore this option altogether. */
2479           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
2480           continue;
2481         }
2482         if( c=='&' ){
2483           zFile[iOut++] = '\0';
2484         }else{
2485           eState = 2;
2486         }
2487         c = 0;
2488       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
2489         c = 0;
2490         eState = 1;
2491       }
2492       zFile[iOut++] = c;
2493     }
2494     if( eState==1 ) zFile[iOut++] = '\0';
2495     zFile[iOut++] = '\0';
2496     zFile[iOut++] = '\0';
2497 
2498     /* Check if there were any options specified that should be interpreted
2499     ** here. Options that are interpreted here include "vfs" and those that
2500     ** correspond to flags that may be passed to the sqlite3_open_v2()
2501     ** method. */
2502     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
2503     while( zOpt[0] ){
2504       int nOpt = sqlite3Strlen30(zOpt);
2505       char *zVal = &zOpt[nOpt+1];
2506       int nVal = sqlite3Strlen30(zVal);
2507 
2508       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
2509         zVfs = zVal;
2510       }else{
2511         struct OpenMode {
2512           const char *z;
2513           int mode;
2514         } *aMode = 0;
2515         char *zModeType = 0;
2516         int mask = 0;
2517         int limit = 0;
2518 
2519         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
2520           static struct OpenMode aCacheMode[] = {
2521             { "shared",  SQLITE_OPEN_SHAREDCACHE },
2522             { "private", SQLITE_OPEN_PRIVATECACHE },
2523             { 0, 0 }
2524           };
2525 
2526           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
2527           aMode = aCacheMode;
2528           limit = mask;
2529           zModeType = "cache";
2530         }
2531         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
2532           static struct OpenMode aOpenMode[] = {
2533             { "ro",  SQLITE_OPEN_READONLY },
2534             { "rw",  SQLITE_OPEN_READWRITE },
2535             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
2536             { "memory", SQLITE_OPEN_MEMORY },
2537             { 0, 0 }
2538           };
2539 
2540           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
2541                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
2542           aMode = aOpenMode;
2543           limit = mask & flags;
2544           zModeType = "access";
2545         }
2546 
2547         if( aMode ){
2548           int i;
2549           int mode = 0;
2550           for(i=0; aMode[i].z; i++){
2551             const char *z = aMode[i].z;
2552             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
2553               mode = aMode[i].mode;
2554               break;
2555             }
2556           }
2557           if( mode==0 ){
2558             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
2559             rc = SQLITE_ERROR;
2560             goto parse_uri_out;
2561           }
2562           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
2563             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
2564                                         zModeType, zVal);
2565             rc = SQLITE_PERM;
2566             goto parse_uri_out;
2567           }
2568           flags = (flags & ~mask) | mode;
2569         }
2570       }
2571 
2572       zOpt = &zVal[nVal+1];
2573     }
2574 
2575   }else{
2576     zFile = sqlite3_malloc(nUri+2);
2577     if( !zFile ) return SQLITE_NOMEM;
2578     memcpy(zFile, zUri, nUri);
2579     zFile[nUri] = '\0';
2580     zFile[nUri+1] = '\0';
2581     flags &= ~SQLITE_OPEN_URI;
2582   }
2583 
2584   *ppVfs = sqlite3_vfs_find(zVfs);
2585   if( *ppVfs==0 ){
2586     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
2587     rc = SQLITE_ERROR;
2588   }
2589  parse_uri_out:
2590   if( rc!=SQLITE_OK ){
2591     sqlite3_free(zFile);
2592     zFile = 0;
2593   }
2594   *pFlags = flags;
2595   *pzFile = zFile;
2596   return rc;
2597 }
2598 
2599 
2600 /*
2601 ** This routine does the work of opening a database on behalf of
2602 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
2603 ** is UTF-8 encoded.
2604 */
2605 static int openDatabase(
2606   const char *zFilename, /* Database filename UTF-8 encoded */
2607   sqlite3 **ppDb,        /* OUT: Returned database handle */
2608   unsigned int flags,    /* Operational flags */
2609   const char *zVfs       /* Name of the VFS to use */
2610 ){
2611   sqlite3 *db;                    /* Store allocated handle here */
2612   int rc;                         /* Return code */
2613   int isThreadsafe;               /* True for threadsafe connections */
2614   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
2615   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
2616 
2617 #ifdef SQLITE_ENABLE_API_ARMOR
2618   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
2619 #endif
2620   *ppDb = 0;
2621 #ifndef SQLITE_OMIT_AUTOINIT
2622   rc = sqlite3_initialize();
2623   if( rc ) return rc;
2624 #endif
2625 
2626   /* Only allow sensible combinations of bits in the flags argument.
2627   ** Throw an error if any non-sense combination is used.  If we
2628   ** do not block illegal combinations here, it could trigger
2629   ** assert() statements in deeper layers.  Sensible combinations
2630   ** are:
2631   **
2632   **  1:  SQLITE_OPEN_READONLY
2633   **  2:  SQLITE_OPEN_READWRITE
2634   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
2635   */
2636   assert( SQLITE_OPEN_READONLY  == 0x01 );
2637   assert( SQLITE_OPEN_READWRITE == 0x02 );
2638   assert( SQLITE_OPEN_CREATE    == 0x04 );
2639   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
2640   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
2641   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
2642   if( ((1<<(flags&7)) & 0x46)==0 ){
2643     return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
2644   }
2645 
2646   if( sqlite3GlobalConfig.bCoreMutex==0 ){
2647     isThreadsafe = 0;
2648   }else if( flags & SQLITE_OPEN_NOMUTEX ){
2649     isThreadsafe = 0;
2650   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
2651     isThreadsafe = 1;
2652   }else{
2653     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
2654   }
2655   if( flags & SQLITE_OPEN_PRIVATECACHE ){
2656     flags &= ~SQLITE_OPEN_SHAREDCACHE;
2657   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
2658     flags |= SQLITE_OPEN_SHAREDCACHE;
2659   }
2660 
2661   /* Remove harmful bits from the flags parameter
2662   **
2663   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
2664   ** dealt with in the previous code block.  Besides these, the only
2665   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
2666   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
2667   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
2668   ** off all other flags.
2669   */
2670   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
2671                SQLITE_OPEN_EXCLUSIVE |
2672                SQLITE_OPEN_MAIN_DB |
2673                SQLITE_OPEN_TEMP_DB |
2674                SQLITE_OPEN_TRANSIENT_DB |
2675                SQLITE_OPEN_MAIN_JOURNAL |
2676                SQLITE_OPEN_TEMP_JOURNAL |
2677                SQLITE_OPEN_SUBJOURNAL |
2678                SQLITE_OPEN_MASTER_JOURNAL |
2679                SQLITE_OPEN_NOMUTEX |
2680                SQLITE_OPEN_FULLMUTEX |
2681                SQLITE_OPEN_WAL
2682              );
2683 
2684   /* Allocate the sqlite data structure */
2685   db = sqlite3MallocZero( sizeof(sqlite3) );
2686   if( db==0 ) goto opendb_out;
2687   if( isThreadsafe ){
2688     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
2689     if( db->mutex==0 ){
2690       sqlite3_free(db);
2691       db = 0;
2692       goto opendb_out;
2693     }
2694   }
2695   sqlite3_mutex_enter(db->mutex);
2696   db->errMask = 0xff;
2697   db->nDb = 2;
2698   db->magic = SQLITE_MAGIC_BUSY;
2699   db->aDb = db->aDbStatic;
2700 
2701   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
2702   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
2703   db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
2704   db->autoCommit = 1;
2705   db->nextAutovac = -1;
2706   db->szMmap = sqlite3GlobalConfig.szMmap;
2707   db->nextPagesize = 0;
2708   db->nMaxSorterMmap = 0x7FFFFFFF;
2709   db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
2710 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
2711                  | SQLITE_AutoIndex
2712 #endif
2713 #if SQLITE_DEFAULT_FILE_FORMAT<4
2714                  | SQLITE_LegacyFileFmt
2715 #endif
2716 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
2717                  | SQLITE_LoadExtension
2718 #endif
2719 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
2720                  | SQLITE_RecTriggers
2721 #endif
2722 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
2723                  | SQLITE_ForeignKeys
2724 #endif
2725 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
2726                  | SQLITE_ReverseOrder
2727 #endif
2728       ;
2729   sqlite3HashInit(&db->aCollSeq);
2730 #ifndef SQLITE_OMIT_VIRTUALTABLE
2731   sqlite3HashInit(&db->aModule);
2732 #endif
2733 
2734   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
2735   ** and UTF-16, so add a version for each to avoid any unnecessary
2736   ** conversions. The only error that can occur here is a malloc() failure.
2737   **
2738   ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
2739   ** functions:
2740   */
2741   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
2742   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
2743   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
2744   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
2745   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
2746   if( db->mallocFailed ){
2747     goto opendb_out;
2748   }
2749   /* EVIDENCE-OF: R-08308-17224 The default collating function for all
2750   ** strings is BINARY.
2751   */
2752   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
2753   assert( db->pDfltColl!=0 );
2754 
2755   /* Parse the filename/URI argument. */
2756   db->openFlags = flags;
2757   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
2758   if( rc!=SQLITE_OK ){
2759     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
2760     sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
2761     sqlite3_free(zErrMsg);
2762     goto opendb_out;
2763   }
2764 
2765   /* Open the backend database driver */
2766   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
2767                         flags | SQLITE_OPEN_MAIN_DB);
2768   if( rc!=SQLITE_OK ){
2769     if( rc==SQLITE_IOERR_NOMEM ){
2770       rc = SQLITE_NOMEM;
2771     }
2772     sqlite3Error(db, rc);
2773     goto opendb_out;
2774   }
2775   sqlite3BtreeEnter(db->aDb[0].pBt);
2776   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
2777   if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
2778   sqlite3BtreeLeave(db->aDb[0].pBt);
2779   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
2780 
2781   /* The default safety_level for the main database is 'full'; for the temp
2782   ** database it is 'NONE'. This matches the pager layer defaults.
2783   */
2784   db->aDb[0].zName = "main";
2785   db->aDb[0].safety_level = 3;
2786   db->aDb[1].zName = "temp";
2787   db->aDb[1].safety_level = 1;
2788 
2789   db->magic = SQLITE_MAGIC_OPEN;
2790   if( db->mallocFailed ){
2791     goto opendb_out;
2792   }
2793 
2794   /* Register all built-in functions, but do not attempt to read the
2795   ** database schema yet. This is delayed until the first time the database
2796   ** is accessed.
2797   */
2798   sqlite3Error(db, SQLITE_OK);
2799   sqlite3RegisterBuiltinFunctions(db);
2800 
2801   /* Load automatic extensions - extensions that have been registered
2802   ** using the sqlite3_automatic_extension() API.
2803   */
2804   rc = sqlite3_errcode(db);
2805   if( rc==SQLITE_OK ){
2806     sqlite3AutoLoadExtensions(db);
2807     rc = sqlite3_errcode(db);
2808     if( rc!=SQLITE_OK ){
2809       goto opendb_out;
2810     }
2811   }
2812 
2813 #ifdef SQLITE_ENABLE_FTS1
2814   if( !db->mallocFailed ){
2815     extern int sqlite3Fts1Init(sqlite3*);
2816     rc = sqlite3Fts1Init(db);
2817   }
2818 #endif
2819 
2820 #ifdef SQLITE_ENABLE_FTS2
2821   if( !db->mallocFailed && rc==SQLITE_OK ){
2822     extern int sqlite3Fts2Init(sqlite3*);
2823     rc = sqlite3Fts2Init(db);
2824   }
2825 #endif
2826 
2827 #ifdef SQLITE_ENABLE_FTS3
2828   if( !db->mallocFailed && rc==SQLITE_OK ){
2829     rc = sqlite3Fts3Init(db);
2830   }
2831 #endif
2832 
2833 #ifdef SQLITE_ENABLE_FTS5
2834   if( !db->mallocFailed && rc==SQLITE_OK ){
2835     rc = sqlite3Fts5Init(db);
2836   }
2837 #endif
2838 
2839 #ifdef SQLITE_ENABLE_ICU
2840   if( !db->mallocFailed && rc==SQLITE_OK ){
2841     rc = sqlite3IcuInit(db);
2842   }
2843 #endif
2844 
2845 #ifdef SQLITE_ENABLE_RTREE
2846   if( !db->mallocFailed && rc==SQLITE_OK){
2847     rc = sqlite3RtreeInit(db);
2848   }
2849 #endif
2850 
2851   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
2852   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
2853   ** mode.  Doing nothing at all also makes NORMAL the default.
2854   */
2855 #ifdef SQLITE_DEFAULT_LOCKING_MODE
2856   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
2857   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
2858                           SQLITE_DEFAULT_LOCKING_MODE);
2859 #endif
2860 
2861   if( rc ) sqlite3Error(db, rc);
2862 
2863   /* Enable the lookaside-malloc subsystem */
2864   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
2865                         sqlite3GlobalConfig.nLookaside);
2866 
2867   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
2868 
2869 opendb_out:
2870   sqlite3_free(zOpen);
2871   if( db ){
2872     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
2873     sqlite3_mutex_leave(db->mutex);
2874   }
2875   rc = sqlite3_errcode(db);
2876   assert( db!=0 || rc==SQLITE_NOMEM );
2877   if( rc==SQLITE_NOMEM ){
2878     sqlite3_close(db);
2879     db = 0;
2880   }else if( rc!=SQLITE_OK ){
2881     db->magic = SQLITE_MAGIC_SICK;
2882   }
2883   *ppDb = db;
2884 #ifdef SQLITE_ENABLE_SQLLOG
2885   if( sqlite3GlobalConfig.xSqllog ){
2886     /* Opening a db handle. Fourth parameter is passed 0. */
2887     void *pArg = sqlite3GlobalConfig.pSqllogArg;
2888     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
2889   }
2890 #endif
2891   return sqlite3ApiExit(0, rc);
2892 }
2893 
2894 /*
2895 ** Open a new database handle.
2896 */
2897 int sqlite3_open(
2898   const char *zFilename,
2899   sqlite3 **ppDb
2900 ){
2901   return openDatabase(zFilename, ppDb,
2902                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
2903 }
2904 int sqlite3_open_v2(
2905   const char *filename,   /* Database filename (UTF-8) */
2906   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2907   int flags,              /* Flags */
2908   const char *zVfs        /* Name of VFS module to use */
2909 ){
2910   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
2911 }
2912 
2913 #ifndef SQLITE_OMIT_UTF16
2914 /*
2915 ** Open a new database handle.
2916 */
2917 int sqlite3_open16(
2918   const void *zFilename,
2919   sqlite3 **ppDb
2920 ){
2921   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
2922   sqlite3_value *pVal;
2923   int rc;
2924 
2925 #ifdef SQLITE_ENABLE_API_ARMOR
2926   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
2927 #endif
2928   *ppDb = 0;
2929 #ifndef SQLITE_OMIT_AUTOINIT
2930   rc = sqlite3_initialize();
2931   if( rc ) return rc;
2932 #endif
2933   if( zFilename==0 ) zFilename = "\000\000";
2934   pVal = sqlite3ValueNew(0);
2935   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
2936   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
2937   if( zFilename8 ){
2938     rc = openDatabase(zFilename8, ppDb,
2939                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
2940     assert( *ppDb || rc==SQLITE_NOMEM );
2941     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
2942       SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
2943     }
2944   }else{
2945     rc = SQLITE_NOMEM;
2946   }
2947   sqlite3ValueFree(pVal);
2948 
2949   return sqlite3ApiExit(0, rc);
2950 }
2951 #endif /* SQLITE_OMIT_UTF16 */
2952 
2953 /*
2954 ** Register a new collation sequence with the database handle db.
2955 */
2956 int sqlite3_create_collation(
2957   sqlite3* db,
2958   const char *zName,
2959   int enc,
2960   void* pCtx,
2961   int(*xCompare)(void*,int,const void*,int,const void*)
2962 ){
2963   return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
2964 }
2965 
2966 /*
2967 ** Register a new collation sequence with the database handle db.
2968 */
2969 int sqlite3_create_collation_v2(
2970   sqlite3* db,
2971   const char *zName,
2972   int enc,
2973   void* pCtx,
2974   int(*xCompare)(void*,int,const void*,int,const void*),
2975   void(*xDel)(void*)
2976 ){
2977   int rc;
2978 
2979 #ifdef SQLITE_ENABLE_API_ARMOR
2980   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
2981 #endif
2982   sqlite3_mutex_enter(db->mutex);
2983   assert( !db->mallocFailed );
2984   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
2985   rc = sqlite3ApiExit(db, rc);
2986   sqlite3_mutex_leave(db->mutex);
2987   return rc;
2988 }
2989 
2990 #ifndef SQLITE_OMIT_UTF16
2991 /*
2992 ** Register a new collation sequence with the database handle db.
2993 */
2994 int sqlite3_create_collation16(
2995   sqlite3* db,
2996   const void *zName,
2997   int enc,
2998   void* pCtx,
2999   int(*xCompare)(void*,int,const void*,int,const void*)
3000 ){
3001   int rc = SQLITE_OK;
3002   char *zName8;
3003 
3004 #ifdef SQLITE_ENABLE_API_ARMOR
3005   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
3006 #endif
3007   sqlite3_mutex_enter(db->mutex);
3008   assert( !db->mallocFailed );
3009   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
3010   if( zName8 ){
3011     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
3012     sqlite3DbFree(db, zName8);
3013   }
3014   rc = sqlite3ApiExit(db, rc);
3015   sqlite3_mutex_leave(db->mutex);
3016   return rc;
3017 }
3018 #endif /* SQLITE_OMIT_UTF16 */
3019 
3020 /*
3021 ** Register a collation sequence factory callback with the database handle
3022 ** db. Replace any previously installed collation sequence factory.
3023 */
3024 int sqlite3_collation_needed(
3025   sqlite3 *db,
3026   void *pCollNeededArg,
3027   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
3028 ){
3029 #ifdef SQLITE_ENABLE_API_ARMOR
3030   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3031 #endif
3032   sqlite3_mutex_enter(db->mutex);
3033   db->xCollNeeded = xCollNeeded;
3034   db->xCollNeeded16 = 0;
3035   db->pCollNeededArg = pCollNeededArg;
3036   sqlite3_mutex_leave(db->mutex);
3037   return SQLITE_OK;
3038 }
3039 
3040 #ifndef SQLITE_OMIT_UTF16
3041 /*
3042 ** Register a collation sequence factory callback with the database handle
3043 ** db. Replace any previously installed collation sequence factory.
3044 */
3045 int sqlite3_collation_needed16(
3046   sqlite3 *db,
3047   void *pCollNeededArg,
3048   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
3049 ){
3050 #ifdef SQLITE_ENABLE_API_ARMOR
3051   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3052 #endif
3053   sqlite3_mutex_enter(db->mutex);
3054   db->xCollNeeded = 0;
3055   db->xCollNeeded16 = xCollNeeded16;
3056   db->pCollNeededArg = pCollNeededArg;
3057   sqlite3_mutex_leave(db->mutex);
3058   return SQLITE_OK;
3059 }
3060 #endif /* SQLITE_OMIT_UTF16 */
3061 
3062 #ifndef SQLITE_OMIT_DEPRECATED
3063 /*
3064 ** This function is now an anachronism. It used to be used to recover from a
3065 ** malloc() failure, but SQLite now does this automatically.
3066 */
3067 int sqlite3_global_recover(void){
3068   return SQLITE_OK;
3069 }
3070 #endif
3071 
3072 /*
3073 ** Test to see whether or not the database connection is in autocommit
3074 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
3075 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
3076 ** by the next COMMIT or ROLLBACK.
3077 */
3078 int sqlite3_get_autocommit(sqlite3 *db){
3079 #ifdef SQLITE_ENABLE_API_ARMOR
3080   if( !sqlite3SafetyCheckOk(db) ){
3081     (void)SQLITE_MISUSE_BKPT;
3082     return 0;
3083   }
3084 #endif
3085   return db->autoCommit;
3086 }
3087 
3088 /*
3089 ** The following routines are substitutes for constants SQLITE_CORRUPT,
3090 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
3091 ** constants.  They serve two purposes:
3092 **
3093 **   1.  Serve as a convenient place to set a breakpoint in a debugger
3094 **       to detect when version error conditions occurs.
3095 **
3096 **   2.  Invoke sqlite3_log() to provide the source code location where
3097 **       a low-level error is first detected.
3098 */
3099 int sqlite3CorruptError(int lineno){
3100   testcase( sqlite3GlobalConfig.xLog!=0 );
3101   sqlite3_log(SQLITE_CORRUPT,
3102               "database corruption at line %d of [%.10s]",
3103               lineno, 20+sqlite3_sourceid());
3104   return SQLITE_CORRUPT;
3105 }
3106 int sqlite3MisuseError(int lineno){
3107   testcase( sqlite3GlobalConfig.xLog!=0 );
3108   sqlite3_log(SQLITE_MISUSE,
3109               "misuse at line %d of [%.10s]",
3110               lineno, 20+sqlite3_sourceid());
3111   return SQLITE_MISUSE;
3112 }
3113 int sqlite3CantopenError(int lineno){
3114   testcase( sqlite3GlobalConfig.xLog!=0 );
3115   sqlite3_log(SQLITE_CANTOPEN,
3116               "cannot open file at line %d of [%.10s]",
3117               lineno, 20+sqlite3_sourceid());
3118   return SQLITE_CANTOPEN;
3119 }
3120 
3121 
3122 #ifndef SQLITE_OMIT_DEPRECATED
3123 /*
3124 ** This is a convenience routine that makes sure that all thread-specific
3125 ** data for this thread has been deallocated.
3126 **
3127 ** SQLite no longer uses thread-specific data so this routine is now a
3128 ** no-op.  It is retained for historical compatibility.
3129 */
3130 void sqlite3_thread_cleanup(void){
3131 }
3132 #endif
3133 
3134 /*
3135 ** Return meta information about a specific column of a database table.
3136 ** See comment in sqlite3.h (sqlite.h.in) for details.
3137 */
3138 int sqlite3_table_column_metadata(
3139   sqlite3 *db,                /* Connection handle */
3140   const char *zDbName,        /* Database name or NULL */
3141   const char *zTableName,     /* Table name */
3142   const char *zColumnName,    /* Column name */
3143   char const **pzDataType,    /* OUTPUT: Declared data type */
3144   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
3145   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
3146   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
3147   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
3148 ){
3149   int rc;
3150   char *zErrMsg = 0;
3151   Table *pTab = 0;
3152   Column *pCol = 0;
3153   int iCol = 0;
3154 
3155   char const *zDataType = 0;
3156   char const *zCollSeq = 0;
3157   int notnull = 0;
3158   int primarykey = 0;
3159   int autoinc = 0;
3160 
3161   /* Ensure the database schema has been loaded */
3162   sqlite3_mutex_enter(db->mutex);
3163   sqlite3BtreeEnterAll(db);
3164   rc = sqlite3Init(db, &zErrMsg);
3165   if( SQLITE_OK!=rc ){
3166     goto error_out;
3167   }
3168 
3169   /* Locate the table in question */
3170   pTab = sqlite3FindTable(db, zTableName, zDbName);
3171   if( !pTab || pTab->pSelect ){
3172     pTab = 0;
3173     goto error_out;
3174   }
3175 
3176   /* Find the column for which info is requested */
3177   if( zColumnName==0 ){
3178     /* Query for existance of table only */
3179   }else{
3180     for(iCol=0; iCol<pTab->nCol; iCol++){
3181       pCol = &pTab->aCol[iCol];
3182       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
3183         break;
3184       }
3185     }
3186     if( iCol==pTab->nCol ){
3187       if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
3188         iCol = pTab->iPKey;
3189         pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
3190       }else{
3191         pTab = 0;
3192         goto error_out;
3193       }
3194     }
3195   }
3196 
3197   /* The following block stores the meta information that will be returned
3198   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
3199   ** and autoinc. At this point there are two possibilities:
3200   **
3201   **     1. The specified column name was rowid", "oid" or "_rowid_"
3202   **        and there is no explicitly declared IPK column.
3203   **
3204   **     2. The table is not a view and the column name identified an
3205   **        explicitly declared column. Copy meta information from *pCol.
3206   */
3207   if( pCol ){
3208     zDataType = pCol->zType;
3209     zCollSeq = pCol->zColl;
3210     notnull = pCol->notNull!=0;
3211     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
3212     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
3213   }else{
3214     zDataType = "INTEGER";
3215     primarykey = 1;
3216   }
3217   if( !zCollSeq ){
3218     zCollSeq = "BINARY";
3219   }
3220 
3221 error_out:
3222   sqlite3BtreeLeaveAll(db);
3223 
3224   /* Whether the function call succeeded or failed, set the output parameters
3225   ** to whatever their local counterparts contain. If an error did occur,
3226   ** this has the effect of zeroing all output parameters.
3227   */
3228   if( pzDataType ) *pzDataType = zDataType;
3229   if( pzCollSeq ) *pzCollSeq = zCollSeq;
3230   if( pNotNull ) *pNotNull = notnull;
3231   if( pPrimaryKey ) *pPrimaryKey = primarykey;
3232   if( pAutoinc ) *pAutoinc = autoinc;
3233 
3234   if( SQLITE_OK==rc && !pTab ){
3235     sqlite3DbFree(db, zErrMsg);
3236     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
3237         zColumnName);
3238     rc = SQLITE_ERROR;
3239   }
3240   sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
3241   sqlite3DbFree(db, zErrMsg);
3242   rc = sqlite3ApiExit(db, rc);
3243   sqlite3_mutex_leave(db->mutex);
3244   return rc;
3245 }
3246 
3247 /*
3248 ** Sleep for a little while.  Return the amount of time slept.
3249 */
3250 int sqlite3_sleep(int ms){
3251   sqlite3_vfs *pVfs;
3252   int rc;
3253   pVfs = sqlite3_vfs_find(0);
3254   if( pVfs==0 ) return 0;
3255 
3256   /* This function works in milliseconds, but the underlying OsSleep()
3257   ** API uses microseconds. Hence the 1000's.
3258   */
3259   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
3260   return rc;
3261 }
3262 
3263 /*
3264 ** Enable or disable the extended result codes.
3265 */
3266 int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
3267 #ifdef SQLITE_ENABLE_API_ARMOR
3268   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3269 #endif
3270   sqlite3_mutex_enter(db->mutex);
3271   db->errMask = onoff ? 0xffffffff : 0xff;
3272   sqlite3_mutex_leave(db->mutex);
3273   return SQLITE_OK;
3274 }
3275 
3276 /*
3277 ** Invoke the xFileControl method on a particular database.
3278 */
3279 int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
3280   int rc = SQLITE_ERROR;
3281   Btree *pBtree;
3282 
3283 #ifdef SQLITE_ENABLE_API_ARMOR
3284   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
3285 #endif
3286   sqlite3_mutex_enter(db->mutex);
3287   pBtree = sqlite3DbNameToBtree(db, zDbName);
3288   if( pBtree ){
3289     Pager *pPager;
3290     sqlite3_file *fd;
3291     sqlite3BtreeEnter(pBtree);
3292     pPager = sqlite3BtreePager(pBtree);
3293     assert( pPager!=0 );
3294     fd = sqlite3PagerFile(pPager);
3295     assert( fd!=0 );
3296     if( op==SQLITE_FCNTL_FILE_POINTER ){
3297       *(sqlite3_file**)pArg = fd;
3298       rc = SQLITE_OK;
3299     }else if( fd->pMethods ){
3300       rc = sqlite3OsFileControl(fd, op, pArg);
3301     }else{
3302       rc = SQLITE_NOTFOUND;
3303     }
3304     sqlite3BtreeLeave(pBtree);
3305   }
3306   sqlite3_mutex_leave(db->mutex);
3307   return rc;
3308 }
3309 
3310 /*
3311 ** Interface to the testing logic.
3312 */
3313 int sqlite3_test_control(int op, ...){
3314   int rc = 0;
3315 #ifndef SQLITE_OMIT_BUILTIN_TEST
3316   va_list ap;
3317   va_start(ap, op);
3318   switch( op ){
3319 
3320     /*
3321     ** Save the current state of the PRNG.
3322     */
3323     case SQLITE_TESTCTRL_PRNG_SAVE: {
3324       sqlite3PrngSaveState();
3325       break;
3326     }
3327 
3328     /*
3329     ** Restore the state of the PRNG to the last state saved using
3330     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
3331     ** this verb acts like PRNG_RESET.
3332     */
3333     case SQLITE_TESTCTRL_PRNG_RESTORE: {
3334       sqlite3PrngRestoreState();
3335       break;
3336     }
3337 
3338     /*
3339     ** Reset the PRNG back to its uninitialized state.  The next call
3340     ** to sqlite3_randomness() will reseed the PRNG using a single call
3341     ** to the xRandomness method of the default VFS.
3342     */
3343     case SQLITE_TESTCTRL_PRNG_RESET: {
3344       sqlite3_randomness(0,0);
3345       break;
3346     }
3347 
3348     /*
3349     **  sqlite3_test_control(BITVEC_TEST, size, program)
3350     **
3351     ** Run a test against a Bitvec object of size.  The program argument
3352     ** is an array of integers that defines the test.  Return -1 on a
3353     ** memory allocation error, 0 on success, or non-zero for an error.
3354     ** See the sqlite3BitvecBuiltinTest() for additional information.
3355     */
3356     case SQLITE_TESTCTRL_BITVEC_TEST: {
3357       int sz = va_arg(ap, int);
3358       int *aProg = va_arg(ap, int*);
3359       rc = sqlite3BitvecBuiltinTest(sz, aProg);
3360       break;
3361     }
3362 
3363     /*
3364     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
3365     **
3366     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
3367     ** if xCallback is not NULL.
3368     **
3369     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
3370     ** is called immediately after installing the new callback and the return
3371     ** value from sqlite3FaultSim(0) becomes the return from
3372     ** sqlite3_test_control().
3373     */
3374     case SQLITE_TESTCTRL_FAULT_INSTALL: {
3375       /* MSVC is picky about pulling func ptrs from va lists.
3376       ** http://support.microsoft.com/kb/47961
3377       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
3378       */
3379       typedef int(*TESTCALLBACKFUNC_t)(int);
3380       sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
3381       rc = sqlite3FaultSim(0);
3382       break;
3383     }
3384 
3385     /*
3386     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
3387     **
3388     ** Register hooks to call to indicate which malloc() failures
3389     ** are benign.
3390     */
3391     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
3392       typedef void (*void_function)(void);
3393       void_function xBenignBegin;
3394       void_function xBenignEnd;
3395       xBenignBegin = va_arg(ap, void_function);
3396       xBenignEnd = va_arg(ap, void_function);
3397       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
3398       break;
3399     }
3400 
3401     /*
3402     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
3403     **
3404     ** Set the PENDING byte to the value in the argument, if X>0.
3405     ** Make no changes if X==0.  Return the value of the pending byte
3406     ** as it existing before this routine was called.
3407     **
3408     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
3409     ** an incompatible database file format.  Changing the PENDING byte
3410     ** while any database connection is open results in undefined and
3411     ** deleterious behavior.
3412     */
3413     case SQLITE_TESTCTRL_PENDING_BYTE: {
3414       rc = PENDING_BYTE;
3415 #ifndef SQLITE_OMIT_WSD
3416       {
3417         unsigned int newVal = va_arg(ap, unsigned int);
3418         if( newVal ) sqlite3PendingByte = newVal;
3419       }
3420 #endif
3421       break;
3422     }
3423 
3424     /*
3425     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
3426     **
3427     ** This action provides a run-time test to see whether or not
3428     ** assert() was enabled at compile-time.  If X is true and assert()
3429     ** is enabled, then the return value is true.  If X is true and
3430     ** assert() is disabled, then the return value is zero.  If X is
3431     ** false and assert() is enabled, then the assertion fires and the
3432     ** process aborts.  If X is false and assert() is disabled, then the
3433     ** return value is zero.
3434     */
3435     case SQLITE_TESTCTRL_ASSERT: {
3436       volatile int x = 0;
3437       assert( (x = va_arg(ap,int))!=0 );
3438       rc = x;
3439       break;
3440     }
3441 
3442 
3443     /*
3444     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
3445     **
3446     ** This action provides a run-time test to see how the ALWAYS and
3447     ** NEVER macros were defined at compile-time.
3448     **
3449     ** The return value is ALWAYS(X).
3450     **
3451     ** The recommended test is X==2.  If the return value is 2, that means
3452     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
3453     ** default setting.  If the return value is 1, then ALWAYS() is either
3454     ** hard-coded to true or else it asserts if its argument is false.
3455     ** The first behavior (hard-coded to true) is the case if
3456     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
3457     ** behavior (assert if the argument to ALWAYS() is false) is the case if
3458     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
3459     **
3460     ** The run-time test procedure might look something like this:
3461     **
3462     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
3463     **      // ALWAYS() and NEVER() are no-op pass-through macros
3464     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
3465     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
3466     **    }else{
3467     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
3468     **    }
3469     */
3470     case SQLITE_TESTCTRL_ALWAYS: {
3471       int x = va_arg(ap,int);
3472       rc = ALWAYS(x);
3473       break;
3474     }
3475 
3476     /*
3477     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
3478     **
3479     ** The integer returned reveals the byte-order of the computer on which
3480     ** SQLite is running:
3481     **
3482     **       1     big-endian,    determined at run-time
3483     **      10     little-endian, determined at run-time
3484     **  432101     big-endian,    determined at compile-time
3485     **  123410     little-endian, determined at compile-time
3486     */
3487     case SQLITE_TESTCTRL_BYTEORDER: {
3488       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
3489       break;
3490     }
3491 
3492     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
3493     **
3494     ** Set the nReserve size to N for the main database on the database
3495     ** connection db.
3496     */
3497     case SQLITE_TESTCTRL_RESERVE: {
3498       sqlite3 *db = va_arg(ap, sqlite3*);
3499       int x = va_arg(ap,int);
3500       sqlite3_mutex_enter(db->mutex);
3501       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
3502       sqlite3_mutex_leave(db->mutex);
3503       break;
3504     }
3505 
3506     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
3507     **
3508     ** Enable or disable various optimizations for testing purposes.  The
3509     ** argument N is a bitmask of optimizations to be disabled.  For normal
3510     ** operation N should be 0.  The idea is that a test program (like the
3511     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
3512     ** with various optimizations disabled to verify that the same answer
3513     ** is obtained in every case.
3514     */
3515     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
3516       sqlite3 *db = va_arg(ap, sqlite3*);
3517       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
3518       break;
3519     }
3520 
3521 #ifdef SQLITE_N_KEYWORD
3522     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
3523     **
3524     ** If zWord is a keyword recognized by the parser, then return the
3525     ** number of keywords.  Or if zWord is not a keyword, return 0.
3526     **
3527     ** This test feature is only available in the amalgamation since
3528     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
3529     ** is built using separate source files.
3530     */
3531     case SQLITE_TESTCTRL_ISKEYWORD: {
3532       const char *zWord = va_arg(ap, const char*);
3533       int n = sqlite3Strlen30(zWord);
3534       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
3535       break;
3536     }
3537 #endif
3538 
3539     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
3540     **
3541     ** Pass pFree into sqlite3ScratchFree().
3542     ** If sz>0 then allocate a scratch buffer into pNew.
3543     */
3544     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
3545       void *pFree, **ppNew;
3546       int sz;
3547       sz = va_arg(ap, int);
3548       ppNew = va_arg(ap, void**);
3549       pFree = va_arg(ap, void*);
3550       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
3551       sqlite3ScratchFree(pFree);
3552       break;
3553     }
3554 
3555     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
3556     **
3557     ** If parameter onoff is non-zero, configure the wrappers so that all
3558     ** subsequent calls to localtime() and variants fail. If onoff is zero,
3559     ** undo this setting.
3560     */
3561     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
3562       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
3563       break;
3564     }
3565 
3566     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
3567     **
3568     ** Set or clear a flag that indicates that the database file is always well-
3569     ** formed and never corrupt.  This flag is clear by default, indicating that
3570     ** database files might have arbitrary corruption.  Setting the flag during
3571     ** testing causes certain assert() statements in the code to be activated
3572     ** that demonstrat invariants on well-formed database files.
3573     */
3574     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
3575       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
3576       break;
3577     }
3578 
3579 
3580     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
3581     **
3582     ** Set the VDBE coverage callback function to xCallback with context
3583     ** pointer ptr.
3584     */
3585     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
3586 #ifdef SQLITE_VDBE_COVERAGE
3587       typedef void (*branch_callback)(void*,int,u8,u8);
3588       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
3589       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
3590 #endif
3591       break;
3592     }
3593 
3594     /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
3595     case SQLITE_TESTCTRL_SORTER_MMAP: {
3596       sqlite3 *db = va_arg(ap, sqlite3*);
3597       db->nMaxSorterMmap = va_arg(ap, int);
3598       break;
3599     }
3600 
3601     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
3602     **
3603     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
3604     ** not.
3605     */
3606     case SQLITE_TESTCTRL_ISINIT: {
3607       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
3608       break;
3609     }
3610 
3611     /*   sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
3612     **
3613     ** This test control is used to create imposter tables.  "db" is a pointer
3614     ** to the database connection.  dbName is the database name (ex: "main" or
3615     ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
3616     ** or off.  "tnum" is the root page of the b-tree to which the imposter
3617     ** table should connect.
3618     **
3619     ** Enable imposter mode only when the schema has already been parsed.  Then
3620     ** run a single CREATE TABLE statement to construct the imposter table in the
3621     ** parsed schema.  Then turn imposter mode back off again.
3622     **
3623     ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
3624     ** the schema to be reparsed the next time it is needed.  This has the
3625     ** effect of erasing all imposter tables.
3626     */
3627     case SQLITE_TESTCTRL_IMPOSTER: {
3628       sqlite3 *db = va_arg(ap, sqlite3*);
3629       db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
3630       db->init.busy = db->init.imposterTable = va_arg(ap,int);
3631       db->init.newTnum = va_arg(ap,int);
3632       if( db->init.busy==0 && db->init.newTnum>0 ){
3633         sqlite3ResetAllSchemasOfConnection(db);
3634       }
3635       break;
3636     }
3637   }
3638   va_end(ap);
3639 #endif /* SQLITE_OMIT_BUILTIN_TEST */
3640   return rc;
3641 }
3642 
3643 /*
3644 ** This is a utility routine, useful to VFS implementations, that checks
3645 ** to see if a database file was a URI that contained a specific query
3646 ** parameter, and if so obtains the value of the query parameter.
3647 **
3648 ** The zFilename argument is the filename pointer passed into the xOpen()
3649 ** method of a VFS implementation.  The zParam argument is the name of the
3650 ** query parameter we seek.  This routine returns the value of the zParam
3651 ** parameter if it exists.  If the parameter does not exist, this routine
3652 ** returns a NULL pointer.
3653 */
3654 const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
3655   if( zFilename==0 || zParam==0 ) return 0;
3656   zFilename += sqlite3Strlen30(zFilename) + 1;
3657   while( zFilename[0] ){
3658     int x = strcmp(zFilename, zParam);
3659     zFilename += sqlite3Strlen30(zFilename) + 1;
3660     if( x==0 ) return zFilename;
3661     zFilename += sqlite3Strlen30(zFilename) + 1;
3662   }
3663   return 0;
3664 }
3665 
3666 /*
3667 ** Return a boolean value for a query parameter.
3668 */
3669 int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
3670   const char *z = sqlite3_uri_parameter(zFilename, zParam);
3671   bDflt = bDflt!=0;
3672   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
3673 }
3674 
3675 /*
3676 ** Return a 64-bit integer value for a query parameter.
3677 */
3678 sqlite3_int64 sqlite3_uri_int64(
3679   const char *zFilename,    /* Filename as passed to xOpen */
3680   const char *zParam,       /* URI parameter sought */
3681   sqlite3_int64 bDflt       /* return if parameter is missing */
3682 ){
3683   const char *z = sqlite3_uri_parameter(zFilename, zParam);
3684   sqlite3_int64 v;
3685   if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
3686     bDflt = v;
3687   }
3688   return bDflt;
3689 }
3690 
3691 /*
3692 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
3693 */
3694 Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
3695   int i;
3696   for(i=0; i<db->nDb; i++){
3697     if( db->aDb[i].pBt
3698      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
3699     ){
3700       return db->aDb[i].pBt;
3701     }
3702   }
3703   return 0;
3704 }
3705 
3706 /*
3707 ** Return the filename of the database associated with a database
3708 ** connection.
3709 */
3710 const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
3711   Btree *pBt;
3712 #ifdef SQLITE_ENABLE_API_ARMOR
3713   if( !sqlite3SafetyCheckOk(db) ){
3714     (void)SQLITE_MISUSE_BKPT;
3715     return 0;
3716   }
3717 #endif
3718   pBt = sqlite3DbNameToBtree(db, zDbName);
3719   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
3720 }
3721 
3722 /*
3723 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
3724 ** no such database exists.
3725 */
3726 int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
3727   Btree *pBt;
3728 #ifdef SQLITE_ENABLE_API_ARMOR
3729   if( !sqlite3SafetyCheckOk(db) ){
3730     (void)SQLITE_MISUSE_BKPT;
3731     return -1;
3732   }
3733 #endif
3734   pBt = sqlite3DbNameToBtree(db, zDbName);
3735   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
3736 }
3737