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